Completed
Push — 2.x ( 144798...0daeb2 )
by Akihito
10s
created

DependencyProvider::__toString()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 7
ccs 4
cts 4
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 0
crap 1
1
<?php
2
3
declare(strict_types=1);
4
/**
5
 * This file is part of the Ray.Di package.
6
 *
7
 * @license http://opensource.org/licenses/MIT MIT
8
 */
9
namespace Ray\Di;
10
11
final class DependencyProvider implements DependencyInterface
12
{
13
    /**
14
     * @var string|null
15
     */
16
    public $context;
17
18
    /**
19
     * Provider dependency
20
     *
21
     * @var Dependency
22
     */
23
    private $dependency;
24
25
    /**
26
     * @var bool
27
     */
28
    private $isSingleton = false;
29
30
    /**
31
     * @var mixed
32
     */
33
    private $instance;
34
35 49
    public function __construct(Dependency $dependency, string $context)
36
    {
37 49
        $this->dependency = $dependency;
38 49
        $this->context = $context;
39 49
    }
40
41 4
    public function __sleep()
42
    {
43 4
        return ['dependency', 'isSingleton'];
44
    }
45
46 1
    public function __toString()
47
    {
48 1
        return sprintf(
49 1
            '(provider) %s',
50 1
            (string) $this->dependency
51
        );
52
    }
53
54
    /**
55
     * {@inheritdoc}
56
     */
57 49
    public function register(array &$container, Bind $bind)
58
    {
59 49
        $container[(string) $bind] = $bind->getBound();
60 49
    }
61
62
    /**
63
     * {@inheritdoc}
64
     */
65 13
    public function inject(Container $container)
66
    {
67 13
        if ($this->isSingleton && $this->instance) {
68 1
            return $this->instance;
69
        }
70 13
        $provider = $this->dependency->inject($container);
71 13
        if ($provider instanceof SetContextInterface) {
72 2
            $this->setContext($provider);
73
        }
74 13
        $this->instance = $provider->get();
75
76 13
        return $this->instance;
77
    }
78
79
    /**
80
     * {@inheritdoc}
81
     */
82 42
    public function setScope($scope)
83
    {
84 42
        if ($scope === Scope::SINGLETON) {
85 42
            $this->isSingleton = true;
86
        }
87 42
    }
88
89 3
    public function setContext(SetContextInterface $provider)
90
    {
91 3
        $provider->setContext($this->context);
92 3
    }
93
}
94