Completed
Push — master ( 80feaa...8a9c1c )
by Hong
02:15
created

ContainerTrait::newInstance()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.8666
c 0
b 0
f 0
cc 2
nc 2
nop 2
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
use Phoole\Base\Tree\Tree;
15
use Phoole\Config\ConfigInterface;
16
use Phoole\Di\Exception\RuntimeException;
17
use Phoole\Base\Reference\ReferenceTrait;
18
19
/**
20
 * ContainerTrait
21
 *
22
 * @package Phoole\Di
23
 */
24
trait ContainerTrait
25
{
26
    use FactoryTrait;
27
    use ReferenceTrait;
28
    
29
    /**
30
     * for configuration lookup
31
     *
32
     * @var ConfigInterface
33
     */
34
    protected $config;
35
36
    /**
37
     * delegator for object lookup
38
     */
39
    protected $delegator;
40
41
    /**
42
     * object pool
43
     *
44
     * @var array
45
     */
46
    protected $objects = [];
47
48
    /**
49
     * Get the instance
50
     *
51
     * @param  string $id
52
     * @return object
53
     */
54
    protected function getInstance(string $id): object
55
    {
56
        if (!isset($this->objects[$id])) {
57
            $this->objects[$id] = $this->newInstance($id);
58
        }
59
        return $this->objects[$id];
60
    }
61
62
    /**
63
     * creaet a new instance
64
     *
65
     * @param  string $id
66
     * @return object
67
     */
68
    protected function newInstance(string $id, array $args = []): object
69
    {
70
        $fid = 'di.service.' . $id;
71
        $def = $this->config->get($fid);
72
73
        if (!empty($args)) {
74
            $this->resolve($args);
75
            $def['args'] = $args;
76
        }
77
78
        return $this->fabricate($def);
79
    }
80
81
    /**
82
     * Try find a service in the definition
83
     *
84
     * @param  string $id
85
     * @return bool
86
     */
87
    protected function hasDefinition(string $id): bool
88
    {
89
        $def = 'di.service.' . $id;
90
        return $this->config->has($def);
91
    }
92
93
    /**
94
     * {@inheritDoc}
95
     */
96
    protected function getReference(string $name)
97
    {
98
        return $this->delegator->get($name);
99
    }
100
101
    /**
102
     * from ExtendedContainerTrait
103
     */
104
    abstract public function resolve(&$input): void;
105
}
106