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

WidthCalculator::getCellWidth()   B

Complexity

Conditions 5
Paths 8

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 5.2

Importance

Changes 4
Bugs 1 Features 1
Metric Value
c 4
b 1
f 1
dl 0
loc 13
ccs 8
cts 10
cp 0.8
rs 8.8571
cc 5
eloc 8
nc 8
nop 2
crap 5.2
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