LeftoverFiller   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 23
c 1
b 0
f 0
dl 0
loc 63
rs 10
wmc 8

3 Methods

Rating   Name   Duplication   Size   Complexity  
A cleanUp() 0 10 3
A fill() 0 27 4
A __construct() 0 5 1
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
    private Calculator $calculator;
24
    private Operations $operations;
25
    
26
   /**
27
    * @var Column[]
28
    */
29
    private array $columns;
30
    
31
    public function __construct(Calculator $calculator)
32
    {
33
        $this->calculator = $calculator;
34
        $this->operations = $calculator->getOperations();
35
        $this->columns = $calculator->getColumns();
36
    }
37
    
38
    public function fill() : void
39
    {
40
        $leftover = $this->calculator->getMaxTotal() - $this->operations->calcTotal();
41
        $perCol = $leftover / $this->operations->countColumns();
42
43
        if($this->calculator->isIntegerMode())
44
        {
45
            $perCol = (int)ceil($perCol);
46
        }
47
48
        for($i=($this->operations->countColumns()-1); $i >=0; $i--)
49
        {
50
            if($leftover <= 0)
51
            {
52
                break;
53
            }
54
            
55
            $leftover -= $perCol;
56
            
57
            $col = $this->columns[$i];
58
            
59
            $val = $col->getValue() + $perCol;
60
            
61
            $col->setValue($val);
62
        }
63
64
        $this->cleanUp($leftover);
65
    }
66
    
67
   /**
68
    * In integer mode, after filling all items, because of rounding
69
    * the amount of column up, we may have added a bit too much. We
70
    * fix this here, by removing it from the last column.
71
    * 
72
    * @param float $leftover
73
    */
74
    private function cleanUp(float $leftover) : void
75
    {
76
        if($leftover >= 0 || empty($this->columns))
77
        {
78
            return;
79
        }
80
81
        $col = array_pop($this->columns);
82
        
83
        $col->setValue($col->getValue() + $leftover);
84
    }
85
}
86