Introduce lazy pointers

This commit is contained in:
Andrea Marco Sartori 2023-03-20 19:26:48 +10:00
parent f930423627
commit 8a69cabfd8
2 changed files with 44 additions and 2 deletions

View File

@ -64,6 +64,7 @@ final class JsonParser implements IteratorAggregate
try { try {
yield from $this->parser; yield from $this->parser;
} catch (SyntaxException $e) { } catch (SyntaxException $e) {
$e->setPosition($this->parser->position());
call_user_func($this->config->onSyntaxError, $e); call_user_func($this->config->onSyntaxError, $e);
} }
} }
@ -92,7 +93,36 @@ final class JsonParser implements IteratorAggregate
*/ */
public function pointer(string $pointer, Closure $callback = null): self public function pointer(string $pointer, Closure $callback = null): self
{ {
$this->config->pointers->add(new Pointer($pointer, $callback)); $this->config->pointers->add(new Pointer($pointer, false, $callback));
return $this;
}
/**
* Set the lazy JSON pointers
*
* @param string[]|array<string, Closure> $pointers
* @return self
*/
public function lazyPointers(array $pointers): self
{
foreach ($pointers as $pointer => $callback) {
$callback instanceof Closure ? $this->lazyPointer($pointer, $callback) : $this->lazyPointer($callback);
}
return $this;
}
/**
* Set a lazy JSON pointer
*
* @param string $pointer
* @param Closure|null $callback
* @return self
*/
public function lazyPointer(string $pointer, Closure $callback = null): self
{
$this->config->pointers->add(new Pointer($pointer, true, $callback));
return $this; return $this;
} }

View File

@ -50,9 +50,10 @@ final class Pointer implements Stringable
* Instantiate the class. * Instantiate the class.
* *
* @param string $pointer * @param string $pointer
* @param bool $isLazy
* @param Closure|null $callback * @param Closure|null $callback
*/ */
public function __construct(private string $pointer, Closure $callback = null) public function __construct(private string $pointer, private bool $isLazy = false, Closure $callback = null)
{ {
$this->referenceTokens = $this->toReferenceTokens(); $this->referenceTokens = $this->toReferenceTokens();
$this->depth = count($this->referenceTokens); $this->depth = count($this->referenceTokens);
@ -76,6 +77,16 @@ final class Pointer implements Stringable
return array_slice($referenceTokens, 1); return array_slice($referenceTokens, 1);
} }
/**
* Determine whether the pointer is lazy
*
* @return bool
*/
public function isLazy(): bool
{
return $this->isLazy;
}
/** /**
* Retrieve the reference tokens * Retrieve the reference tokens
* *
@ -148,6 +159,7 @@ final class Pointer implements Stringable
*/ */
public function includesTree(Tree $tree): bool public function includesTree(Tree $tree): bool
{ {
// if ($this->pointer == '' && !$this->isLazy) {
if ($this->pointer == '') { if ($this->pointer == '') {
return true; return true;
} }