Passed
Push — master ( 9c4b3c...2ae703 )
by Sebastian
02:13
created

LeftoverFiller::cleanUp()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 1
dl 0
loc 10
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * File containing the {@see Mistralys\WidthsCalculator\Calculator\LeftoverFiller} class.
4
 *
5
 * @package WidthsCalculator
6
 * @see Mistralys\WidthsCalculator\Calculator\LeftoverFiller
7
 */
8
9
declare (strict_types=1);
10
11
namespace Mistralys\WidthsCalculator\Calculator;
12
13
use Mistralys\WidthsCalculator\Calculator;
14
15
/**
16
 * Handles filling any percentages missing to reach the full 100%.
17
 *
18
 * @package WidthsCalculator
19
 * @author Sebastian Mordziol <[email protected]>
20
 */
21
class LeftoverFiller
22
{
23
    /**
24
     * @var Calculator
25
     */
26
    private $calculator;
27
    
28
    /**
29
     * @var Operations
30
     */
31
    private $operations;
32
    
33
   /**
34
    * @var Column[]
35
    */
36
    private $columns = array();
37
    
38
    public function __construct(Calculator $calculator)
39
    {
40
        $this->calculator = $calculator;
41
        $this->operations = $calculator->getOperations();
42
        $this->columns = $calculator->getColumns();
43
    }
44
    
45
    public function fill() : void
46
    {
47
        $leftover = $this->calculator->getMaxTotal() - $this->operations->calcTotal();
48
        $perCol = $leftover / $this->operations->countColumns();
49
50
        if($this->calculator->isIntegerMode())
51
        {
52
            $perCol = (int)ceil($perCol);
53
        }
54
55
        for($i=($this->operations->countColumns()-1); $i >=0; $i--)
56
        {
57
            if($leftover <= 0)
58
            {
59
                break;
60
            }
61
            
62
            $leftover -= $perCol;
63
            
64
            $col = $this->columns[$i];
65
            
66
            $val = $col->getValue() + $perCol;
67
            
68
            $col->setValue($val);
69
        }
70
71
        $this->cleanUp($leftover);
72
    }
73
    
74
   /**
75
    * In integer mode, after filling all items, because of rounding
76
    * the amount of column up, we may have added a bit too much. We
77
    * fix this here, by removing it from the last column.
78
    * 
79
    * @param float $leftover
80
    */
81
    private function cleanUp(float $leftover) : void
82
    {
83
        if($leftover >= 0)
84
        {
85
            return;
86
        }
87
        
88
        $col = array_pop($this->columns);
89
        
90
        $col->setValue($col->getValue() + $leftover);
91
    }
92
}
93