Passed
Pull Request — master (#2)
by Pol
03:09
created

Partitions::partition()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types = 1);
4
5
namespace drupol\phpartition\Partitions;
6
7
use drupol\phpartition\Partition\Partition;
8
use drupol\phpartition\Partition\PartitionFactory;
9
10
class Partitions implements \Countable
11
{
12
    /**
13
     * @var array
14
     */
15
    private $storage;
16
17
    /**
18
     * Partitions constructor.
19
     *
20
     * @param int $size
21
     * @param \drupol\phpartition\Partition\PartitionFactory $partitionFactory
22
     */
23
    public function __construct(int $size, PartitionFactory $partitionFactory = null)
24
    {
25
        $this->storage['size'] = $size;
26
        $partitionFactory = $partitionFactory ?? new PartitionFactory();
27
28
        for ($i = 0; $i < $size; ++$i) {
29
            $this->storage['partitions'][$i] = $partitionFactory::create();
30
        }
31
    }
32
33
    /**
34
     * {@inheritdoc}
35
     */
36
    public function count()
37
    {
38
        return \count($this->storage['partitions']);
39
    }
40
41
    /**
42
     * @param int $index
43
     *
44
     * @return \drupol\phpartition\Partition\Partition
45
     */
46
    public function partition(int $index)
47
    {
48
        return $this->storage['partitions'][$index];
49
    }
50
51
    /**
52
     * @return \drupol\phpartition\Partition\Partition[]
53
     */
54
    public function partitions()
55
    {
56
        return $this->storage['partitions'];
57
    }
58
59
    /**
60
     * @param null|callable $compareCallable
61
     *
62
     * @return \drupol\phpartition\Partitions\Partitions
63
     */
64
    public function sort(callable $compareCallable = null)
65
    {
66
        if (null === $compareCallable) {
67
            $compareCallable = static function (Partition $item1, Partition $item2) {
68
                return $item1->getWeight() <=> $item2->getWeight();
69
            };
70
        }
71
72
        \usort($this->storage['partitions'], $compareCallable);
73
74
        return $this;
75
    }
76
}
77