Completed
Push — 2.x ( 07ed38...d68955 )
by Akihito
03:36
created

DependencyProvider::__toString()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 7
ccs 0
cts 4
cp 0
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 0
crap 2
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 47
    public function __construct(Dependency $dependency, string $context)
36
    {
37 47
        $this->dependency = $dependency;
38 47
        $this->context = $context;
39 47
    }
40
41 2
    public function __sleep()
42
    {
43 2
        return ['dependency', 'isSingleton'];
44
    }
45
46
    public function __toString()
47
    {
48
        return sprintf(
49
            '(provider) %s',
50
            (string) $this->dependency
51
        );
52
    }
53
54
    /**
55
     * {@inheritdoc}
56
     */
57 47
    public function register(array &$container, Bind $bind)
58
    {
59 47
        $container[(string) $bind] = $bind->getBound();
60 47
    }
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 40
    public function setScope($scope)
83
    {
84 40
        if ($scope === Scope::SINGLETON) {
85 40
            $this->isSingleton = true;
86
        }
87 40
    }
88
89 3
    public function setContext(SetContextInterface $provider)
90
    {
91 3
        $provider->setContext($this->context);
92 3
    }
93
}
94