Throw exception on invalid pointer

This commit is contained in:
Andrea Marco Sartori 2022-11-21 00:36:08 +10:00
parent dea8a49af5
commit 2d9292a039
4 changed files with 43 additions and 0 deletions

View File

@ -0,0 +1,21 @@
<?php
namespace Cerbero\JsonParser\Exceptions;
/**
* The exception thrown when a pointer-related error occurs.
*
*/
class PointerException extends JsonParserException
{
/**
* Retrieve the exception when the given pointer is invalid
*
* @param string $pointer
* @return static
*/
public static function invalid(string $pointer): static
{
return new static("The string [$pointer] is not a valid JSON pointer", static::CODE_POINTER_INVALID);
}
}

View File

@ -3,6 +3,7 @@
namespace Cerbero\JsonParser\Pointers;
use ArrayAccess;
use Cerbero\JsonParser\Exceptions\PointerException;
use Cerbero\JsonParser\Tree;
use Stringable;
@ -44,6 +45,10 @@ class Pointer implements ArrayAccess, Stringable
*/
protected function toReferenceTokens(): array
{
if (preg_match('#^(?:/(?:(?:[^/~])|(?:~[01]))*)*$#', $this->pointer) === 0) {
throw PointerException::invalid($this->pointer);
}
$tokens = explode('/', substr($this->pointer, 1));
return array_map(fn (string $token) => str_replace(['~1', '~0'], ['/', '~'], $token), $tokens);

View File

@ -59,4 +59,14 @@ class Dataset
}
}
}
/**
* Retrieve the dataset to test invalid pointers
*
* @return Generator
*/
public static function forInvalidPointers(): Generator
{
yield from ['abc', '/foo~2', '/~', ' '];
}
}

View File

@ -1,6 +1,7 @@
<?php
use Cerbero\JsonParser\Dataset;
use Cerbero\JsonParser\Exceptions\PointerException;
use Cerbero\JsonParser\JsonParser;
it('supports single JSON pointers', function (string $json, string $pointer, array $parsed) {
@ -8,6 +9,12 @@ it('supports single JSON pointers', function (string $json, string $pointer, arr
})->with(Dataset::forSinglePointers());
it('throws an exception when providing an invalid JSON pointer', function (string $pointer) {
expect(fn () => iterator_to_array(JsonParser::parse('{}')->pointer($pointer)))
->toThrow(PointerException::class, "The string [$pointer] is not a valid JSON pointer");
})->with(Dataset::forInvalidPointers());
// it('supports multiple JSON pointers', function (string $json, array $pointers, array $parsed) {
// expect(JsonParser::parse($json)->pointer(...$pointers))->toParseTo($parsed);
// })->with(Dataset::forMultiplePointers());