Completed
Push — 1.x ( 494d7e...e73fc7 )
by Akihito
03:28 queued 11s
created

JsonSchemaInterceptor::throwJsonSchemaException()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 6
cts 6
cp 1
rs 9.9332
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace BEAR\Resource\Interceptor;
6
7
use BEAR\Resource\Annotation\JsonSchema;
8
use BEAR\Resource\Code;
9
use BEAR\Resource\Exception\JsonSchemaException;
10
use BEAR\Resource\Exception\JsonSchemaNotFoundException;
11
use BEAR\Resource\JsonSchemaExceptionHandlerInterface;
12
use BEAR\Resource\ResourceObject;
13
use function is_string;
14
use JsonSchema\Constraints\Constraint;
15
use JsonSchema\Validator;
16
use Ray\Aop\MethodInterceptor;
17
use Ray\Aop\MethodInvocation;
18
use Ray\Aop\ReflectionMethod;
19
use Ray\Aop\WeavedInterface;
20
use Ray\Di\Di\Named;
21
22
final class JsonSchemaInterceptor implements MethodInterceptor
23
{
24
    /**
25
     * @var string
26
     */
27
    private $schemaDir;
28
29
    /**
30
     * @var string
31
     */
32
    private $validateDir;
33
34
    /**
35
     * @var null|string
36
     */
37
    private $schemaHost;
38
39
    /**
40
     * @var JsonSchemaExceptionHandlerInterface
41
     */
42 14
    private $handler;
43
44 14
    /**
45 14
     * @Named("schemaDir=json_schema_dir,validateDir=json_validate_dir,schemaHost=json_schema_host")
46 14
     */
47 14
    public function __construct(string $schemaDir, string $validateDir, JsonSchemaExceptionHandlerInterface $handler, string $schemaHost = null)
48
    {
49
        $this->schemaDir = $schemaDir;
50
        $this->validateDir = $validateDir;
51
        $this->schemaHost = $schemaHost;
52 14
        $this->handler = $handler;
53
    }
54
55 14
    /**
56
     * {@inheritdoc}
57 14
     */
58 14
    public function invoke(MethodInvocation $invocation)
59 6
    {
60 6
        /** @var ReflectionMethod $method */
61
        $method = $invocation->getMethod();
62
        /** @var JsonSchema $jsonSchema */
63 12
        $jsonSchema = $method->getAnnotation(JsonSchema::class);
64 12
        if ($jsonSchema->params) {
65 10
            $arguments = $this->getNamedArguments($invocation);
66
            $this->validateRequest($jsonSchema, $arguments);
67 6
        }
68
        /** @var ResourceObject $ro */
69
        $ro = $invocation->proceed();
70
        if ($ro->code === 200 || $ro->code == 201) {
71 6
            $this->validateResponse($ro, $jsonSchema);
72
        }
73
74 6
        return $ro;
75
    }
76 6
77 6
    private function validateRequest(JsonSchema $jsonSchema, array $arguments)
78 6
    {
79 4
        $schemaFile = $this->validateDir . '/' . $jsonSchema->params;
80
        $this->validateFileExists($schemaFile);
81 10
        $this->validate($arguments, $schemaFile);
82
    }
83 10
84 8
    private function validateResponse(ResourceObject $ro, JsonSchema $jsonSchema)
85 8
    {
86 4
        $schemaFile = $this->getSchemaFile($jsonSchema, $ro);
87
        try {
88 10
            $this->validateRo($ro, $schemaFile);
89
            if (is_string($this->schemaHost)) {
90 10
                $ro->headers['Link'] = sprintf('<%s%s>; rel="describedby"', $this->schemaHost, $jsonSchema->schema);
91 10
            }
92 10
        } catch (JsonSchemaException $e) {
93 10
            $this->handler->handle($ro, $e, $schemaFile);
94 10
        }
95 6
    }
96
97 6
    private function validateRo(ResourceObject $ro, string $schemaFile)
98 6
    {
99 6
        $validator = new Validator;
0 ignored issues
show
Unused Code introduced by
$validator is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
100 6
        $json = json_decode((string) $ro);
101
        $this->validate($json, $schemaFile);
102
    }
103 6
104
    private function validate($scanObject, $schemaFile)
105
    {
106 10
        $validator = new Validator;
107
        $schema = (object) ['$ref' => 'file://' . $schemaFile];
108 10
        $validator->validate($scanObject, $schema, Constraint::CHECK_MODE_TYPE_CAST);
109
        $isValid = $validator->isValid();
110 2
        if ($isValid) {
111 2
            return;
112 2
        }
113 2
114 2
        throw $this->throwJsonSchemaException($validator);
115
    }
116
117 8
    private function throwJsonSchemaException(Validator $validator) : JsonSchemaException
118 8
    {
119
        $errors = $validator->getErrors();
120 6
        $msg = '';
121
        foreach ($errors as $error) {
122
            $msg .= sprintf('[%s] %s; ', $error['property'], $error['message']);
123 10
        }
124
125 10
        return new JsonSchemaException($msg, Code::ERROR);
126 2
    }
127
128 8
    private function getSchemaFile(JsonSchema $jsonSchema, ResourceObject $ro) : string
129
    {
130 6
        if (! $jsonSchema->schema) {
131
            // for BC only
132 6
            $ref = new \ReflectionClass($ro);
133 6
            if (! $ref instanceof \ReflectionClass) {
134 6
                throw new \ReflectionException(get_class($ro)); // @codeCoverageIgnore
135 6
            }
136 6
            $roFileName = $ro instanceof WeavedInterface ? $roFileName = $ref->getParentClass()->getFileName() : $ref->getFileName();
137
            $bcFile = str_replace('.php', '.json', $roFileName);
138
            if (file_exists($bcFile)) {
139 6
                return $bcFile;
140
            }
141
        }
142
        $schemaFile = $this->schemaDir . '/' . $jsonSchema->schema;
143
        $this->validateFileExists($schemaFile);
144
145
        return $schemaFile;
146
    }
147
148
    private function validateFileExists(string $schemaFile)
149
    {
150
        if (! file_exists($schemaFile) || is_dir($schemaFile)) {
151
            throw new JsonSchemaNotFoundException($schemaFile);
152
        }
153
    }
154
155
    private function getNamedArguments(MethodInvocation $invocation)
156
    {
157
        $parameters = $invocation->getMethod()->getParameters();
158
        $values = $invocation->getArguments();
159
        $arguments = [];
160
        foreach ($parameters as $index => $parameter) {
161
            $arguments[$parameter->name] = $values[$index] ?? $parameter->getDefaultValue();
162
        }
163
164
        return $arguments;
165
    }
166
}
167