Completed
Push — 1.x ( 6a818c...39b374 )
by Akihito
14s
created

JsonSchemaInterceptor::invoke()   B

Complexity

Conditions 5
Paths 8

Size

Total Lines 23
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 5.005

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 23
ccs 16
cts 17
cp 0.9412
rs 8.5906
cc 5
eloc 17
nc 8
nop 1
crap 5.005
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