Passed
Push — master ( db5775...98efde )
by Maxim
02:20
created

CollectionFactory   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 64
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 10
eloc 24
c 1
b 0
f 0
dl 0
loc 64
ccs 26
cts 26
cp 1
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A from() 0 3 1
A numbers() 0 16 4
A generate() 0 15 3
A fromIterable() 0 8 2
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 8
    public static function numbers(int $from, ?int $to = null): Collection
44
    {
45 8
        if ($to === null) {
46 7
            $to = $from - 1;
47 7
            $from = 0;
48
        }
49
50 8
        if ($from > $to) {
51 1
            throw new RuntimeException('FROM need to be less than TO');
52
        }
53 8
        $list = new ArrayList();
54 8
        for ($i = $from; $i <= $to; $i++) {
55 8
            $list->add($i);
56
        }
57
58 8
        return $list;
59
    }
60
61 24
    public static function from(array $values): Collection
62
    {
63 24
        return new ArrayList($values);
64
    }
65
66 1
    public static function fromIterable(iterable $iterable): Collection
67
    {
68 1
        $list = ArrayList::of();
69 1
        foreach ($iterable as $item) {
70 1
            $list->add($item);
71
        }
72
73 1
        return $list;
74
    }
75
}
76