Passed
Push — master ( e9e132...801188 )
by compolom
02:22
created

Collection::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
1
<?php declare(strict_types=1);
2
3
namespace Compolomus\Collection;
4
5
use Compolomus\Collection\Linq;
6
use InvalidArgumentException;
7
8
class Collection
9
{
10
    public const ASC = 1;
11
    public const DESC = 0;
12
13
    private $generic;
14
15
    private $collection = [];
16
17 13
    public function __construct(string $class)
18
    {
19 13
        $this->generic = $class;
20 13
    }
21
22 10
    public function addOne(object $object): self
23
    {
24 10
        if (!($object instanceof $this->generic)) {
25 2
            throw new InvalidArgumentException('Object mast be instanceof ' . $this->generic . ' class, ' . get_class($object) . ' given');
26
        }
27 10
        $this->collection[] = $object;
28
29 10
        return $this;
30
    }
31
32 5
    public function addAll(array $objects): self
33
    {
34 5
        array_map([$this, 'addOne'], $objects);
35
36 5
        return $this;
37
    }
38
39 3
    public function count(): int
40
    {
41 3
        return count($this->collection);
42
    }
43
44 2
    public function immutable(): self
45
    {
46 2
        return clone $this;
47
    }
48
49 3
    public function getGeneric(): string
50
    {
51 3
        return $this->generic;
52
    }
53
54 1
    private function cmp(string $key, int $order): callable
55
    {
56
        return static function (object $a, object $b) use ($key, $order) {
57 1
            return $order ? $a->$key <=> $b->$key : $b->$key <=> $a->$key;
58 1
        };
59
    }
60
61
    public function where(string $query): self
62
    {
63
        $linq = new Linq($this);
64
65
        return (new self($this->getGeneric()))->addAll($linq->where($query)->get());
66
    }
67
68 1
    public function sort(string $key, int $order = Collection::ASC): self
69
    {
70 1
        uasort($this->collection, $this->cmp($key, $order));
71
72 1
        return $this;
73
    }
74
75 3
    public function limit(int $limit, int $offset = 0): self
76
    {
77 3
        $this->collection = array_slice($this->collection, $offset, $limit);
78
79 3
        return $this;
80
    }
81
82 6
    public function get(): array
83
    {
84 6
        return $this->collection;
85
    }
86
}
87