Completed
Push — master ( da315f...8e06d5 )
by Stefan
03:13
created

WidthCalculator   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 87.5%

Importance

Changes 4
Bugs 1 Features 1
Metric Value
wmc 7
c 4
b 1
f 1
lcom 1
cbo 2
dl 0
loc 51
ccs 14
cts 16
cp 0.875
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A setFont() 0 4 1
B getCellWidth() 0 13 5
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 6
    public function __construct()
29
    {
30 6
        $this->widthCollection = new WidthCollection();
31 6
    }
32
33
    /**
34
     * Returns the estimated width of a cell value.
35
     *
36
     * @param mixed $value
37
     * @param Font  $font
38
     * @return float
39
     */
40 3
    public function getCellWidth($value, Font $font)
41
    {
42 3
        $width = 0.07 * $font->getSize();
43 3
        foreach (preg_split('~~u', $value, -1, PREG_SPLIT_NO_EMPTY) as $character) {
44 3
            if (isset($this->characterWidths[$character])) {
45 3
                $width += $this->characterWidths[$character];
46 3
            } elseif (strlen($character)) {
47
                $width += 0.06 * $font->getSize();
48
            }
49 3
        }
50
51 3
        return $font->isBold() ? $width * $this->characterWidths['bold'] : $width;
52
    }
53
54
    /**
55
     * Set proper font sizes by font.
56
     *
57
     * @param Font $font
58
     */
59 4
    public function setFont(Font $font)
60
    {
61 4
        $this->characterWidths = $this->widthCollection->get($font->getName(), $font->getSize());
62 4
    }
63
}
64