Completed
Push — master ( 63f743...cd2958 )
by Hiraku
01:37
created

Collection::column()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 11
ccs 9
cts 9
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 8
nc 2
nop 1
crap 2
1
<?php
2
namespace Spindle\Collection;
3
4
class Collection implements \IteratorAggregate
5
{
6
    use Traits\SortTrait;
7
    use Traits\SetsTrait;
8
    use Traits\TerminateTrait;
9
    use Traits\LimitTrait;
10
11
    const TYPE_FOR = 'for';
12
    const TYPE_FOREACH = 'foreach';
13
14
    private $type = self::TYPE_FOREACH;
15
    private $debug = false;
16
17
    private $ops = [];
18
    private $seed;
19
    private $is_array;
20
    private $vars = [];
21
    private $fn_cnt = 0;
22
23
    /**
24
     * @return \Spindle\Collection
25
     */
26 7
    public static function from($iterable, $debug = null)
27
    {
28 7
        return new static($iterable, $debug);
29
    }
30
31
    /**
32
     * Generator-based range()
33
     * @param int|string $start
34
     * @param int|string $end
35
     * @param int $step
36
     * @param bool $debug
37
     * @return \Spindle\Collection
38
     */
39 13
    public static function range($start, $end, $step = 1, $debug = null)
40
    {
41 13
        if (!is_int($step) || $step < 1) {
42
            throw new \InvalidArgumentException('$step must be natural number: ' . $step);
43
        }
44 13
        if (is_numeric($start) && is_numeric($end)) {
45
            $seed = [
46 13
                '$_current = ' . $start,
47 13
                '$_current <= ' . $end,
48 13
                $step === 1 ? '++$_current' : '$_current += ' . $step,
49 13
            ];
50 13
        } else {
51
            $seed = [
52
                '$_current = ' . var_export($start, 1),
53
                '$_current <= ' . var_export($end, 1),
54
                implode(',', array_fill(0, $step, '++$_current')),
55
            ];
56
        }
57 13
        return new static($seed, $debug, self::TYPE_FOR);
0 ignored issues
show
Documentation introduced by
$seed is of type array<integer,string,{"0..."string","2":"string"}>, but the function expects a object<Spindle\Collection\iterable>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
58
    }
59
60
    /**
61
     * Generator-based repeat()
62
     * @param mixed $elem
63
     * @param int $count
64
     * @param bool $debug
65
     */
66 2
    public static function repeat($elem, $count, $debug = null)
67
    {
68 2
        if (!is_int($count) || $count < 0) {
69 1
            throw new \InvalidArgumentException('$count must be int >= 0. given: ' . gettype($count));
70
        }
71
        $seed = [
72 1
            '$_current = $_elem, $_count = ' . var_export($count, 1),
73 1
            '$_count > 0',
74
            '--$_count'
75 1
        ];
76 1
        $collection = new static($seed, $debug, self::TYPE_FOR);
0 ignored issues
show
Documentation introduced by
$seed is of type array<integer,string,{"0..."string","2":"string"}>, but the function expects a object<Spindle\Collection\iterable>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
77 1
        $collection->vars['_elem'] = $elem;
78 1
        return $collection;
79
    }
80
81
    /**
82
     * @param iterable $seed
83
     */
84 21
    public function __construct($seed, $debug = null, $type = null)
85
    {
86 21
        if (!is_array($seed) && !is_object($seed)) {
87 1
            throw new \InvalidArgumentException('$seed should be iterable, given ' . gettype($seed));
88
        }
89 20
        $this->seed = $seed;
90 20
        if ($debug) {
91
            $this->debug = true;
92
        }
93 20
        if ($type === self::TYPE_FOR) {
94 14
            $this->type = $type;
95 14
            $this->is_array = false;
96 14
            return;
97
        }
98 10
        $this->is_array = is_array($seed);
99 10
    }
100
101 8
    private function step()
102
    {
103 8
        if ($this->debug) {
104
            $this->toArray();
105
            return $this;
106
        }
107 8
        return $this;
108
    }
109
110
    /**
111
     * @param string|callable $fn '$_ * 2'
112
     * @return $this
113
     */
114 4 View Code Duplication
    public function map($fn)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
115
    {
116 4
        $this->is_array = false;
117 4
        if (is_callable($fn)) {
118 1
            $fn_name = '_fn' . $this->fn_cnt++;
119 1
            $this->vars[$fn_name] = $fn;
120 1
            $this->ops[] = '    $_ = $' . $fn_name . '($_);';
121 1
        } else {
122 4
            $this->ops[] = '    $_ = ' . $fn . ';';
123
        }
124 4
        return $this->step();
125
    }
126
127
    /**
128
     * @param string|string[] columns
129
     * @return $this
130
     */
131 1
    public function column($columns)
132
    {
133 1
        $this->is_array = false;
134 1
        if (is_array($columns)) {
135 1
            $defs = [];
136 1
            foreach ($columns as $key) {
137 1
                $exported = var_export($key, 1);
138 1
                $defs[] = "$exported => \$_[$exported]";
139 1
            }
140 1
            $this->ops[] = '    $_ = [' . implode(',', $defs) . '];';
141 1
        } else {
142
            $exported = var_export($key, 1);
0 ignored issues
show
Bug introduced by
The variable $key seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
Unused Code introduced by
$exported is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
143
            $this->ops[] = "    \$_ = \$_[$key];";
0 ignored issues
show
Bug introduced by
The variable $key seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
144
        }
145 1
        return $this->step();
146
    }
147
148
    /**
149
     * @return \Spindle\Collection (new instance)
150
     */
151 1
    public function flip()
152
    {
153 1
        $this->is_array = false;
154 1
        $this->ops[] = '    list($_key, $_) = [$_, $_key];';
155 1
        return $this->step();
156
    }
157
158
    /**
159
     * @return \Generator|\ArrayIterator
160
     */
161 1
    public function getIterator()
162
    {
163 1
        if ($this->is_array) {
164
            return new \ArrayIterator($this->seed);
165
        }
166 1
        $ops = $this->ops;
167 1
        $ops[] = 'yield $_key => $_;';
168 1
        $gen = self::evaluate(
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $gen is correct as self::evaluate($this->se...() use($_seed){', '};') (which targets Spindle\Collection\Collection::evaluate()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
169 1
            $this->seed,
170 1
            $this->vars,
171 1
            $this->compile($ops),
172 1
            '$_result = static function() use($_seed){',
173
            '};'
174 1
        );
175 1
        return $gen();
176
    }
177
178
    /**
179
     * @return array
180
     */
181 12
    public function toArray()
182
    {
183 12
        if ($this->is_array) {
184 6
            return $this->seed;
185
        }
186 8
        $ops = $this->ops;
187 8
        $ops[] = '    $_result[$_key] = $_;';
188 8
        $array = self::evaluate(
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $array is correct as self::evaluate($this->se..., '$_result = [];', '') (which targets Spindle\Collection\Collection::evaluate()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
189 8
            $this->seed,
190 8
            $this->vars,
191 8
            $this->compile($ops),
192 8
            '$_result = [];',
193
            ''
194 8
        );
195 8
        $this->type = self::TYPE_FOREACH;
196 8
        $this->is_array = true;
197 8
        $this->ops = [];
198 8
        $this->seed = $array;
199 8
        $this->vars = [];
200 8
        $this->fn_cnt = 0;
201 8
        return $array;
202
    }
203
204
    /**
205
     * @return $this
206
     */
207 1
    public function dump()
208
    {
209 1
        var_dump($this);
0 ignored issues
show
Security Debugging Code introduced by
var_dump($this); looks like debug code. Are you sure you do not want to remove it? This might expose sensitive data.
Loading history...
210 1
        return $this;
211
    }
212
213
    /**
214
     * @return $this
215
     */
216 1
    public function assignTo(&$var = null)
217
    {
218 1
        $var = new $this($this->toArray());
219 1
        return $var;
220
    }
221
222
    /**
223
     * @return $this
224
     */
225 1
    public function assignArrayTo(&$var = null)
226
    {
227 1
        $var = $this->toArray();
228 1
        return $this;
229
    }
230
231
    /**
232
     * @return string
233
     */
234 1
    public function __toString()
235
    {
236 1
        return implode("\n", [
237 1
            static::class,
238 1
            ' array-mode:' . (int)$this->is_array,
239 1
            " codes:\n  " . implode("\n  ", $this->ops)
240 1
        ]);
241
    }
242
243
    /**
244
     * @return array
245
     */
246 1
    public function __debugInfo()
247
    {
248 1
        if (is_array($this->seed)) {
249 1
            $cnt = count($this->seed);
250 1
            if ($cnt === 0) {
251 1
                $seed = "empty array()";
252 1
            } else {
253 1
                $first = gettype(current($this->seed));
254 1
                $seed = "array($first, ...($cnt items))";
255
            }
256 1
        } else {
257 1
            $seed = get_class($this->seed);
258
        }
259
        return [
260 1
            'seed' => $seed,
261 1
            'code' => $this->compile($this->ops),
262 1
        ];
263
    }
264
265
    private static function evaluate($_seed, $_vars, $_code, $_before, $_after)
0 ignored issues
show
Unused Code introduced by
The parameter $_seed is not used and could be removed.

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

Loading history...
266
    {
267 14
        $_old_handler = set_error_handler(function($severity, $message, $file, $line){
268
            throw new \ErrorException($message, 0, $severity, $file, $line);
269 14
        }, E_ALL ^ E_DEPRECATED ^ E_USER_DEPRECATED);
270
        try {
271 14
            $_result = null;
272 14
            extract($_vars);
273 14
            eval("$_before \n $_code \n $_after");
0 ignored issues
show
Coding Style introduced by
It is generally not recommended to use eval unless absolutely required.

On one hand, eval might be exploited by malicious users if they somehow manage to inject dynamic content. On the other hand, with the emergence of faster PHP runtimes like the HHVM, eval prevents some optimization that they perform.

Loading history...
274 14
        } catch (\ParseError $e) {
0 ignored issues
show
Bug introduced by
The class ParseError does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
275
            throw new \RuntimeException($e->getMessage(), $e->getCode(), $e);
276 14
        } finally {
277 14
            set_error_handler($_old_handler);
278
        }
279 14
        return $_result;
280
    }
281
282 15
    private function compile($ops)
283
    {
284 15
        if ($this->type === self::TYPE_FOR) {
285 12
            return $this->compileFor($ops, $this->seed);
286
        }
287
288 3
        return $this->compileForeach($ops);
289
    }
290
291 12
    private static function compileFor($ops, $seed)
292
    {
293 12
        array_unshift(
294 12
            $ops,
295 12
            '$_i = 0;',
296 12
            'for (' . implode('; ', $seed). ') {',
297 12
            '    $_key = $_i;',
298 12
            '    $_ = $_current;',
299
            '    ++$_i;'
300 12
        );
301 12
        $ops[] = '}';
302
303 12
        return implode("\n", $ops);
304
    }
305
306 3
    private static function compileForeach($ops)
307
    {
308 3
        array_unshift(
309 3
            $ops,
310 3
            '$_i = 0;',
311 3
            'foreach ($_seed as $_key => $_) {',
312
            '    ++$_i;'
313 3
        );
314 3
        $ops[] = '}';
315
316 3
        return implode("\n", $ops);
317
    }
318
}
319