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

IntegerDistributor   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Importance

Changes 1
Bugs 1 Features 0
Metric Value
wmc 7
lcom 0
cbo 0
dl 0
loc 41
rs 10
c 1
b 1
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
B distribute() 0 25 5
A validateNumberOfTargets() 0 4 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