Completed
Push — master ( 5d1ea4...84ee67 )
by Stefan
03:26
created

WidthCollection   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 73
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 100%

Importance

Changes 8
Bugs 2 Features 3
Metric Value
wmc 8
c 8
b 2
f 3
lcom 1
cbo 0
dl 0
loc 73
ccs 26
cts 26
cp 1
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A loadWidthsFromCsv() 0 11 2
A get() 0 8 2
A calculate() 0 14 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