LazyCollection::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
1
<?php declare(strict_types=1);
2
3
namespace Zalas\Collection;
4
5
use Closure;
6
use Traversable;
7
8
final class LazyCollection implements Collection
9
{
10
    private $elements;
11
12 10
    public function __construct(Traversable $elements)
13
    {
14 10
        $this->elements = $elements;
15
    }
16
17 9
    public function getIterator(): Traversable
18
    {
19 9
        yield from $this->elements;
20
    }
21
22 2
    public function merge(Collection $other): Collection
23
    {
24
        return self::createFromClosure(function () use ($other) {
25 2
            foreach ($this as $e) {
26 2
                yield $e;
27
            }
28 2
            foreach ($other as $e) {
29 2
                yield $e;
30
            }
31 2
        });
32
    }
33
34 2
    public function filter(callable $f): Collection
35
    {
36
        return self::createFromClosure(function () use ($f) {
37 2
            foreach ($this as $e) {
38 2
                if ($f($e)) {
39 2
                    yield $e;
40
                }
41
            }
42 2
        });
43
    }
44
45 2
    public function map(callable $f): Collection
46
    {
47
        return self::createFromClosure(function () use ($f) {
48 2
            foreach ($this as $e) {
49 2
                yield $f($e);
50
            }
51 2
        });
52
    }
53
54
    /**
55
     * @param mixed $initial
56
     * @param callable $f
57
     *
58
     * @return mixed
59
     */
60 1
    public function reduce($initial, callable $f)
61
    {
62 1
        return \array_reduce(\iterator_to_array($this), $f, $initial);
63
    }
64
65 6
    private static function createFromClosure(Closure $f): Collection
66
    {
67 6
        return new self($f());
68
    }
69
}
70