1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* This file is part of the BEAR.Resource package. |
4
|
|
|
* |
5
|
|
|
* @license http://opensource.org/licenses/MIT MIT |
6
|
|
|
*/ |
7
|
|
|
namespace BEAR\Resource\Interceptor; |
8
|
|
|
|
9
|
|
|
use BEAR\Resource\Code; |
10
|
|
|
use BEAR\Resource\Exception\JsonSchemaErrorException; |
11
|
|
|
use BEAR\Resource\Exception\JsonSchemaException; |
12
|
|
|
use JsonSchema\Validator; |
13
|
|
|
use Ray\Aop\MethodInterceptor; |
14
|
|
|
use Ray\Aop\MethodInvocation; |
15
|
|
|
use Ray\Aop\WeavedInterface; |
16
|
|
|
|
17
|
|
|
final class JsonSchemaInterceptor implements MethodInterceptor |
18
|
|
|
{ |
19
|
|
|
/** |
20
|
|
|
* {@inheritdoc} |
21
|
|
|
*/ |
22
|
1 |
|
public function invoke(MethodInvocation $invocation) |
23
|
|
|
{ |
24
|
1 |
|
$result = $invocation->proceed(); |
25
|
1 |
|
$object = $invocation->getThis(); |
26
|
|
|
/* @var $result \BEAR\Resource\ResourceObject */ |
27
|
1 |
|
$ref = new \ReflectionClass($object); |
28
|
1 |
|
$thisFile = $object instanceof WeavedInterface ? $thisFile = $ref->getParentClass()->getFileName() : $ref->getFileName(); |
29
|
1 |
|
$schemaFile = str_replace('.php', '.json', $thisFile); |
30
|
1 |
|
$validator = new Validator; |
31
|
1 |
|
$data = (object) $result->body; |
32
|
1 |
|
$validator->validate($data, (object) ['$ref' => 'file://' . $schemaFile]); |
33
|
1 |
|
$isValid = $validator->isValid(); |
34
|
1 |
|
if ($isValid === true) { |
35
|
|
|
return $result; |
36
|
|
|
} |
37
|
|
|
|
38
|
1 |
|
$e = null; |
39
|
1 |
|
foreach ($validator->getErrors() as $error) { |
40
|
1 |
|
$msg = sprintf('[%s] %s', $error['property'], $error['message']); |
41
|
1 |
|
$e = $e ? new JsonSchemaErrorException($msg, 0, $e) : new JsonSchemaErrorException($msg); |
42
|
|
|
} |
43
|
1 |
|
throw new JsonSchemaException($schemaFile, Code::ERROR, $e); |
44
|
|
|
} |
45
|
|
|
} |
46
|
|
|
|