From ab11f4e41659f49bb743f74c2cd110d026cc48a2 Mon Sep 17 00:00:00 2001 From: Andrea Marco Sartori Date: Thu, 10 Nov 2022 21:45:56 +1000 Subject: [PATCH] Add factory method to parser --- src/JsonParser.php | 3 +-- src/Parser.php | 12 ++++++++++++ src/Sources/Source.php | 10 ++++++++++ 3 files changed, 23 insertions(+), 2 deletions(-) diff --git a/src/JsonParser.php b/src/JsonParser.php index a49aa03..89dc7f6 100644 --- a/src/JsonParser.php +++ b/src/JsonParser.php @@ -38,8 +38,7 @@ class JsonParser implements IteratorAggregate public function __construct(mixed $source) { $this->config = new Config(); - $source = AnySource::from($source, $this->config); - $this->parser = new Parser(new Lexer($source), $this->config); + $this->parser = Parser::for(AnySource::from($source, $this->config)); } /** diff --git a/src/Parser.php b/src/Parser.php index cd08f9a..00e7c53 100644 --- a/src/Parser.php +++ b/src/Parser.php @@ -3,6 +3,7 @@ namespace Cerbero\JsonParser; use Cerbero\JsonParser\Pointers\Pointers; +use Cerbero\JsonParser\Sources\Source; use Cerbero\JsonParser\Tokens\Token; use IteratorAggregate; use Traversable; @@ -39,6 +40,17 @@ class Parser implements IteratorAggregate $this->pointers = new Pointers(...$config->pointers); } + /** + * Instantiate the class statically + * + * @param Source $source + * @return static + */ + public static function for(Source $source): static + { + return new static(new Lexer($source), $source->config()); + } + /** * Retrieve the JSON fragments * diff --git a/src/Sources/Source.php b/src/Sources/Source.php index cf7cf92..317419c 100644 --- a/src/Sources/Source.php +++ b/src/Sources/Source.php @@ -87,6 +87,16 @@ abstract class Source implements IteratorAggregate } } + /** + * Retrieve the underlying configuration + * + * @return Config + */ + public function config(): Config + { + return $this->config; + } + /** * Retrieve the size of the JSON source and cache it *