Completed
Push — master ( c89067...3b0f09 )
by Hong
04:25
created

ClassmapTrait::hasClass()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 22
rs 9.2568
c 0
b 0
f 0
cc 5
nc 5
nop 1
1
<?php
2
3
/**
4
 * Phoole (PHP7.2+)
5
 *
6
 * @category  Library
7
 * @package   Phoole\Di
8
 * @copyright Copyright (c) 2019 Hong Zhang
9
 */
10
declare(strict_types=1);
11
12
namespace Phoole\Di\Util;
13
14
/**
15
 * ClassmapTrait
16
 *
17
 * @package Phoole\Di
18
 */
19
trait ClassmapTrait
20
{
21
    /**
22
     * service objects stored by its classname
23
     *
24
     * @var object[]
25
     */
26
    protected $classNames = [];
27
28
    /**
29
     * has service created by its classname/interface name?
30
     *
31
     * @param  string $className
32
     * @return string|NULL
33
     */
34
    protected function hasClass(string $className): ?string
35
    {
36
        // not a classname
37
        if (!class_exists($className)) {
38
            return NULL;
39
        }
40
41
        // exact match
42
        if (isset($this->classNames[$className])) {
43
            return $className;
44
        }
45
46
        // find matching parent if any
47
        $classes = array_keys($this->classNames);
48
        foreach ($classes as $class) {
49
            if (is_a($class, $className, TRUE)) {
50
                return $class;
51
            }
52
        }
53
54
        return NULL;
55
    }
56
57
    /**
58
     * @param  string $className
59
     * @return object|null
60
     */
61
    protected function matchClass(string $className): ?object
62
    {
63
        if ($class = $this->hasClass($className)) {
64
            return $this->classNames[$class];
65
        }
66
        return NULL;
67
    }
68
69
    /**
70
     * Only store global object (not in a domain) into classmap
71
     *
72
     * @param  object $object
73
     */
74
    protected function storeClass(object $object): void
75
    {
76
        $this->classNames[get_class($object)] = $object;
77
    }
78
}