Completed
Push — master ( 27a5d2...ad3b69 )
by John
20s
created

TypeNameResolver   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Importance

Changes 0
Metric Value
wmc 10
c 0
b 0
f 0
lcom 0
cbo 0
dl 0
loc 54
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A isResolvableSchema() 0 4 1
A resolveUsingSchema() 0 8 2
C findTypeInSchema() 0 22 7
1
<?php declare(strict_types = 1);
2
/*
3
 * This file is part of the KleijnWeb\SwaggerBundle package.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 */
8
namespace KleijnWeb\SwaggerBundle\Serialize\TypeResolver;
9
10
use KleijnWeb\SwaggerBundle\Document\Specification;
11
12
class TypeNameResolver
13
{
14
    /**
15
     * @param \stdClass $schema
16
     *
17
     * @return bool
18
     */
19
    public function isResolvableSchema(\stdClass $schema): bool
20
    {
21
        return (bool)$this->findTypeInSchema($schema);
22
    }
23
24
    /**
25
     * @param \stdClass $schema
26
     *
27
     * @return string
28
     */
29
    public function resolveUsingSchema(\stdClass $schema): string
30
    {
31
        if ($type = $this->findTypeInSchema($schema)) {
32
            return $type;
33
        }
34
35
        throw new \InvalidArgumentException("Failed to resolve type");
36
    }
37
38
    /**
39
     * @param \stdClass $schema
40
     *
41
     * @return string
42
     */
43
    private function findTypeInSchema(\stdClass $schema): string
44
    {
45
        if (isset($schema->{'x-type'})) {
46
            return $schema->{'x-type'};
47
        }
48
        if (!isset($schema->type)) {
49
            return '';
50
        }
51
52
        $getTypeFromReference = function ($schema) {
53
            return $schema->{'x-type'} = substr($schema->{'x-ref-id'}, strrpos($schema->{'x-ref-id'}, '/') + 1);
54
        };
55
56
        if ($schema->type === 'array' && $schema->items->type == 'object') {
57
            return "{$getTypeFromReference($schema->items)}[]";
58
        }
59
        if (isset($schema->{'x-ref-id'}) && $schema->type === 'object') {
60
            return $getTypeFromReference($schema);
61
        }
62
63
        return '';
64
    }
65
}
66