Skip to content

Path exception alternative #5

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Oct 21, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion src/JsonPatch.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ public static function import(array $data)
}

if (!is_object($operation)) {
throw new Exception( 'Invalid patch operation - should be a JSON object' );
throw new Exception('Invalid patch operation - should be a JSON object');
}

if (!isset($operation->op)) {
Expand Down Expand Up @@ -145,20 +145,26 @@ public function apply(&$original, $stopOnError = true)
$errors = array();
foreach ($this->operations as $operation) {
try {
// track the current pointer field so we can use it for a potential PathException
$pointerField = 'path';
$pathItems = JsonPointer::splitPath($operation->path);
switch (true) {
case $operation instanceof Add:
JsonPointer::add($original, $pathItems, $operation->value, $this->flags);
break;
case $operation instanceof Copy:
$pointerField = 'from';
$fromItems = JsonPointer::splitPath($operation->from);
$value = JsonPointer::get($original, $fromItems);
$pointerField = 'path';
JsonPointer::add($original, $pathItems, $value, $this->flags);
break;
case $operation instanceof Move:
$pointerField = 'from';
$fromItems = JsonPointer::splitPath($operation->from);
$value = JsonPointer::get($original, $fromItems);
JsonPointer::remove($original, $fromItems, $this->flags);
$pointerField = 'path';
JsonPointer::add($original, $pathItems, $value, $this->flags);
break;
case $operation instanceof Remove:
Expand All @@ -178,6 +184,18 @@ public function apply(&$original, $stopOnError = true)
}
break;
}
} catch (JsonPointerException $jsonPointerException) {
$pathException = new PathException(
$jsonPointerException->getMessage(),
$operation,
$pointerField,
$jsonPointerException->getCode()
);
if ($stopOnError) {
throw $pathException;
} else {
$errors[] = $pathException;
}
} catch (Exception $exception) {
if ($stopOnError) {
throw $exception;
Expand Down
30 changes: 15 additions & 15 deletions src/JsonPointer.php
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ public static function splitPath($path)
return self::splitPathURIFragment($pathItems);
} else {
if ($first !== '') {
throw new Exception('Path must start with "/": ' . $path);
throw new JsonPointerException('Path must start with "/": ' . $path);
}
return self::splitPathJsonString($pathItems);
}
Expand Down Expand Up @@ -105,15 +105,15 @@ public static function add(&$holder, $pathItems, $value, $flags = self::RECURSIV
while (null !== $key = array_shift($pathItems)) {
if ($ref instanceof \stdClass || is_object($ref)) {
if (PHP_VERSION_ID < 70100 && '' === $key) {
throw new Exception('Empty property name is not supported by PHP <7.1',
throw new JsonPointerException('Empty property name is not supported by PHP <7.1',
Exception::EMPTY_PROPERTY_NAME_UNSUPPORTED);
}

if ($flags & self::RECURSIVE_KEY_CREATION) {
$ref = &$ref->$key;
} else {
if (!isset($ref->$key) && count($pathItems)) {
throw new Exception('Non-existent path item: ' . $key);
throw new JsonPointerException('Non-existent path item: ' . $key);
} else {
$ref = &$ref->$key;
}
Expand All @@ -126,7 +126,7 @@ public static function add(&$holder, $pathItems, $value, $flags = self::RECURSIV
$ref = new \stdClass();
$ref = &$ref->{$key};
} else {
throw new Exception('Non-existent path item: ' . $key);
throw new JsonPointerException('Non-existent path item: ' . $key);
}
} elseif ([] === $ref && 0 === ($flags & self::STRICT_MODE) && false === $intKey && '-' !== $key) {
$ref = new \stdClass();
Expand All @@ -138,7 +138,7 @@ public static function add(&$holder, $pathItems, $value, $flags = self::RECURSIV
} else {
if (false === $intKey) {
if (0 === ($flags & self::TOLERATE_ASSOCIATIVE_ARRAYS)) {
throw new Exception('Invalid key for array operation');
throw new JsonPointerException('Invalid key for array operation');
}
$ref = &$ref[$key];
continue;
Expand All @@ -148,9 +148,9 @@ public static function add(&$holder, $pathItems, $value, $flags = self::RECURSIV
}
if (0 === ($flags & self::TOLERATE_ASSOCIATIVE_ARRAYS)) {
if ($intKey > count($ref) && 0 === ($flags & self::RECURSIVE_KEY_CREATION)) {
throw new Exception('Index is greater than number of items in array');
throw new JsonPointerException('Index is greater than number of items in array');
} elseif ($intKey < 0) {
throw new Exception('Negative index');
throw new JsonPointerException('Negative index');
}
}

Expand Down Expand Up @@ -203,30 +203,30 @@ public static function get($holder, $pathItems)
while (null !== $key = array_shift($pathItems)) {
if ($ref instanceof \stdClass) {
if (PHP_VERSION_ID < 70100 && '' === $key) {
throw new Exception('Empty property name is not supported by PHP <7.1',
throw new JsonPointerException('Empty property name is not supported by PHP <7.1',
Exception::EMPTY_PROPERTY_NAME_UNSUPPORTED);
}

$vars = (array)$ref;
if (self::arrayKeyExists($key, $vars)) {
$ref = self::arrayGet($key, $vars);
} else {
throw new Exception('Key not found: ' . $key);
throw new JsonPointerException('Key not found: ' . $key);
}
} elseif (is_array($ref)) {
if (self::arrayKeyExists($key, $ref)) {
$ref = $ref[$key];
} else {
throw new Exception('Key not found: ' . $key);
throw new JsonPointerException('Key not found: ' . $key);
}
} elseif (is_object($ref)) {
if (isset($ref->$key)) {
$ref = $ref->$key;
} else {
throw new Exception('Key not found: ' . $key);
throw new JsonPointerException('Key not found: ' . $key);
}
} else {
throw new Exception('Key not found: ' . $key);
throw new JsonPointerException('Key not found: ' . $key);
}
}
return $ref;
Expand Down Expand Up @@ -260,19 +260,19 @@ public static function remove(&$holder, $pathItems, $flags = 0)
if (property_exists($ref, $key)) {
$ref = &$ref->$key;
} else {
throw new Exception('Key not found: ' . $key);
throw new JsonPointerException('Key not found: ' . $key);
}
} elseif (is_object($ref)) {
if (isset($ref->$key)) {
$ref = &$ref->$key;
} else {
throw new Exception('Key not found: ' . $key);
throw new JsonPointerException('Key not found: ' . $key);
}
} else {
if (array_key_exists($key, $ref)) {
$ref = &$ref[$key];
} else {
throw new Exception('Key not found: ' . $key);
throw new JsonPointerException('Key not found: ' . $key);
}
}
}
Expand Down
5 changes: 5 additions & 0 deletions src/JsonPointerException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<?php

namespace Swaggest\JsonDiff;

class JsonPointerException extends Exception {}
51 changes: 51 additions & 0 deletions src/PathException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?php

namespace Swaggest\JsonDiff;


use Throwable;

class PathException extends Exception
{
/** @var object */
private $operation;

/** @var string */
private $field;

/**
* @param string $message
* @param object $operation
* @param string $field
* @param int $code
* @param Throwable|null $previous
*/
public function __construct(
$message,
$operation,
$field,
$code = 0,
Throwable $previous = null
)
{
parent::__construct($message, $code, $previous);
$this->operation = $operation;
$this->field = $field;
}

/**
* @return object
*/
public function getOperation()
{
return $this->operation;
}

/**
* @return string
*/
public function getField()
{
return $this->field;
}
}
86 changes: 86 additions & 0 deletions tests/src/JsonPatchTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@
use Swaggest\JsonDiff\Exception;
use Swaggest\JsonDiff\JsonDiff;
use Swaggest\JsonDiff\JsonPatch;
use Swaggest\JsonDiff\JsonPatch\OpPath;
use Swaggest\JsonDiff\MissingFieldException;
use Swaggest\JsonDiff\PatchTestOperationFailedException;
use Swaggest\JsonDiff\PathException;
use Swaggest\JsonDiff\UnknownOperationException;

class JsonPatchTest extends \PHPUnit_Framework_TestCase
Expand Down Expand Up @@ -174,4 +176,88 @@ public function testTestOperationFailed()
$this->assertSame($actualValue, $testError->getActualValue());
}

public function testPathExceptionContinueOnError()
{
$actualValue = 'xyz';
$data = array('abc' => $actualValue);
$patch = new JsonPatch();

$operation1 = new JsonPatch\Test('/abc', 'def');
$patch->op($operation1);

$operation2 = new JsonPatch\Move('/target', '/source');
$patch->op($operation2);

$errors = $patch->apply($data, false);

$this->assertInstanceOf(PatchTestOperationFailedException::class, $errors[0]);
$this->assertSame($operation1, $errors[0]->getOperation());

$this->assertInstanceOf(PathException::class, $errors[1]);
$this->assertSame($operation2, $errors[1]->getOperation());
$this->assertSame('from', $errors[1]->getField());
}

public function pathExceptionProvider() {
return [
'splitPath_path' => [
new JsonPatch\Copy('invalid/path', '/valid/from'),
'Path must start with "/": invalid/path',
'path'
],
'splitPath_from' => [
new JsonPatch\Copy('/valid/path', 'invalid/from'),
'Path must start with "/": invalid/from',
'from'
],
'add' => [
new JsonPatch\Add('/some/path', 22),
'Non-existent path item: some',
'path'
],
'get_from' => [
new JsonPatch\Copy('/target', '/source'),
'Key not found: source',
'from'
],
'get_path' => [
new JsonPatch\Replace('/some/path', 23),
'Key not found: some',
'path'
],
'remove_from' => [
new JsonPatch\Move('/target', '/source'),
'Key not found: source',
'from'
],
'remove_path' => [
new JsonPatch\Remove('/some/path'),
'Key not found: some',
'path'
]
];
}

/**
* @param OpPath $operation
* @param string $expectedMessage
* @param string $expectedField
*
* @dataProvider pathExceptionProvider
*/
public function testPathException(OpPath $operation, $expectedMessage, $expectedField) {
$data = new \stdClass();
$patch = new JsonPatch();

$patch->op($operation);

try {
$patch->apply($data );
$this->fail('PathException expected');
} catch (Exception $ex) {
$this->assertInstanceOf(PathException::class, $ex);
$this->assertEquals($expectedMessage, $ex->getMessage());
$this->assertEquals($expectedField, $ex->getField());
}
}
}
5 changes: 3 additions & 2 deletions tests/src/JsonPointerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

use Swaggest\JsonDiff\Exception;
use Swaggest\JsonDiff\JsonPointer;
use Swaggest\JsonDiff\JsonPointerException;

class JsonPointerTest extends \PHPUnit_Framework_TestCase
{
Expand All @@ -30,7 +31,7 @@ public function testProcess()

try {
$this->assertSame('null', json_encode(JsonPointer::get($json, JsonPointer::splitPath('/l1/l2/non-existent'))));
} catch (Exception $exception) {
} catch (JsonPointerException $exception) {
$this->assertSame('Key not found: non-existent', $exception->getMessage());
}

Expand Down Expand Up @@ -89,7 +90,7 @@ public function testGetSetDeleteObject()
try {
JsonPointer::get($s, ['one', 'two']);
$this->fail('Exception expected');
} catch (Exception $e) {
} catch (JsonPointerException $e) {
$this->assertEquals('Key not found: two', $e->getMessage());
}
$this->assertEquals(null, $s->one->two);
Expand Down