CallbackWrapperDefinition::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 5
rs 9.4285
cc 1
eloc 3
nc 1
nop 2
1
<?php
2
namespace TheCodingMachine\Yaco\ServiceProvider;
3
4
use TheCodingMachine\Yaco\Definition\DumpableInterface;
5
use TheCodingMachine\Yaco\Definition\InlineEntry;
6
use TheCodingMachine\Yaco\Definition\InlineEntryInterface;
7
8
/**
9
 * Wraps a definition into a callback (to lazy load it easily)
10
 */
11
class CallbackWrapperDefinition implements DumpableInterface
12
{
13
    /**
14
     * The identifier of the instance in the container.
15
     *
16
     * @var string|null
17
     */
18
    private $identifier;
19
20
    /**
21
     * @var DumpableInterface
22
     */
23
    private $wrappedDefinition;
24
25
    /**
26
     * @param null|string $identifier
27
     * @param DumpableInterface $wrappedDefinition
28
     */
29
    public function __construct($identifier, DumpableInterface $wrappedDefinition)
30
    {
31
        $this->identifier = $identifier;
32
        $this->wrappedDefinition = $wrappedDefinition;
33
    }
34
35
36
    /**
37
     * Returns the identifier for this object in the container.
38
     * If null, classes consuming this definition should assume the definition must be inlined.
39
     *
40
     * @return string|null
41
     */
42
    public function getIdentifier()
43
    {
44
        return $this->identifier;
45
    }
46
47
    /**
48
     * Returns an InlineEntryInterface object representing the PHP code necessary to generate
49
     * the container entry.
50
     *
51
     * @param string $containerVariable The name of the variable that allows access to the container instance. For instance: "$container", or "$this->container"
52
     * @param array $usedVariables An array of variables that are already used and that should not be used when generating this code.
53
     *
54
     * @return InlineEntryInterface
55
     */
56
    public function toPhpCode($containerVariable, array $usedVariables = array())
57
    {
58
        $innerEntry = $this->wrappedDefinition->toPhpCode($containerVariable, $usedVariables);
59
        $code = sprintf('function() use (%s) {
60
    %s
61
    return %s;
62
}', $containerVariable, $innerEntry->getStatements(), $innerEntry->getExpression());
63
        return new InlineEntry($code, null, $usedVariables);
64
    }
65
}
66