Collection   A
last analyzed

Complexity

Total Complexity 13

Size/Duplication

Total Lines 79
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 90.32%

Importance

Changes 0
Metric Value
wmc 13
lcom 1
cbo 1
dl 0
loc 79
ccs 28
cts 31
cp 0.9032
rs 10
c 0
b 0
f 0

11 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A addOne() 0 9 2
A addAll() 0 6 1
A count() 0 4 1
A immutable() 0 4 1
A cmp() 0 6 2
A where() 0 6 1
A sort() 0 6 1
A limit() 0 6 1
A get() 0 4 1
A getGeneric() 0 4 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