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
|
|
|
|