Completed
Push — master ( 3af88c...d76c98 )
by Mewes
05:10
created

XlsMacroTokenParser   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 11

Importance

Changes 3
Bugs 0 Features 0
Metric Value
wmc 5
c 3
b 0
f 0
lcom 1
cbo 11
dl 0
loc 62
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
B parse() 0 34 3
A decideBlockEnd() 0 4 1
A getTag() 0 4 1
1
<?php
2
3
namespace MewesK\TwigExcelBundle\Twig\TokenParser;
4
5
use MewesK\TwigExcelBundle\Twig\TokenParser\Traits\RemoveTextNodeTrait;
6
use Twig_Error_Syntax;
7
use Twig_Node_Body;
8
use Twig_Node_Expression_Constant;
9
use Twig_Node_Macro;
10
use Twig_Token;
11
use Twig_TokenParser_Macro;
12
13
/**
14
 * Class XlsMacroTokenParser
15
 *
16
 * @package MewesK\TwigExcelBundle\Twig\TokenParser
17
 */
18
class XlsMacroTokenParser extends Twig_TokenParser_Macro
19
{
20
    use RemoveTextNodeTrait;
21
22
    /**
23
     * TODO: Is there a way access Twig_Node_Macro without copying the whole method body?
24
     *
25
     * @param Twig_Token $token
26
     * @throws Twig_Error_Syntax
27
     */
28
    public function parse(Twig_Token $token)
29
    {
30
        $lineno = $token->getLine();
31
        $stream = $this->parser->getStream();
32
        $name = $stream->expect(Twig_Token::NAME_TYPE)->getValue();
33
34
        $arguments = $this->parser->getExpressionParser()->parseArguments(true, true);
35
36
        // fix macro context
37
        $arguments->setNode('phpExcel', new Twig_Node_Expression_Constant(null, null));
38
39
        $stream->expect(Twig_Token::BLOCK_END_TYPE);
40
        $this->parser->pushLocalScope();
41
        $body = $this->parser->subparse(array($this, 'decideBlockEnd'), true);
42
        if ($token = $stream->nextIf(Twig_Token::NAME_TYPE)) {
43
            $value = $token->getValue();
44
45
            if ($value != $name) {
46
                throw new Twig_Error_Syntax(sprintf('Expected endxlsmacro for macro "%s" (but "%s" given).', $name, $value), $stream->getCurrent()->getLine(), $stream->getFilename());
47
            }
48
        }
49
        $this->parser->popLocalScope();
50
        $stream->expect(Twig_Token::BLOCK_END_TYPE);
51
52
        // remove all unwanted text nodes
53
        $this->removeTextNodesRecursively($body);
54
55
        $macro = new Twig_Node_Macro($name, new Twig_Node_Body(array($body)), $arguments, $lineno, $this->getTag());
56
57
        // mark for syntax checks
58
        $macro->setAttribute('twigExcelBundle', true);
59
60
        $this->parser->setMacro($name, $macro);
61
    }
62
63
    /**
64
     * @param Twig_Token $token
65
     * @return bool
66
     */
67
    public function decideBlockEnd(Twig_Token $token)
68
    {
69
        return $token->test('endxlsmacro');
70
    }
71
72
    /**
73
     * @return string
74
     */
75
    public function getTag()
76
    {
77
        return 'xlsmacro';
78
    }
79
}
80