Completed
Push — master ( 6e1c48...7d90f1 )
by John
03:00
created

ClassNameResolver::qualify()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 2
1
<?php declare(strict_types=1);
2
/*
3
 * This file is part of the KleijnWeb\PhpApi\Descriptions\Hydrator 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
9
namespace KleijnWeb\PhpApi\Descriptions\Hydrator;
10
11
use KleijnWeb\PhpApi\Descriptions\Hydrator\Exception\ClassNotFoundException;
12
13
/**
14
 * @author John Kleijn <[email protected]>
15
 */
16
class ClassNameResolver
17
{
18
    /**
19
     * @var array
20
     */
21
    protected $resourceNamespaces = [];
22
23
    /**
24
     * @var array
25
     */
26
    protected $cache = [];
27
28
    /**
29
     * ClassNameResolver constructor.
30
     *
31
     * @param array $resourceNamespaces
32
     */
33
    public function __construct(array $resourceNamespaces)
34
    {
35
        $this->resourceNamespaces = $resourceNamespaces;
36
    }
37
38
    /**
39
     * @param string $typeName
40
     *
41
     * @return string
42
     */
43
    public function resolve(string $typeName): string
44
    {
45
        if (!isset($this->cache[$typeName])) {
46
            foreach ($this->resourceNamespaces as $resourceNamespace) {
47
                if (class_exists($this->cache[$typeName] = $this->qualify($resourceNamespace, $typeName))) {
48
                    return $this->cache[$typeName];
49
                }
50
            }
51
52
            throw new ClassNotFoundException(
53
                sprintf(
54
                    "Did not find type '%s' in namespace(s) '%s'.",
55
                    $typeName,
56
                    implode(', ', $this->resourceNamespaces)
57
                )
58
            );
59
        }
60
61
        return $this->cache[$typeName];
62
    }
63
64
    /**
65
     * @param string $resourceNamespace
66
     * @param string $typeName
67
     *
68
     * @return string
69
     */
70
    protected function qualify(string $resourceNamespace, string $typeName): string
71
    {
72
        return ltrim("$resourceNamespace\\$typeName");
73
    }
74
}
75