Skip to content

Commit

Permalink
Replace singleton implementation to support PHP 8 (#276)
Browse files Browse the repository at this point in the history
  • Loading branch information
OndraM committed Mar 8, 2021
1 parent b842713 commit 470b1f4
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 4 deletions.
1 change: 0 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@
"beberlei/assert": "^3.0",
"clue/graph": "^0.9.2",
"doctrine/inflector": "^2.0.3",
"florianwolters/component-util-singleton": "^0.3.2",
"graphp/algorithms": "^0.8.2",
"hanneskod/classtools": "^1.2",
"ondram/ci-detector": "^4.0",
Expand Down
8 changes: 8 additions & 0 deletions src-tests/ConfigProviderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -138,4 +138,12 @@ public function testShouldFailIfSettingCustomConfigurationOptionsAfterFirstInsta
// This should fail, as the Config instance was already created
$config->setCustomConfigurationOptions(['CUSTOM_OPTION']);
}

public function testShouldAlwaysGetTheSameSingletonInstance(): void
{
$firstInstance = ConfigProvider::getInstance();
$secondInstance = ConfigProvider::getInstance();

$this->assertSame($firstInstance, $secondInstance);
}
}
32 changes: 29 additions & 3 deletions src/ConfigProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,11 @@

use Doctrine\Inflector\InflectorFactory;
use Doctrine\Inflector\Language;
use FlorianWolters\Component\Util\Singleton\SingletonTrait;

/**
* Provide access to global configuration (from within the tests).
* The configuration is immutable - ie. cannot be altered after it is used for the first time.
*
* @method static ConfigProvider getInstance()
* @property-read string $browserName
* @property-read string $env
* @property-read string $serverUrl
Expand All @@ -21,13 +19,27 @@
*/
class ConfigProvider
{
use SingletonTrait;
/** @var ConfigProvider */
private static $instance;

/** @var array Configuration options and theirs values */
private $config;
/** @var array Array of custom configuration options that should be added to the default ones */
private $customConfigurationOptions = [];

final protected function __construct()
{
}

public static function getInstance(): self
{
if (self::$instance === null) {
self::$instance = new static();
}

return self::$instance;
}

public function __get(string $name)
{
$this->initialize();
Expand Down Expand Up @@ -133,4 +145,18 @@ private function retrieveConfigurationValues(array $options): array

return $outputValues;
}

/**
* Prevent cloning of the singleton
*/
private function __clone()
{
}

/**
* Prevent unserializing the singleton
*/
private function __wakeup(): void
{
}
}

0 comments on commit 470b1f4

Please sign in to comment.