PluginForeach::postProcessing()   F
last analyzed

Complexity

Conditions 36
Paths > 20000

Size

Total Lines 113
Code Lines 69

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 69
c 0
b 0
f 0
dl 0
loc 113
rs 0
cc 36
nc 86261767
nop 5

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
 * Copyright (c) 2013-2016
4
 *
5
 * @category  Library
6
 * @package   Dwoo\Plugins\Blocks
7
 * @author    Jordi Boggiano <[email protected]>
8
 * @author    David Sanchez <[email protected]>
9
 * @copyright 2008-2013 Jordi Boggiano
10
 * @copyright 2013-2016 David Sanchez
11
 * @license   http://dwoo.org/LICENSE Modified BSD License
12
 * @version   1.3.0
13
 * @date      2016-09-19
14
 * @link      http://dwoo.org/
15
 */
16
17
namespace Dwoo\Plugins\Blocks;
18
19
use Dwoo\Compiler;
20
use Dwoo\IElseable;
21
use Dwoo\Block\Plugin as BlockPlugin;
22
use Dwoo\ICompilable\Block as ICompilableBlock;
23
use Dwoo\Compilation\Exception as CompilationException;
24
25
/**
26
 * Similar to the php foreach block, loops over an array.
27
 * Note that if you don't provide the item parameter, the key will act as item
28
 * <pre>
29
 *  * from : the array that you want to iterate over
30
 *  * key : variable name for the key (or for the item if item is not defined)
31
 *  * item : variable name for each item
32
 *  * name : foreach name to access it's iterator variables through {$.foreach.name.var} see {@link
33
 *  http://wiki.dwoo.org/index.php/IteratorVariables} for details
34
 * </pre>
35
 * Example :
36
 * <code>
37
 * {foreach $array val}
38
 *   {$val.something}
39
 * {/foreach}
40
 * </code>
41
 * This software is provided 'as-is', without any express or implied warranty.
42
 * In no event will the authors be held liable for any damages arising from the use of this software.
43
 */
