Skip to content

Commit

Permalink
Create singleton client
Browse files Browse the repository at this point in the history
  • Loading branch information
cerbero90 committed Jan 20, 2024
1 parent 4a9758f commit d53537d
Showing 1 changed file with 72 additions and 0 deletions.
72 changes: 72 additions & 0 deletions src/Services/Client.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
<?php

declare(strict_types=1);

namespace Cerbero\LazyJsonPages\Services;

use GuzzleHttp\Client as Guzzle;
use GuzzleHttp\RequestOptions;

/**
* The client singleton.
*/
final class Client
{
/**
* The default options.
*
* @var array<string, mixed>
*/
private static array $defaultOptions = [
RequestOptions::STREAM => true,
RequestOptions::HEADERS => [
'Accept' => 'application/json',
'Content-Type' => 'application/json',
],
];

/**
* The custom options.
*/
private static array $options = [];

/**
* The Guzzle client instance.
*/
private static ?Guzzle $guzzle = null;

/**
* Instantiate the class.
*/
private function __construct()
{
// disable the constructor
}

/**
* Set the Guzzle client options.
*/
public static function configure(array $options): void
{
self::$options = array_replace_recursive(self::$options, $options);
}

/**
* Retrieve the Guzzle client instance.
*/
public static function instance(): Guzzle
{
return self::$guzzle ??= new Guzzle(
array_replace_recursive(self::$defaultOptions, self::$options),
);
}

/**
* Clean up the static values.
*/
public static function reset(): void
{
self::$guzzle = null;
self::$options = [];
}
}

0 comments on commit d53537d

Please sign in to comment.