Completed
Pull Request — 1.0 (#8)
by David
02:19
created

CallbackWrapperDefinition   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 3
c 2
b 0
f 0
lcom 1
cbo 3
dl 0
loc 55
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getIdentifier() 0 4 1
A __construct() 0 5 1
A toPhpCode() 0 10 1
1
<?php
2
3
namespace TheCodingMachine\Yaco\ServiceProvider;
4
5
use TheCodingMachine\Yaco\Definition\DumpableInterface;
6
use TheCodingMachine\Yaco\Definition\InlineEntry;
7
use TheCodingMachine\Yaco\Definition\InlineEntryInterface;
8
9
/**
10
 * Wraps a definition into a callback (to lazy load it easily).
11
 */
12
class CallbackWrapperDefinition implements DumpableInterface
13
{
14
    /**
15
     * The identifier of the instance in the container.
16
     *
17
     * @var string|null
18
     */
19
    private $identifier;
20
21
    /**
22
     * @var DumpableInterface
23
     */
24
    private $wrappedDefinition;
25
26
    /**
27
     * @param null|string       $identifier
28
     * @param DumpableInterface $wrappedDefinition
29
     */
30
    public function __construct($identifier, DumpableInterface $wrappedDefinition)
31
    {
32
        $this->identifier = $identifier;
33
        $this->wrappedDefinition = $wrappedDefinition;
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
64
        return new InlineEntry($code, null, $usedVariables);
65
    }
66
}
67