1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Class for validation JSON Patch for target document using JSON Pointer |
4
|
|
|
*/ |
5
|
|
|
|
6
|
|
|
namespace Graviton\RestBundle\Service; |
7
|
|
|
|
8
|
|
|
use Graviton\ExceptionBundle\Exception\InvalidJsonPatchException; |
9
|
|
|
use Rs\Json\Pointer; |
10
|
|
|
use Rs\Json\Pointer\InvalidPointerException; |
11
|
|
|
use Rs\Json\Pointer\NonexistentValueReferencedException; |
12
|
|
|
|
13
|
|
|
class JsonPatchValidator |
14
|
|
|
{ |
15
|
|
|
/** |
16
|
|
|
* @param string $targetDocument JSON of target document |
17
|
|
|
* @param string $jsonPatch |
18
|
|
|
* @return boolean |
19
|
|
|
* @throws InvalidJsonPatchException |
20
|
|
|
*/ |
21
|
18 |
|
public function validate($targetDocument, $jsonPatch) |
|
|
|
|
22
|
|
|
{ |
23
|
18 |
|
$operations = json_decode($jsonPatch, true); |
24
|
18 |
|
$pointer = new Pointer($targetDocument); |
25
|
18 |
|
foreach ($operations as $op) { |
26
|
|
|
try { |
27
|
18 |
|
$pointer->get($op['path']); |
28
|
16 |
|
} catch (InvalidPointerException $e) { |
29
|
6 |
|
throw new InvalidJsonPatchException($e); |
30
|
8 |
|
} catch (NonexistentValueReferencedException $e) { |
31
|
8 |
|
$pathParts = explode('/', $op['path']); |
32
|
8 |
|
$lastPart = end($pathParts); |
33
|
|
|
|
34
|
8 |
|
if (is_numeric($lastPart)) { |
35
|
|
|
/** |
36
|
|
|
* JSON Pointer library throws an Exception when INDEX is equal to number of elements in array |
37
|
|
|
* But JSON Patch allow this as described in RFC |
38
|
|
|
* |
39
|
|
|
* http://tools.ietf.org/html/rfc6902#section-4.1 |
40
|
|
|
* "The specified index MUST NOT be greater than the number of elements in the array." |
41
|
|
|
*/ |
42
|
|
|
|
43
|
|
|
// Try to check previous element |
44
|
6 |
|
array_pop($pathParts); |
45
|
6 |
|
array_push($pathParts, $lastPart - 1); |
46
|
|
|
|
47
|
|
|
try { |
48
|
6 |
|
$pointer->get(implode('/', $pathParts)); |
49
|
5 |
|
} catch (NonexistentValueReferencedException $e) { |
50
|
8 |
|
throw new InvalidJsonPatchException($e); |
51
|
|
|
} |
52
|
1 |
|
} |
53
|
|
|
} |
54
|
4 |
|
} |
55
|
|
|
|
56
|
8 |
|
return true; |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
|
This check examines a number of code elements and verifies that they conform to the given naming conventions.
You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.