Passed
Push — master ( 2e610f...e9d334 )
by Paweł
02:08
created

SchemaFactory::createFromProject()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 5
rs 10
1
<?php
2
/**
3
 * Copyright (c) 2020.
4
 * @author Paweł Antosiak <[email protected]>
5
 */
6
7
declare(strict_types=1);
8
9
namespace Gorynych\Util;
10
11
use Cake\Collection\Collection;
12
use OpenApi\Annotations\Schema;
13
use const OpenApi\Annotations\UNDEFINED;
14
15
final class SchemaFactory
16
{
17
    /** @var Collection<int, Schema> */
18
    private Collection $schemas;
19
20
    public function __construct(OAReader $oaReader)
21
    {
22
        $this->schemas = new Collection($oaReader->read()->components->schemas);;
23
    }
24
25
    /**
26
     * Creates single JSON schema for provided class name
27
     */
28
    public function create(string $className): string
29
    {
30
        $schemaName = (new \ReflectionClass($className))->getShortName();
31
32
        $schema = $this->schemas->filter(
33
            static function(Schema $schema) use ($schemaName): bool {
34
                return $schema->schema === $schemaName;
35
            }
36
        )->first();
37
38
        $relatedSchemas = new Collection([$schema]);
39
40
        foreach ($schema->properties as $property) {
41
            if (UNDEFINED === $property->ref) {
42
                continue;
43
            }
44
45
            $relatedSchemas = $relatedSchemas->append(
46
                $this->schemas->filter(
47
                    static function(Schema $schema) use ($property): bool {
48
                        return $schema->schema === ucfirst($property->property);
49
                    }
50
                )
51
            );
52
        }
53
54
        return json_encode([
55
            'schemas' => $relatedSchemas->toArray()
56
        ]);
57
    }
58
}
59