Completed
Pull Request — master (#11)
by Stefan
03:32 queued 58s
created

WidthCalculator   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 68
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 100%

Importance

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

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
B getCellWidth() 0 14 5
A setFont() 0 4 1
A getSingleCharacterArray() 0 7 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
     * @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
46 5
        foreach ($this->getSingleCharacterArray($value) as $character) {
47 5
            if (isset($this->characterWidths[$character])) {
48 5
                $width += $this->characterWidths[$character];
49 5
            } elseif (strlen($character)) {
50 2
                $width += 0.06 * $font->getSize();
51 2
            }
52 5
        }
53
54 5
        return $font->isBold() ? $width * $this->characterWidths['bold'] : $width;
55
    }
56
57
    /**
58
     * Set proper font sizes by font.
59
     *
60
     * @param Font $font
61
     */
62 6
    public function setFont(Font $font)
63
    {
64 6
        $this->characterWidths = $this->widthCollection->get($font->getName(), $font->getSize());
65 6
    }
66
67
    /**
68
     * Split value into individual characters.
69
     *
70
     * @param mixed $value
71
     * @return array
72
     */
73 5
    private function getSingleCharacterArray($value)
74
    {
75 5
        if (mb_strlen($value) == strlen($value)) {
76 3
            return str_split($value);
77
        }
78 2
        return preg_split('~~u', $value, -1, PREG_SPLIT_NO_EMPTY);
79
    }
80
}
81