Completed
Push — master ( c3e9f0...3d403c )
by Hong
01:14
created

ClassmapTrait::hasClass()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 22
rs 8.9457
c 0
b 0
f 0
cc 6
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
 * Store resolved/created objects in a classmap for later access or reference
18
 *
19
 * @package Phoole\Di
20
 */
21
trait ClassmapTrait
22
{
23
    /**
24
     * service objects stored by its classname
25
     *
26
     * @var object[]
27
     */
28
    protected $classMap = [];
29
30
    /**
31
     * has service created by its classname/interface name already?
32
     * returns the matching classname or NULL
33
     *
34
     * @param  string $className
35
     * @return string|NULL
36
     */
37
    protected function hasClass(string $className): ?string
38
    {
39
        // not a classname
40
        if (!\class_exists($className) && !\interface_exists($className)) {
41
            return NULL;
42
        }
43
44
        // exact match found
45
        if (isset($this->classMap[$className])) {
46
            return $className;
47
        }
48
49
        // try subclass exists or not
50
        $classes = array_keys($this->classMap);
51
        foreach ($classes as $class) {
52
            if (is_a($class, $className, TRUE)) {
53
                return $class;
54
            }
55
        }
56
57
        return NULL;
58
    }
59
60
    /**
61
     * Retrieve object from classmap if match found
62
     *
63
     * @param  string $className
64
     * @return object|null
65
     */
66
    protected function matchClass(string $className): ?object
67
    {
68
        if ($class = $this->hasClass($className)) {
69
            return $this->classMap[$class];
70
        }
71
        return NULL;
72
    }
73
74
    /**
75
     * Store object in classmap
76
     *
77
     * @param  object $object
78
     */
79
    protected function storeClass(object $object): void
80
    {
81
        $this->classMap[get_class($object)] = $object;
82
    }
83
}