mirror of
https://github.com/cerbero90/json-parser.git
synced 2025-05-06 09:25:18 +02:00
Implement pointers collection
This commit is contained in:
parent
b2611c4bf1
commit
d6297238ad
@ -2,13 +2,14 @@
|
||||
|
||||
namespace Cerbero\JsonParser\Pointers;
|
||||
|
||||
use Stringable;
|
||||
use Cerbero\JsonParser\Tree;
|
||||
use Countable;
|
||||
|
||||
/**
|
||||
* The JSON pointers collection.
|
||||
*
|
||||
*/
|
||||
class Pointers
|
||||
class Pointers implements Countable
|
||||
{
|
||||
/**
|
||||
* The JSON pointers collection.
|
||||
@ -17,6 +18,20 @@ class Pointers
|
||||
*/
|
||||
protected array $pointers;
|
||||
|
||||
/**
|
||||
* The default pointer.
|
||||
*
|
||||
* @var Pointer
|
||||
*/
|
||||
protected Pointer $defaultPointer;
|
||||
|
||||
/**
|
||||
* The list of pointers that were found within the JSON.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected array $found = [];
|
||||
|
||||
/**
|
||||
* Instantiate the class.
|
||||
*
|
||||
@ -25,5 +40,49 @@ class Pointers
|
||||
public function __construct(Pointer ...$pointers)
|
||||
{
|
||||
$this->pointers = $pointers;
|
||||
$this->defaultPointer = new NullPointer();
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the number of JSON pointers
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function count(): int
|
||||
{
|
||||
return count($this->pointers);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the pointer matching the given tree
|
||||
*
|
||||
* @param Tree $tree
|
||||
* @return Pointer
|
||||
*/
|
||||
public function matchTree(Tree $tree): Pointer
|
||||
{
|
||||
$pointers = [];
|
||||
|
||||
foreach ($this->pointers as $pointer) {
|
||||
foreach ($tree as $depth => $node) {
|
||||
if (!$pointer->depthMatchesNode($depth, $node)) {
|
||||
continue 2;
|
||||
} elseif (!isset($pointers[$depth])) {
|
||||
$pointers[$depth] = $pointer;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return end($pointers) ?: $this->defaultPointer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine whether all pointers were found within the JSON
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function wereFound(): bool
|
||||
{
|
||||
return count($this->pointers) == count($this->found);
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user