Completed
Push — master ( 0e81ca...7e02c1 )
by Stefan
02:45
created

WidthCalculator   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 100%

Importance

Changes 5
Bugs 1 Features 1
Metric Value
wmc 7
c 5
b 1
f 1
lcom 1
cbo 2
dl 0
loc 53
ccs 16
cts 16
cp 1
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
     * @param WidthCollection $widthCollection
29
     */
30 16
    public function __construct(WidthCollection $widthCollection)
31
    {
32 16
        $this->widthCollection = $widthCollection;
33 16
    }
34
35
    /**
36
     * Returns the estimated width of a cell value.
37
     *
38
     * @param mixed $value
39
     * @param Font  $font
40
     * @return float
41
     */
42 5
    public function getCellWidth($value, Font $font)
43
    {
44 5
        $width = 0.07 * $font->getSize();
45 5
        foreach (preg_split('~~u', $value, -1, PREG_SPLIT_NO_EMPTY) as $character) {
46 5
            if (isset($this->characterWidths[$character])) {
47 5
                $width += $this->characterWidths[$character];
48 5
            } elseif (strlen($character)) {
49 2
                $width += 0.06 * $font->getSize();
50 2
            }
51 5
        }
52
53 5
        return $font->isBold() ? $width * $this->characterWidths['bold'] : $width;
54
    }
55
56
    /**
57
     * Set proper font sizes by font.
58
     *
59
     * @param Font $font
60
     */
61 6
    public function setFont(Font $font)
62
    {
63 6
        $this->characterWidths = $this->widthCollection->get($font->getName(), $font->getSize());
64 6
    }
65
}
66