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

JsonSchemaInterceptor   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 29
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 4

Test Coverage

Coverage 94.12%

Importance

Changes 1
Bugs 0 Features 1
Metric Value
wmc 5
c 1
b 0
f 1
lcom 0
cbo 4
dl 0
loc 29
ccs 16
cts 17
cp 0.9412
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
B invoke() 0 23 5
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