Completed
Push — master ( d998d0...abb41b )
by Kamil
38:34
created

IntegerDistributor::distribute()   B

Complexity

Conditions 6
Paths 9

Size

Total Lines 25
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 2 Features 0
Metric Value
c 2
b 2
f 0
dl 0
loc 25
rs 8.439
cc 6
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\Bundle\CoreBundle\Distributor;
13
14
/**
15
 * @author Mateusz Zalewski <[email protected]>
16
 */
17
class IntegerDistributor implements IntegerDistributorInterface
18
{
19
    /**
20
     * {@inheritdoc}
21
     */
22
    public function distribute($numberOfTargets, $baseAmount)
23
    {
24
        if (!is_int($numberOfTargets) || 1 > $numberOfTargets) {
25
            throw new \InvalidArgumentException('Number of targets must be an integer, bigger than 0.');
26
        }
27
28
        $sign = $baseAmount < 0 ? -1 : 1;
29
        $amount = abs($baseAmount);
30
31
        $low = intval($amount / $numberOfTargets);
32
        $high = $low + 1;
33
34
        $remainder = $amount % $numberOfTargets;
35
        $result = array();
36
37
        for ($i = 0; $i < $remainder; $i++) {
38
            $result[] = $high * $sign;
39
        }
40
41
        for ($i = $remainder; $i < $numberOfTargets; $i++) {
42
            $result[] = $low * $sign;
43
        }
44
45
        return $result;
46
    }
47
}
48