Completed
Push — master ( cf3632...f41966 )
by Vitaly
09:23
created

ClosureContainer::generateCondition()   B

Complexity

Conditions 5
Paths 9

Size

Total Lines 34
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 5.0342

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 34
ccs 16
cts 18
cp 0.8889
rs 8.439
cc 5
eloc 14
nc 9
nop 2
crap 5.0342
1
<?php
2
/**
3
 * Created by Vitaly Iegorov <[email protected]>.
4
 * on 26.01.16 at 10:32
5
 */
6
namespace samsonframework\di;
7
8
/**
9
 * Container for resolving closure dependencies.
10
 *
11
 * @package samsonframework\di
12
 */
13
class ClosureContainer extends AbstractContainer
14
{
15 2
    protected function getSpaces($line)
16
    {
17 2
        if (preg_match('/(\s+)[^\s]/', $line, $matches)) {
18 2
            return $matches[1];
19
        }
20
        return '';
21
    }
22
    /**
23
     * Generate container dependency condition code.
24
     * @param string    $alias Entity alias
25
     * @param mixed     $entity Entity
26
     */
27 2
    public function generateCondition($alias, $entity)
28
    {
29
        // Get closure reflection
30 2
        $reflection = new \ReflectionFunction($entity);
31
        // Read closure file
32 2
        $lines = file($reflection->getFileName());
33
34 2
        $indentation = $this->getSpaces($lines[$reflection->getStartLine()]);
35
36 2
        $opened = 0;
37
        // Read only closure lines
38 2
        for ($l = $reflection->getStartLine(); $l < $reflection->getEndLine(); $l++) {
39
            // Fix opening braces scope
40 2
            if (strpos($lines[$l], '{') !== false) {
41
                $opened++;
42
            }
43
44
            // Fix closing braces scope
45 2
            if (strpos($lines[$l], '}') !== false) {
46 2
                $opened--;
47 2
            }
48
49
            // Break if we reached closure end
50 2
            if ($opened === -1) {
51 2
                break;
52
            }
53
54
            // Cut only base $indentation to beautify output
55 2
            $spaces = substr($this->getSpaces($lines[$l]), strlen($indentation));
56
57
            // Add closure code
58 2
            $this->generator->newLine($spaces.trim($lines[$l]));
59 2
        }
60 2
    }
61
62
    /**
63
     * Set container dependency.
64
     *
65
     * @param callable    $entity     Callable
66
     * @param string|null $alias      Entity alias for simplier finding
67
     * @param array       $parameters Collection of additional parameters
68
     *
69
     * @return self Chaining
70
     */
71 2
    public function set($entity, $alias = null, array $parameters = array())
72
    {
73
        // Add unique closure alias
74 2
        $this->aliases[$alias] = 'closure' . uniqid(0, 99999);
75
76
        // Store parameters
77 2
        $this->parameters[$alias] = $parameters;
78
79
        // Store dependency
80 2
        $this->dependencies[$alias] = $entity;
81 2
    }
82
}
83