Completed
Pull Request — master (#81)
by John
03:37
created

ClassNameResolver::resolve()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 15
rs 9.2
cc 4
eloc 9
nc 5
nop 1
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
use KleijnWeb\SwaggerBundle\Document\Specification\Operation;
12
13
class ClassNameResolver
14
{
15
    /**
16
     * @var array
17
     */
18
    private $resourceNamespaces = [];
19
20
    /**
21
     * @var TypeNameResolver
22
     */
23
    private $typeNameResolver;
24
25
    /**
26
     * TypeNameResolver constructor.
27
     *
28
     * @param array            $resourceNamespaces
29
     * @param TypeNameResolver $typeNameResolver
30
     */
31
    public function __construct(array $resourceNamespaces, TypeNameResolver $typeNameResolver)
32
    {
33
        $this->resourceNamespaces = $resourceNamespaces;
34
        $this->typeNameResolver   = $typeNameResolver;
35
    }
36
37
    /**
38
     * @param string $typeName
39
     *
40
     * @return string
41
     */
42
    public function resolve(string $typeName): string
43
    {
44
        foreach ($this->resourceNamespaces as $resourceNamespace) {
45
            $suffix = "";
46
            if (false !== strpos($typeName, '[]')) {
47
                $typeName = substr($typeName, 0, strlen($typeName) - 2);
48
                $suffix = "[]";
49
            }
50
            if (class_exists($fqcn = $this->qualify($resourceNamespace, $typeName))) {
51
                return $fqcn . $suffix;
52
            }
53
        }
54
55
        throw new \InvalidArgumentException("Failed to resolve type '$typeName' to a class name");
56
    }
57
58
    /**
59
     * @param string $resourceNamespace
60
     * @param string $typeName
61
     *
62
     * @return string
63
     */
64
    protected function qualify(string $resourceNamespace, string $typeName): string
65
    {
66
        return ltrim($resourceNamespace . '\\' . $typeName, '\\');
67
    }
68
}
69