Completed
Push — master ( 155c16...880d18 )
by Kamil
26:05
created

IntegerDistributor::distribute()   B

Complexity

Conditions 5
Paths 9

Size

Total Lines 25
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
dl 0
loc 25
rs 8.439
c 1
b 1
f 0
cc 5
eloc 14
nc 9
nop 2
1
<?php
2
3
/*
4
 * This file is part of the Sylius package.
5
 *
6
 * (c) Paweł Jędrzejewski
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Sylius\Component\Core\Distributor;
13
14
use Sylius\Component\Core\Distributor\IntegerDistributorInterface;
15
16
/**
17
 * @author Mateusz Zalewski <[email protected]>
18
 */
19
class IntegerDistributor implements IntegerDistributorInterface
20
{
21
    /**
22
     * {@inheritdoc}
23
     */
24
    public function distribute($amount, $numberOfTargets)
25
    {
26
        if (!$this->validateNumberOfTargets($numberOfTargets)) {
27
            throw new \InvalidArgumentException('Number of targets must be an integer, bigger than 0.');
28
        }
29
30
        $sign = $amount < 0 ? -1 : 1;
31
        $amount = abs($amount);
32
33
        $low = (int) ($amount / $numberOfTargets);
34
        $high = $low + 1;
35
36
        $remainder = $amount % $numberOfTargets;
37
        $result = [];
38
39
        for ($i = 0; $i < $remainder; ++$i) {
40
            $result[] = $high * $sign;
41
        }
42
43
        for ($i = $remainder; $i < $numberOfTargets; ++$i) {
44
            $result[] = $low * $sign;
45
        }
46
47
        return $result;
48
    }
49
50
    /**
51
     * @param int $numberOfTargets
52
     *
53
     * @return bool
54
     */
55
    private function validateNumberOfTargets($numberOfTargets)
56
    {
57
        return is_int($numberOfTargets) && 1 <= $numberOfTargets;
58
    }
59
}
60