Completed
Push — master ( bf375b...cc5661 )
by Rafał
07:07
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
     * @param int    $lineno
28
     * @param string $tag
29
     */
30
    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)
31
    {
32
        $body = new \Twig_Node([$body, $this->loop = new \Twig_Node_ForLoop($lineno, $tag)]);
33
34
        if (null !== $ifExpression) {
35
            $body = new \Twig_Node_If(new \Twig_Node([$ifExpression, $body]), null, $lineno, $tag);
36
        }
37
38
        parent::__construct([
39
            'variable' => $variable,
40
            'collectionType' => $collectionType,
41
            'collectionFilters' => $collectionFilters,
42
            'parameters' => $parameters,
43
            'ifExpression' => $ifExpression,
44
            'else' => $else,
45
            'body' => $body,
46
        ], ['with_loop' => true, 'ifexpr' => null !== $ifExpression], $lineno, $tag);
47
    }
48
49
    /**
50
     * {@inheritdoc}
51
     */
52
    public function compile(\Twig_Compiler $compiler)
53
    {
54
        $i = self::$count++;
55
56
        $collectionTypeName = $this->getNode('collectionType')->getNode(0)->getAttribute('name');
57
58
        $compiler
59
            ->addDebugInfo($this);
60
61
        if (!is_null($this->getNode('collectionFilters'))) {
62
            $compiler->write("\$context['_collection_type_filters'] = [];\n");
63
            $compiler->write("\$context['".$collectionTypeName."'] = null;\n");
64
            $compiler->write("\$context['_collection_type_filters'] = ")->subcompile($this->getNode('collectionFilters'))->raw("['_collection_type_filters']; unset(\$context['".$collectionTypeName."']['_collection_type_filters']);\n");
65
66 View Code Duplication
            if (!is_null($this->getNode('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...
67
                $compiler->write('$parameters = array_merge(')->subcompile($this->getNode('parameters'))->raw(", \$context['_collection_type_filters']);\n");
68
            } else {
69
                $compiler->write("\$parameters = \$context['_collection_type_filters'];\n");
70
            }
71 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...
72
            if (!is_null($this->getNode('parameters'))) {
73
                $compiler->raw('$parameters = ')->subcompile($this->getNode('parameters'))->raw(";\n");
74
            } else {
75
                $compiler->raw("\$parameters = [];\n");
76
            }
77
        }
78
79
        $compiler->write('$swpCollectionMetaLoader'.$i." = \$this->env->getExtension('swp_gimme')->getLoader();\n")
80
            ->write('')->subcompile($this->getNode('collectionType'))->raw(' = twig_ensure_traversable($swpCollectionMetaLoader'.$i.'->load("')->raw($collectionTypeName)->raw('", ');
81
        $compiler->raw('$parameters');
82
        $compiler->raw(", \SWP\Component\TemplatesSystem\Gimme\Loader\LoaderInterface::COLLECTION));\n");
83
84
        // the (array) cast bypasses a PHP 5.2.6 bug
85
        $compiler->write("\$context['_parent'] = (array) \$context;\n");
86
87
        if (null !== $this->getNode('else')) {
88
            $compiler->write("\$context['_iterated'] = false;\n");
89
        }
90
91
        if ($this->getAttribute('with_loop')) {
92
            $compiler
93
                ->write("\$context['loop'] = array(\n")
94
                ->write("  'parent' => \$context['_parent'],\n")
95
                ->write("  'index0' => 0,\n")
96
                ->write("  'index'  => 1,\n")
97
                ->write("  'first'  => true,\n")
98
                ->write(");\n");
99
100
            if (!$this->getAttribute('ifexpr') && $this->getNode('collectionType')) {
101
                $compiler
102
                    ->write('if (is_array(')->subcompile($this->getNode('collectionType'))->raw(') || (is_object(')->subcompile($this->getNode('collectionType'))->raw(') && ')->subcompile($this->getNode('collectionType'))->raw(" instanceof Countable)) {\n")
103
                    ->indent()
104
                    ->write('$length = count(')->subcompile($this->getNode('collectionType'))->raw(");\n")
105
                    ->write("\$context['loop']['revindex0'] = \$length - 1;\n")
106
                    ->write("\$context['loop']['revindex'] = \$length;\n")
107
                    ->write("\$context['loop']['length'] = \$length;\n")
108
                    ->write("\$context['loop']['totalLength'] = \$length;\n")
109
                    ->write("\$context['loop']['last'] = 1 === \$length;\n")
110
                    ->outdent()
111
                    ->write("}\n");
112
113
                $compiler
114
                    ->write('if(is_object(')->subcompile($this->getNode('collectionType'))->raw(') && ')->subcompile($this->getNode('collectionType'))->raw(" instanceof \SWP\Component\TemplatesSystem\Gimme\Meta\MetaCollection) {\n")
115
                    ->indent()
116
                    ->write('$context[\'loop\'][\'totalLength\'] = ')->subcompile($this->getNode('collectionType'))->raw("->getTotalItemCount();\n")
117
                    ->outdent()
118
                    ->write("}\n");
119
            }
120
        }
121
122
        $this->loop->setAttribute('else', null !== $this->getNode('else'));
123
        $this->loop->setAttribute('with_loop', $this->getAttribute('with_loop'));
124
        $this->loop->setAttribute('ifexpr', $this->getAttribute('ifexpr'));
125
126
        if (null !== $this->getNode('collectionType')) {
127
            $compiler
128
                ->write('foreach (')
129
                ->subcompile($this->getNode('collectionType'))
130
                ->raw(' as $_key')
131
                ->raw(' => ')
132
                ->subcompile($this->getNode('variable'))
133
                ->raw(") {\n")
134
                ->indent()
135
                ->subcompile($this->getNode('body'))
136
                ->outdent()
137
                ->write("}\n");
138
        }
139
140
        if (null !== $this->getNode('else')) {
141
            $compiler
142
                ->write("if (!\$context['_iterated']) {\n")
143
                ->indent()
144
                ->subcompile($this->getNode('else'))
145
                ->outdent()
146
                ->write("}\n");
147
        }
148
149
        $compiler->write("\$_parent = \$context['_parent'];\n");
150
151
        // remove some "private" loop variables (needed for nested loops)
152
        $compiler->write('unset($context[\''.$this->getNode('variable')->getNode(0)->getAttribute('name').'\'], $context[\'_iterated\'], $context[\''.$collectionTypeName.'\'], $context[\'_parent\'], $context[\'loop\']);'."\n");
153
154
        if (!is_null($this->getNode('collectionFilters'))) {
155
            $compiler->write("unset(\$context['_collection_type_filters']);\n");
156
        }
157
158
        // keep the values set in the inner context for variables defined in the outer context
159
        $compiler->write("\$context = array_intersect_key(\$context, \$_parent) + \$_parent;\n");
160
    }
161
}
162