summaryrefslogtreecommitdiffstats
path: root/vendor/gipfl/icingaweb2/src/IconHelper.php
blob: 1c8af9d647f171aac35f653949846b82863ae072 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
<?php

namespace gipfl\IcingaWeb2;

use InvalidArgumentException;

/**
 * Icon helper class
 *
 * Should help to reduce redundant icon-lookup code. Currently with hardcoded
 * icons only, could easily provide support for all of them as follows:
 *
 * $confFile = Icinga::app()
 *     ->getApplicationDir('fonts/fontello-ifont/config.json');
 *
 * $font = json_decode(file_get_contents($confFile));
 * // 'icon-' is to be found in $font->css_prefix_text
 * foreach ($font->glyphs as $icon) {
 * // $icon->css (= 'help') -> 0x . dechex($icon->code)
 * }
 */
class IconHelper
{
    private $icons = [
        'minus'              => 'e806',
        'trash'              => 'e846',
        'plus'               => 'e805',
        'cancel'             => 'e804',
        'help'               => 'e85b',
        'angle-double-right' => 'e87b',
        'up-big'             => 'e825',
        'down-big'           => 'e828',
        'down-open'          => 'e821',
    ];

    private $mappedUtf8Icons;

    private $reversedUtf8Icons;

    private static $instance;

    public function __construct()
    {
        $this->prepareIconMappings();
    }

    public static function instance()
    {
        if (self::$instance === null) {
            self::$instance = new static;
        }

        return self::$instance;
    }

    public function characterIconName($character)
    {
        if (array_key_exists($character, $this->reversedUtf8Icons)) {
            return $this->reversedUtf8Icons[$character];
        } else {
            throw new InvalidArgumentException('There is no mapping for the given character');
        }
    }

    protected function hexToCharacter($hex)
    {
        return json_decode('"\u' . $hex . '"');
    }

    public function iconCharacter($name)
    {
        if (array_key_exists($name, $this->mappedUtf8Icons)) {
            return $this->mappedUtf8Icons[$name];
        } else {
            return $this->mappedUtf8Icons['help'];
        }
    }

    protected function prepareIconMappings()
    {
        $this->mappedUtf8Icons = [];
        $this->reversedUtf8Icons = [];
        foreach ($this->icons as $name => $hex) {
            $character = $this->hexToCharacter($hex);
            $this->mappedUtf8Icons[$name] = $character;
            $this->reversedUtf8Icons[$character] = $name;
        }
    }
}