Completed
Pull Request — master (#7)
by Stefan
03:14
created

WidthCalculator   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 1 Features 0
Metric Value
wmc 6
c 2
b 1
f 0
lcom 1
cbo 2
dl 0
loc 51
ccs 15
cts 15
cp 1
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getCellWidth() 0 13 4
A setFont() 0 4 1
1
<?php
2
3
namespace OneSheet\Width;
4
5
use OneSheet\Style\Font;
6
7
/**
8
 * Class WidthCalculator to calculate the approximate width of
9
 * a cell content.
10
 *
11
 * @package OneSheet\Width
12
 */
13
class WidthCalculator
14
{
15
    /**
16
     * @var WidthCollection
17
     */
18
    private $widthCollection;
19
20
    /**
21
     * @var array
22
     */
23
    private $characterWidths;
24
25
    /**
26
     * Calculator constructor.
27
     */
28 5
    public function __construct()
29
    {
30 5
        $this->widthCollection = new WidthCollection();
31 5
    }
32
33
    /**
34
     * Returns a approximate width of a cell value.
35
     *
36
     * @param mixed $value
37
     * @param bool  $isBold
38
     * @return float
39
     */
40 2
    public function getCellWidth($value, $isBold)
41
    {
42 2
        $width = 1;
43 2
        foreach (str_split($value) as $character) {
44 2
            if (isset($this->characterWidths[$character])) {
45 2
                $width += $this->characterWidths[$character];
46 2
            } else {
47 1
                $width += 0.66;
48
            }
49 2
        }
50
51 2
        return $isBold ? $width * 1.09 : $width;
52
    }
53
54
    /**
55
     * Set proper font sizes by font.
56
     *
57
     * @param Font $font
58
     */
59 2
    public function setFont(Font $font)
60
    {
61 2
        $this->characterWidths = $this->widthCollection->get($font->getName(), $font->getSize());
62 2
    }
63
}
64