Passed
Push — master ( 4ee1ca...f0c776 )
by Maxim
02:45 queued 10s
created

CollectionFactory::fromStrict()   A

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
eloc 1
c 1
b 0
f 0
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
1
<?php
2
/**
3
 * @author Maxim Sokolovsky
4
 */
5
6
namespace WS\Utils\Collections;
7
8
use RuntimeException;
9
10
class CollectionFactory
11
{
12
    use CollectionConstructorTrait;
13
14
    /**
15
     * Returns collection generated with generator <f(int $index): mixed> for $times
16
     * @param int $times
17
     * @param callable|null $generator
18
     * @return Collection
19
     */
20 5
    public static function generate(int $times, ?callable $generator = null): Collection
21
    {
22 5
        if ($times < 0) {
23 1
            throw new RuntimeException('The count of values ($times) must be a positive value');
24
        }
25
        $generator = $generator ?? static function (int $index) {
26 3
            return $index;
27 4
        };
28
29 4
        $collection = self::toCollection();
30 4
        for ($i = 0; $i < $times; $i++) {
31 4
            $collection->add($generator($i));
32
        }
33
34 4
        return $collection;
35
    }
36
37
    /**
38
     * Generate collection of int numbers between $from and $to. If $to arg is absent $from - is count of numbers
39
     * @param int $from
40
     * @param int $to
41
     * @return Collection
42
     */
43 23
    public static function numbers(int $from, ?int $to = null): Collection
44
    {
45 23
        if ($to === null) {
46 22
            $to = $from - 1;
47 22
            $from = 0;
48
        }
49
50 23
        if ($from > $to) {
51 1
            throw new RuntimeException('FROM need to be less than TO');
52
        }
53 23
        $list = new ArrayList();
54 23
        for ($i = $from; $i <= $to; $i++) {
55 23
            $list->add($i);
56
        }
57
58 23
        return $list;
59
    }
60
61 40
    public static function from(array $values): Collection
62
    {
63 40
        return new ArrayList($values);
64
    }
65
66 1
    public static function fromStrict(array $values): Collection
67
    {
68 1
        return new ArrayStrictList($values);
69
    }
70
71 1
    public static function fromIterable(iterable $iterable): Collection
72
    {
73 1
        $list = ArrayList::of();
74 1
        foreach ($iterable as $item) {
75 1
            $list->add($item);
76
        }
77
78 1
        return $list;
79
    }
80
81 7
    public static function empty(): Collection
82
    {
83 7
        return ArrayList::of();
84
    }
85
}
86