diff --git a/src/Lexer.php b/src/Lexer.php index d3f6903..dac4206 100644 --- a/src/Lexer.php +++ b/src/Lexer.php @@ -17,13 +17,6 @@ use Traversable; */ final class Lexer implements IteratorAggregate { - /** - * The tokenizer. - * - * @var Tokenizer - */ - private Tokenizer $tokenizer; - /** * The buffer to yield. * @@ -52,7 +45,6 @@ final class Lexer implements IteratorAggregate */ public function __construct(private Source $source) { - $this->tokenizer = new Tokenizer(); } /** @@ -100,12 +92,12 @@ final class Lexer implements IteratorAggregate } if ($this->buffer != '') { - yield $this->tokenizer->toToken($this->buffer); + yield Tokenizer::instance()->toToken($this->buffer); $this->buffer = ''; } if (isset(Tokens::DELIMITERS[$character])) { - yield $this->tokenizer->toToken($character); + yield Tokenizer::instance()->toToken($character); } } } diff --git a/src/Tokens/Tokenizer.php b/src/Tokens/Tokenizer.php index 924ebef..6b6c556 100644 --- a/src/Tokens/Tokenizer.php +++ b/src/Tokens/Tokenizer.php @@ -8,36 +8,51 @@ namespace Cerbero\JsonParser\Tokens; */ final class Tokenizer { + /** + * The singleton instance. + * + * @var static + */ + private static self $instance; + /** * The map of token instances by type. * * @var array */ - private static array $tokensMap; + private array $tokensMap; /** * Instantiate the class. * */ - public function __construct() + private function __construct() { - static::$tokensMap ??= $this->hydrateTokensMap(); + $this->setTokensMap(); } /** - * Retrieve the hydrated tokens map + * Retrieve the singleton instance * - * @return array + * @return static */ - private function hydrateTokensMap(): array + public static function instance(): static { - $map = $instances = []; + return static::$instance ??= new static(); + } + + /** + * Set the tokens map + * + * @return void + */ + private function setTokensMap(): void + { + $instances = []; foreach (Tokens::MAP as $type => $class) { - $map[$type] = $instances[$class] ??= new $class(); + $this->tokensMap[$type] = $instances[$class] ??= new $class(); } - - return $map; } /** @@ -51,6 +66,6 @@ final class Tokenizer $character = $value[0]; $type = Tokens::TYPES[$character]; - return static::$tokensMap[$type]->setValue($value); + return $this->tokensMap[$type]->setValue($value); } }