Completed
Push — master ( 3ec883...dc88c0 )
by Rafał
02:38
created

GimmeListNode::compile()   D

Complexity

Conditions 11
Paths 192

Size

Total Lines 109
Code Lines 78

Duplication

Lines 12
Ratio 11.01 %

Importance

Changes 0
Metric Value
dl 12
loc 109
rs 4.9629
c 0
b 0
f 0
cc 11
eloc 78
nc 192
nop 1

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * This file is part of the Superdesk Web Publisher Templates System.
5
 *
6
 * Copyright 2015 Sourcefabric z.ú. and contributors.
7
 *
8
 * For the full copyright and license information, please see the
9
 * AUTHORS and LICENSE files distributed with this source code.
10
 *
11
 * @copyright 2015 Sourcefabric z.ú
12
 * @license http://www.superdesk.org/license
13
 */
14
15
namespace SWP\Component\TemplatesSystem\Twig\Node;
16
17
/**
18
 * Gimme twig node.
19
 */
20
class GimmeListNode extends \Twig_Node
21
{
22
    protected static $count = 1;
23
24
    protected $loop;
25
26
    /**
27
     * GimmeListNode constructor.
28
     *
29
     * @param \Twig_Node                        $variable
30
     * @param \Twig_Node                        $collectionType
31
     * @param \Twig_Node_Expression_Filter|null $collectionFilters
32
     * @param \Twig_Node_Expression|null        $parameters
33
     * @param \Twig_Node_Expression|null        $ifExpression
34
     * @param \Twig_NodeInterface|null          $else
35
     * @param \Twig_NodeInterface               $body
36
     * @param                                   $lineno
37
     * @param null                              $tag
38
     */
39
    public function __construct(\Twig_Node $variable, \Twig_Node $collectionType, \Twig_Node_Expression_Filter $collectionFilters = null, \Twig_Node_Expression $parameters = null, \Twig_Node_Expression $ifExpression = null, \Twig_NodeInterface $else = null, \Twig_NodeInterface $body, $lineno, $tag = null)
40
    {
41
        $body = new \Twig_Node([$body, $this->loop = new \Twig_Node_ForLoop($lineno, $tag)]);
42
43
        if (null !== $ifExpression) {
44
            $body = new \Twig_Node_If(new \Twig_Node([$ifExpression, $body]), null, $lineno, $tag);
45
        }
46
47
        $nodes = [
48
            'variable' => $variable,
49
            'collectionType' => $collectionType,
50
            'body' => $body,
51
        ];
52
53
        if (!is_null($parameters)) {
54
            $nodes['parameters'] = $parameters;
55
        }
56
57
        if (!is_null($collectionFilters)) {
58
            $nodes['collectionFilters'] = $collectionFilters;
59
        }
60
61
        if (!is_null($ifExpression)) {
62
            $nodes['ifExpression'] = $ifExpression;
63
        }
64
65
        if (!is_null($else)) {
66
            $nodes['else'] = $else;
67
        }
68
69
        parent::__construct($nodes, ['with_loop' => true, 'ifexpr' => null !== $ifExpression], $lineno, $tag);
70
    }
71
72
    /**
73
     * {@inheritdoc}
74
     */
75
    public function compile(\Twig_Compiler $compiler)
76
    {
77
        $i = self::$count++;
78
79
        $collectionTypeName = $this->getNode('collectionType')->getNode(0)->getAttribute('name');
80
81
        $compiler
82
            ->addDebugInfo($this);
83
84
        if ($this->hasNode('collectionFilters')) {
85
            $compiler->write("\$context['_collection_type_filters'] = [];\n");
86
            $compiler->write("\$context['".$collectionTypeName."'] = null;\n");
87
            $compiler->write("\$context['_collection_type_filters'] = ")->subcompile($this->getNode('collectionFilters'))->raw("['_collection_type_filters']; unset(\$context['".$collectionTypeName."']['_collection_type_filters']);\n");
88
89 View Code Duplication
            if ($this->hasNode('parameters')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
90
                $compiler->write('$parameters = array_merge(')->subcompile($this->getNode('parameters'))->raw(", \$context['_collection_type_filters']);\n");
91
            } else {
92
                $compiler->write("\$parameters = \$context['_collection_type_filters'];\n");
93
            }
94 View Code Duplication
        } else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
95
            if ($this->hasNode('parameters')) {
96
                $compiler->raw('$parameters = ')->subcompile($this->getNode('parameters'))->raw(";\n");
97
            } else {
98
                $compiler->raw("\$parameters = [];\n");
99
            }
100
        }
101
102
        $compiler->write('$swpCollectionMetaLoader'.$i." = \$this->env->getExtension('swp_gimme')->getLoader();\n")
103
            ->write('')->subcompile($this->getNode('collectionType'))->raw(' = twig_ensure_traversable($swpCollectionMetaLoader'.$i.'->load("')->raw($collectionTypeName)->raw('", ');
104
        $compiler->raw('$parameters');
105
        $compiler->raw(", \SWP\Component\TemplatesSystem\Gimme\Loader\LoaderInterface::COLLECTION));\n");
106
107
        // the (array) cast bypasses a PHP 5.2.6 bug
108
        $compiler->write("\$context['_parent'] = (array) \$context;\n");
109
110
        if ($this->hasNode('else')) {
111
            $compiler->write("\$context['_iterated'] = false;\n");
112
        }
113
114
        if ($this->getAttribute('with_loop')) {
115
            $compiler
116
                ->write("\$context['loop'] = array(\n")
117
                ->write("  'parent' => \$context['_parent'],\n")
118
                ->write("  'index0' => 0,\n")
119
                ->write("  'index'  => 1,\n")
120
                ->write("  'first'  => true,\n")
121
                ->write(");\n");
122
123
            if (!$this->getAttribute('ifexpr') && $this->getNode('collectionType')) {
124
                $compiler
125
                    ->write('if (is_array(')->subcompile($this->getNode('collectionType'))->raw(') || (is_object(')->subcompile($this->getNode('collectionType'))->raw(') && ')->subcompile($this->getNode('collectionType'))->raw(" instanceof Countable)) {\n")
126
                    ->indent()
127
                    ->write('$length = count(')->subcompile($this->getNode('collectionType'))->raw(");\n")
128
                    ->write("\$context['loop']['revindex0'] = \$length - 1;\n")
129
                    ->write("\$context['loop']['revindex'] = \$length;\n")
130
                    ->write("\$context['loop']['length'] = \$length;\n")
131
                    ->write("\$context['loop']['totalLength'] = \$length;\n")
132
                    ->write("\$context['loop']['last'] = 1 === \$length;\n")
133
                    ->outdent()
134
                    ->write("}\n");
135
136
                $compiler
137
                    ->write('if(is_object(')->subcompile($this->getNode('collectionType'))->raw(') && ')->subcompile($this->getNode('collectionType'))->raw(" instanceof \SWP\Component\TemplatesSystem\Gimme\Meta\MetaCollection) {\n")
138
                    ->indent()
139
                    ->write('$context[\'loop\'][\'totalLength\'] = ')->subcompile($this->getNode('collectionType'))->raw("->getTotalItemCount();\n")
140
                    ->outdent()
141
                    ->write("}\n");
142
            }
143
        }
144
145
        $this->loop->setAttribute('else', $this->hasNode('else'));
146
        $this->loop->setAttribute('with_loop', $this->getAttribute('with_loop'));
147
        $this->loop->setAttribute('ifexpr', $this->getAttribute('ifexpr'));
148
149
        if (null !== $this->getNode('collectionType')) {
150
            $compiler
151
                ->write('foreach (')
152
                ->subcompile($this->getNode('collectionType'))
153
                ->raw(' as $_key')
154
                ->raw(' => ')
155
                ->subcompile($this->getNode('variable'))
156
                ->raw(") {\n")
157
                ->indent()
158
                ->subcompile($this->getNode('body'))
159
                ->outdent()
160
                ->write("}\n");
161
        }
162
163
        if ($this->hasNode('else')) {
164
            $compiler
165
                ->write("if (!\$context['_iterated']) {\n")
166
                ->indent()
167
                ->subcompile($this->getNode('else'))
168
                ->outdent()
169
                ->write("}\n");
170
        }
171
172
        $compiler->write("\$_parent = \$context['_parent'];\n");
173
174
        // remove some "private" loop variables (needed for nested loops)
175
        $compiler->write('unset($context[\''.$this->getNode('variable')->getNode(0)->getAttribute('name').'\'], $context[\'_iterated\'], $context[\''.$collectionTypeName.'\'], $context[\'_parent\'], $context[\'loop\']);'."\n");
176
177
        if ($this->hasNode('collectionFilters')) {
178
            $compiler->write("unset(\$context['_collection_type_filters']);\n");
179
        }
180
181
        // keep the values set in the inner context for variables defined in the outer context
182
        $compiler->write("\$context = array_intersect_key(\$context, \$_parent) + \$_parent;\n");
183
    }
184
}
185