Completed
Push — master ( 84ee67...48a23c )
by Stefan
02:40
created

SizeCollection::calculate()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 14
ccs 9
cts 9
cp 1
rs 9.4285
cc 3
eloc 8
nc 4
nop 2
crap 3
1
<?php
2
3
namespace OneSheet\Size;
4
5
/**
6
 * Class WidthCollection
7
 *
8
 * @package OneSheet
9
 */
10
class SizeCollection
11
{
12
    /**
13
     * Constant for default character size.
14
     */
15
    const BASE_SIZE = 12;
16
17
    /**
18
     * Array containing character widths for each font & size.
19
     *
20
     * @var array
21
     */
22
    private static $widths = array();
23
24
    /**
25
     * Create character width map for each font.
26
     */
27 18
    public function __construct()
28
    {
29 18
        self::loadWidthsFromCsv(dirname(__FILE__) . '/size_collection.csv');
30 18
    }
31
32
    /**
33
     * Dirty way to allow developers to load character widths that
34
     * are not yet included.
35
     *
36
     * @param string $csvPath
37
     */
38 18
    public static function loadWidthsFromCsv($csvPath)
39
    {
40 18
        $fh = fopen($csvPath, 'r');
41 18
        $head = fgetcsv($fh);
42 18
        unset($head[0], $head[1]);
43 18
        while ($row = fgetcsv($fh)) {
44 18
            $fontName = array_shift($row);
45 18
            $fontSize = array_shift($row);
46 18
            self::$widths[$fontName][$fontSize] = array_combine($head, $row);
47 18
        }
48 18
    }
49
50
    /**
51
     * Return character widths for given font name.
52
     *
53
     * @param string $fontName
54
     * @param int    $fontSize
55
     * @return array
56
     */
57 8
    public function get($fontName, $fontSize)
58
    {
59 8
        if (isset(self::$widths[$fontName][$fontSize])) {
60 6
            return self::$widths[$fontName][$fontSize];
61
        }
62
63 6
        return self::calculate($fontName, $fontSize);
64
    }
65
66
    /**
67
     * Calculate character widths based on font name and size.
68
     *
69
     * @param string $fontName
70
     * @param int    $fontSize
71
     * @return array
72
     */
73 6
    private static function calculate($fontName, $fontSize)
74
    {
75 6
        if (isset(self::$widths[$fontName])) {
76 4
            $baseWidths = self::$widths[$fontName][self::BASE_SIZE];
77 4
        } else {
78 2
            $baseWidths = self::$widths['Calibri'][self::BASE_SIZE];
79
        }
80
81 6
        foreach ($baseWidths as $character => $width) {
82 6
            self::$widths[$fontName][$fontSize][$character] = $width / self::BASE_SIZE * $fontSize;
83 6
        }
84
85 6
        return self::$widths[$fontName][$fontSize];
86
    }
87
}
88