SwitchNode::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
eloc 6
c 1
b 0
f 1
nc 1
nop 3
dl 0
loc 9
rs 10
1
<?php
2
/**
3
 * @author Gerard van Helden <[email protected]>
4
 * @copyright Zicht Online <http://zicht.nl>
5
 */
6
namespace Zicht\Bundle\FrameworkExtraBundle\Twig\ControlStructures;
7
8
use Twig_Node;
9
use Twig_NodeInterface;
10
use Twig_Compiler;
11
12
/**
13
 * Represents a 'switch' statement
14
 */
15
class SwitchNode extends Twig_Node
16
{
17
    /**
18
     * Constructor
19
     *
20
     * @param \Twig_NodeInterface $cases
21
     * @param \Twig_NodeInterface $expression
22
     * @param int $line
23
     */
24
    public function __construct(Twig_NodeInterface $cases, Twig_NodeInterface $expression, $line)
25
    {
26
        parent::__construct(
27
            array(
28
                'expression' => $expression,
29
                'cases'      => $cases
30
            ),
31
            array(),
32
            $line
33
        );
34
    }
35
36
37
    /**
38
     * Compiles the node
39
     *
40
     * @param \Twig_Compiler $compiler
41
     * @return void
42
     */
43
    public function compile(Twig_Compiler $compiler)
44
    {
45
        $compiler->addDebugInfo($this);
46
47
        $compiler
48
            ->write('switch(')
49
            ->subcompile($this->getNode('expression'))
50
            ->raw(") {\n")
51
            ->indent();
52
53
        $total = count($this->getNode('cases'));
54
        for ($i = 0; $i < $total; $i++) {
55
            $expr = $this->getNode('cases')->getNode($i)->getAttribute('expression');
56
            $body = $this->getNode('cases')->getNode($i)->getNode('body');
57
            if (is_null($expr)) {
58
                $compiler
59
                    ->write('default')
60
                    ->raw(":\n");
61
            } else {
62
                foreach ($expr as $subExpr) {
63
                    $compiler
64
                        ->write('case ')
65
                        ->subcompile($subExpr)
66
                        ->raw(":\n");
67
                }
68
            }
69
            $compiler->indent();
70
            $compiler->subcompile($body);
71
            if ($i + 1 >= $total || !$this->getNode('cases')->getNode($i + 1)->getAttribute('fallthrough')) {
72
                $compiler->write("break;\n");
73
            }
74
            $compiler->outdent();
75
        }
76
77
        $compiler->outdent()->write('}');
78
    }
79
}
80