mirror of
https://github.com/cerbero90/json-parser.git
synced 2025-01-17 04:58:15 +01:00
Turn Tokenizer into singleton
This commit is contained in:
parent
8b39422123
commit
3a3618a13f
@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -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<int, Token>
|
||||
*/
|
||||
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<int, Token>
|
||||
* @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);
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user