Completed
Branch master (4caf2b)
by Gawain
11:18 queued 12s
created

SwitchNode::compile()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 35
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 35
rs 8.5806
cc 4
eloc 26
nc 4
nop 1
1
<?php
2
3
namespace Bolt\Twig;
4
5
/**
6
 * Represents a switch node.
7
 *
8
 * @package    twig
9
 *
10
 * @author     Dsls
11
 * @author     maxgalbu
12
 *
13
 * @see        https://gist.github.com/maxgalbu/9409182
14
 */
15
class SwitchNode extends \Twig_Node
16
{
17
    public function __construct(\Twig_NodeInterface $value, \Twig_NodeInterface $cases, \Twig_NodeInterface $default = null, $lineno = 0, $tag = null)
18
    {
19
        parent::__construct(['value' => $value, 'cases' => $cases, 'default' => $default], [], $lineno, $tag);
20
    }
21
22
    /**
23
     * Compiles the node to PHP.
24
     *
25
     * @param Twig_Compiler A Twig_Compiler instance
26
     */
27
    public function compile(\Twig_Compiler $compiler)
28
    {
29
        $compiler->addDebugInfo($this);
30
        $compiler
31
            ->write('switch (')
32
            ->subcompile($this->getNode('value'))
33
            ->raw(") {\n")
34
            ->indent
35
        ;
36
        for ($i = 0; $i < count($this->getNode('cases')); $i += 2) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
37
            $compiler
38
                ->write('case ')
39
                ->subcompile($this->getNode('cases')->getNode($i))
40
                ->raw(":\n")
41
                ->indent()
42
                ->subcompile($this->getNode('cases')->getNode($i + 1))
43
                ->addIndentation()
44
                ->raw("break;\n")
45
            ;
46
        }
47
48
        if ($this->hasNode('default') && null !== $this->getNode('default')) {
49
            $compiler
50
                ->write("default:\n")
51
                ->indent()
52
                ->subcompile($this->getNode('default'))
53
                ->addIndentation()
54
                ->raw("break;\n")
55
            ;
56
        }
57
58
        $compiler
59
            ->outdent()
60
            ->write("}\n");
61
    }
62
}
63