Completed
Pull Request — master (#73)
by Cethy
03:08
created

SerializationTypeResolver::resolveUsingSchema()   B

Complexity

Conditions 6
Paths 12

Size

Total Lines 20
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 1 Features 0
Metric Value
c 5
b 1
f 0
dl 0
loc 20
rs 8.8571
cc 6
eloc 11
nc 12
nop 1
1
<?php
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\Serializer;
9
10
use KleijnWeb\SwaggerBundle\Document\OperationObject;
11
12
class SerializationTypeResolver
13
{
14
    /**
15
     * @var array
16
     */
17
    private $resourceNamespaces = array();
18
19
    /**
20
     * @param mixed $resourceNamespaces
21
     */
22
    public function __construct($resourceNamespaces = null)
23
    {
24
        if(!is_array($resourceNamespaces)) {
25
            $resourceNamespaces = [$resourceNamespaces];
26
        }
27
        $this->resourceNamespaces = $resourceNamespaces;
28
    }
29
30
    /**
31
     * @param OperationObject $operationObject
32
     *
33
     * @return null|string
34
     */
35
    public function resolve(OperationObject $operationObject)
36
    {
37
        if ($operationObject->hasParameters()) {
38
            foreach ($operationObject->getParameters() as $parameterDefinition) {
39
                if ($parameterDefinition->in == 'body' && isset($parameterDefinition->schema)) {
40
                    return $this->resolveUsingSchema($parameterDefinition->schema);
41
                }
42
            }
43
        }
44
45
        return null;
46
    }
47
48
    /**
49
     * @param string $typeName
50
     *
51
     * @return string
52
     */
53
    protected function qualify($resourceNamespace, $typeName)
54
    {
55
        return ltrim($resourceNamespace . '\\' . $typeName, '\\');
56
    }
57
58
    /**
59
     * @param object $schema
60
     *
61
     * @return string
62
     */
63
    public function resolveUsingSchema($schema)
64
    {
65
        $reference = isset($schema->{'$ref'})
66
            ? $schema->{'$ref'}
67
            : (isset($schema->{'x-ref-id'}) ? $schema->{'x-ref-id'} : null)
68
        ;
69
70
        if ($reference) {
71
            $reference = substr($reference, strrpos($reference, '/') + 1);
72
73
            foreach ($this->resourceNamespaces as $resourceNamespace) {
74
                $resourceFullNamespace = $this->qualify($resourceNamespace, $reference);
75
                if (class_exists($resourceFullNamespace)) {
76
                    return $resourceFullNamespace;
77
                }
78
            }
79
        }
80
81
        return null;
82
    }
83
}
84