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
|
|
|
use LogicException; |
10
|
|
|
use Override; |
11
|
|
|
use SplFileInfo; |
12
|
|
|
use stdClass; |
13
|
|
|
|
14
|
|
|
use function class_exists; |
15
|
|
|
use function is_object; |
16
|
|
|
|
17
|
|
|
final class JsonSchemaExceptionFakeHandler implements JsonSchemaExceptionHandlerInterface |
18
|
|
|
{ |
19
|
|
|
final public const X_FAKE_JSON = 'X-Fake-JSON'; |
20
|
|
|
final public const X_JSON_SCHEMA_EXCEPTION = 'X-JSON-Schema-Exception'; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* {@inheritDoc} |
24
|
|
|
*/ |
25
|
|
|
#[Override] |
26
|
|
|
public function handle(ResourceObject $ro, JsonSchemaException $e, string $schemaFile) |
27
|
|
|
{ |
28
|
|
|
$ro->headers[self::X_FAKE_JSON] = $schemaFile; |
29
|
|
|
$ro->headers[self::X_JSON_SCHEMA_EXCEPTION] = $e->getMessage(); |
30
|
|
|
$ro->body = $this->fakeResponse($schemaFile); |
31
|
|
|
$ro->view = null; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
/** @return array<int|string, mixed> */ |
35
|
|
|
private function fakeResponse(string $schemaFile): array |
36
|
|
|
{ |
37
|
|
|
if (! class_exists(Faker::class)) { |
38
|
|
|
throw new LogicException('"koriym/json-schema-faker" not installed. Please run "composer require koriym/json-schema-faker --dev". See more at https://github.com/bearsunday/BEAR.Resource/wiki/json_schema_faker_required'); // @codeCoverageIgnore |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
/** @var array<int|string, mixed> $fakeObject */ |
42
|
|
|
$fakeObject = (new Faker())->generate(new SplFileInfo($schemaFile)); |
43
|
|
|
|
44
|
|
|
return $this->deepArray($fakeObject); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* @param array<int|string, mixed> $values |
49
|
|
|
* |
50
|
|
|
* @return array<int|string, mixed> |
51
|
|
|
*/ |
52
|
|
|
private function deepArray(array|stdClass $values): array |
53
|
|
|
{ |
54
|
|
|
$result = []; |
55
|
|
|
/** @psalm-suppress MixedAssignment */ |
56
|
|
|
foreach ($values as $key => $value) { //@phpstan-ignore-line |
57
|
|
|
$result[$key] = is_object($value) ? $this->deepArray((array) $value) : $result[$key] = $value; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
return $result; |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|