Completed
Pull Request — 1.x (#162)
by Akihito
04:46
created

JsonSchemaExceptionFakeHandler   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 30
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 3
dl 0
loc 30
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A handle() 0 6 1
A fakeResponse() 0 6 1
A deepArray() 0 9 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace BEAR\Resource;
6
7
use BEAR\Resource\Exception\JsonSchemaException;
8
use JSONSchemaFaker\Faker;
9
10
class JsonSchemaExceptionFakeHandler implements JsonSchemaExceptionHandlerInterface
11
{
12
    const X_FAKE_JSON = 'X-Fake-JSON';
13
14
    const X_JSON_SCHEMA_EXCEPTION = 'X-JSON-Schema-Exception';
15
16
    public function handle(ResourceObject $ro, JsonSchemaException $e, string $schemaFile)
17
    {
18
        $ro->headers[self::X_FAKE_JSON] = $schemaFile;
19
        $ro->headers[self::X_JSON_SCHEMA_EXCEPTION] = $e->getMessage();
20
        $ro->body = $this->fakeResponse($schemaFile);
21
    }
22
23
    private function fakeResponse(string $schemaFile) : array
24
    {
25
        $fakeObject = (new Faker)->generate(new \SplFileInfo($schemaFile));
26
27
        return $this->deepArray($fakeObject);
28
    }
29
30
    private function deepArray($values) : array
31
    {
32
        $result = [];
33
        foreach ($values as $key => $value) {
34
            $result[$key] = is_object($value) ? $this->deepArray((array) $value) : $result[$key] = $value;
35
        }
36
37
        return $result;
38
    }
39
}
40