44
class PluginForeach extends BlockPlugin implements ICompilableBlock, IElseable
45
{
46
    public static $cnt = 0;
47
48
    /**
49
     * @param        $from
50
     * @param null   $key
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $key is correct as it would always require null to be passed?
Loading history...
51
     * @param null   $item
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $item is correct as it would always require null to be passed?
Loading history...
52
     * @param string $name
53
     * @param null   $implode
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $implode is correct as it would always require null to be passed?
Loading history...
54
     */
55
    public function init($from, $key = null, $item = null, $name = 'default', $implode = null)
0 ignored issues
show
Unused Code introduced by
The parameter $implode is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

55
    public function init($from, $key = null, $item = null, $name = 'default', /** @scrutinizer ignore-unused */ $implode = null)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $item is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

55
    public function init($from, $key = null, /** @scrutinizer ignore-unused */ $item = null, $name = 'default', $implode = null)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $name is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

55
    public function init($from, $key = null, $item = null, /** @scrutinizer ignore-unused */ $name = 'default', $implode = null)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $key is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

55
    public function init($from, /** @scrutinizer ignore-unused */ $key = null, $item = null, $name = 'default', $implode = null)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $from is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

55
    public function init(/** @scrutinizer ignore-unused */ $from, $key = null, $item = null, $name = 'default', $implode = null)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
56
    {
57
    }
58
59
    /**
60
     * @param Compiler $compiler
61
     * @param array    $params
62
     * @param string   $prepend
63
     * @param string   $append
64
     * @param string   $type
65
     *
66
     * @return string
67
     */
68
    public static function preProcessing(Compiler $compiler, array $params, $prepend, $append, $type)
69
    {
70
        // get block params and save the current template pointer to use it in the postProcessing method
71
        $currentBlock                         = &$compiler->getCurrentBlock();
72
        $currentBlock['params']['tplPointer'] = $compiler->getPointer();
73
74
        return '';
75
    }
76
77
    /**
78
     * @param Compiler $compiler
79
     * @param array    $params
80
     * @param string   $prepend
81
     * @param string   $append
82
     * @param string   $content
83
     *
84
     * @return string
85
     * @throws CompilationException
86
     */
87
    public static function postProcessing(Compiler $compiler, array $params, $prepend, $append, $content)
88
    {
89
        $params = $compiler->getCompiledParams($params);
90
        $tpl    = $compiler->getTemplateSource($params['tplPointer']);
91
92
        // assigns params
93
        $src = $params['from'];
94
95
        if ($params['item'] !== 'null') {
96
            if ($params['key'] !== 'null') {
97
                $key = $params['key'];
98
            }
99
            $val = $params['item'];
100
        } elseif ($params['key'] !== 'null') {
101
            $val = $params['key'];
102
        } else {
103
            throw new CompilationException($compiler, 'Foreach <em>item</em> parameter missing');
0 ignored issues
show
Bug introduced by
'Foreach <em>item</em> parameter missing' of type string is incompatible with the type integer expected by parameter $message of Dwoo\Compilation\Exception::__construct(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

103
            throw new CompilationException($compiler, /** @scrutinizer ignore-type */ 'Foreach <em>item</em> parameter missing');
Loading history...
104
        }
105
        $name = $params['name'];
106
107
        if (substr($val, 0, 1) !== '"' && substr($val, 0, 1) !== '\'') {
108
            throw new CompilationException($compiler, 'Foreach <em>item</em> parameter must be of type string');
109
        }
110
        if (isset($key) && substr($val, 0, 1) !== '"' && substr($val, 0, 1) !== '\'') {
111
            throw new CompilationException($compiler, 'Foreach <em>key</em> parameter must be of type string');
112
        }
113
114
        // evaluates which global variables have to be computed
115
        $varName       = '$dwoo.foreach.' . trim($name, '"\'') . '.';
116
        $shortVarName  = '$.foreach.' . trim($name, '"\'') . '.';
117
        $usesAny       = strpos($tpl, $varName) !== false || strpos($tpl, $shortVarName) !== false;
118
        $usesFirst     = strpos($tpl, $varName . 'first') !== false || strpos($tpl, $shortVarName . 'first') !== false;
119
        $usesLast      = strpos($tpl, $varName . 'last') !== false || strpos($tpl, $shortVarName . 'last') !== false;
120
        $usesIndex     = $usesFirst || strpos($tpl, $varName . 'index') !== false || strpos($tpl, $shortVarName . 'index') !== false;
121
        $usesIteration = $usesLast || strpos($tpl, $varName . 'iteration') !== false || strpos($tpl, $shortVarName . 'iteration') !== false;
122
        $usesShow      = strpos($tpl, $varName . 'show') !== false || strpos($tpl, $shortVarName . 'show') !== false;
123
        $usesTotal     = $usesLast || strpos($tpl, $varName . 'total') !== false || strpos($tpl, $shortVarName . 'total') !== false;
124
125
        if (strpos($name, '$this->scope[') !== false) {
126
            $usesAny = $usesFirst = $usesLast = $usesIndex = $usesIteration = $usesShow = $usesTotal = true;
127
        }
128
129
        // override globals vars if implode is used
130
        if ($params['implode'] !== 'null') {
131
            $implode       = $params['implode'];
132
            $usesAny       = true;
133
            $usesLast      = true;
134
            $usesIteration = true;
135
            $usesTotal     = true;
136
        }
137
138
        // gets foreach id
139
        $cnt = self::$cnt ++;
140
141
        // build pre content output
142
        $pre = Compiler::PHP_OPEN . "\n" . '$_fh' . $cnt . '_data = ' . $src . ';';
143
        // adds foreach properties
144
        if ($usesAny) {
145
            $pre .= "\n" . '$this->globals["foreach"][' . $name . '] = array' . "\n(";
146
            if ($usesIndex) {
147
                $pre .= "\n\t" . '"index"		=> 0,';
148
            }
149
            if ($usesIteration) {
150
                $pre .= "\n\t" . '"iteration"		=> 1,';
151
            }
152
            if ($usesFirst) {
153
                $pre .= "\n\t" . '"first"		=> null,';
154
            }
155
            if ($usesLast) {
156
                $pre .= "\n\t" . '"last"		=> null,';
157
            }
158
            if ($usesShow) {
159
                $pre .= "\n\t" . '"show"		=> $this->isArray($_fh' . $cnt . '_data, true),';
160
            }
161
            if ($usesTotal) {
162
                $pre .= "\n\t" . '"total"		=> $this->count($_fh' . $cnt . '_data),';
163
            }
164
            $pre .= "\n);\n" . '$_fh' . $cnt . '_glob =& $this->globals["foreach"][' . $name . '];';
165
        }
166
        // checks if foreach must be looped
167
        $pre .= "\n" . 'if ($this->isTraversable($_fh' . $cnt . '_data' . (isset($params['hasElse']) ? ', true' : '') . ') == true)' . "\n{";
168
        // iterates over keys
169
        $pre .= "\n\t" . 'foreach ($_fh' . $cnt . '_data as ' . (isset($key) ? '$this->scope[' . $key . ']=>' : '') . '$this->scope[' . $val . '])' . "\n\t{";
170
        // updates properties
171
        if ($usesFirst) {
172
            $pre .= "\n\t\t" . '$_fh' . $cnt . '_glob["first"] = (string) ($_fh' . $cnt . '_glob["index"] === 0);';
173
        }
174
        if ($usesLast) {
175
            $pre .= "\n\t\t" . '$_fh' . $cnt . '_glob["last"] = (string) ($_fh' . $cnt . '_glob["iteration"] === $_fh' . $cnt . '_glob["total"]);';
176
        }
177
        $pre .= "\n/* -- foreach start output */\n" . Compiler::PHP_CLOSE;
178
179
        // build post content output
180
        $post = Compiler::PHP_OPEN . "\n";
181
182
        if (isset($implode)) {
183
            $post .= '/* -- implode */' . "\n" . 'if (!$_fh' . $cnt . '_glob["last"]) {' . "\n\t" . 'echo ' . $implode . ";\n}\n";
184
        }
185
        $post .= '/* -- foreach end output */';
186
        // update properties
187
        if ($usesIndex) {
188
            $post .= "\n\t\t" . '$_fh' . $cnt . '_glob["index"]+=1;';
189
        }
190
        if ($usesIteration) {
191
            $post .= "\n\t\t" . '$_fh' . $cnt . '_glob["iteration"]+=1;';
192
        }
193
        // end loop
194
        $post .= "\n\t}\n}" . Compiler::PHP_CLOSE;
195
        if (isset($params['hasElse'])) {
196
            $post .= $params['hasElse'];
197
        }
198
199
        return $pre . $content . $post;
200
    }
201
}
202