Completed
Pull Request — master (#14)
by Stefan
05:40 queued 03:06
created

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