Completed
Push — master ( 895d73...5bc057 )
by Federico
02:36
created

CodeVisitor::visitCodeConditional()   D

Complexity

Conditions 9
Paths 12

Size

Total Lines 33
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 9
eloc 20
c 1
b 0
f 1
nc 12
nop 1
dl 0
loc 33
rs 4.909
1
<?php
2
3
namespace Jade\Compiler;
4
5
use Jade\Nodes\Code;
6
7
abstract class CodeVisitor extends TagVisitor
8
{
9
    /**
10
     * @param Nodes\Code $node
11
     */
12
    protected function visitCodeConditional(array $matches)
13
    {
14
        $code = trim($matches[2], '; ');
15
        while (($len = strlen($code)) > 1 && ($code[0] === '(' || $code[0] === '{') && ord($code[0]) === ord(substr($code, -1)) - 1) {
16
            $code = trim(substr($code, 1, $len - 2));
17
        }
18
19
        $index = count($this->buffer) - 1;
20
        $conditional = '';
21
22
        if (isset($this->buffer[$index]) && false !== strpos($this->buffer[$index], $this->createCode('}'))) {
23
            // the "else" statement needs to be in the php block that closes the if
24
            $this->buffer[$index] = null;
25
            $conditional .= '} ';
26
        }
27
28
        $conditional .= '%s';
29
30
        if (strlen($code) > 0) {
31
            $conditional .= '(%s) {';
32
            $conditional = $matches[1] === 'unless'
33
                ? sprintf($conditional, 'if', '!(%s)')
34
                : sprintf($conditional, $matches[1], '%s');
35
            $this->buffer($this->createCode($conditional, $code));
36
37
            return;
38
        }
39
40
        $conditional .= ' {';
41
        $conditional = sprintf($conditional, $matches[1]);
42
43
        $this->buffer($this->createCode($conditional));
44
    }
45
46
    /**
47
     * @param Nodes\Code $node
48
     */
49
    protected function visitCodeOpening(Code $node)
50
    {
51
        $code = trim($node->value);
52
53
        if ($node->buffer) {
54
            $this->buffer($this->escapeIfNeeded($node->escape, $code));
55
56
            return;
57
        }
58
59
        $phpOpen = implode('|', $this->phpOpenBlock);
60
61
        if (preg_match("/^[[:space:]]*({$phpOpen})(.*)/", $code, $matches)) {
62
            $this->visitCodeConditional($matches);
63
64
            return;
65
        }
66
67
        $this->buffer($this->createCode('%s', $code));
68
    }
69
70
    /**
71
     * @param Nodes\Code $node
72
     */
73
    protected function visitCode(Code $node)
74
    {
75
        $this->visitCodeOpening($node);
76
77
        if (isset($node->block)) {
78
            $this->indents++;
79
            $this->visit($node->block);
80
            $this->indents--;
81
82
            if (!$node->buffer) {
83
                $this->buffer($this->createCode('}'));
84
            }
85
        }
86
    }
87
}
88