Completed
Push — master ( 75739d...a95317 )
by WEBEWEB
30:09
created

StylesheetTwigExtension::cssRgba()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 21
rs 9.584
c 0
b 0
f 0
cc 3
nc 3
nop 2
1
<?php
2
3
/*
4
 * This file is part of the core-bundle package.
5
 *
6
 * (c) 2019 WEBEWEB
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace WBW\Bundle\CoreBundle\Twig\Extension;
13
14
use Twig\TwigFilter;
15
use Twig\TwigFunction;
16
17
/**
18
 * Stylesheet Twig extension.
19
 *
20
 * @author webeweb <https://github.com/webeweb/>
21
 * @package WBW\Bundle\CoreBundle\Twig\Extension\CSS
22
 */
23
class StylesheetTwigExtension extends AbstractTwigExtension {
24
25
    /**
26
     * Service name.
27
     *
28
     * @var string
29
     */
30
    const SERVICE_NAME = "wbw.core.twig.extension.stylesheet";
31
32
    /**
33
     * Displays a rgba().
34
     *
35
     * @param string $color The hexadecimal color.
36
     * @param float $alpha The alpha channel.
37
     * @return string Returns the rgba().
38
     */
39
    public function cssRgba($color, $alpha = 1.00) {
40
41
        if (0 === preg_match_all("/^#?([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/", strtolower($color), $hex)) {
42
            return "";
43
        }
44
45
        $length = strlen($hex[1][0]);
46
47
        $pattern = "/[A-Fa-f0-9]{" . intval($length / 3) . "}/";
48
        preg_match_all($pattern, $hex[1][0], $channels);
49
50
        if (3 === $length) {
51
            $channels[0][0] = str_repeat($channels[0][0], 2);
52
            $channels[0][1] = str_repeat($channels[0][1], 2);
53
            $channels[0][2] = str_repeat($channels[0][2], 2);
54
        }
55
56
        $template = "rgba(%r%, %g%, %b%, %a%)";
57
58
        return str_replace(["%r%", "%g%", "%b%", "%a%"], [hexdec($channels[0][0]), hexdec($channels[0][1]), hexdec($channels[0][2]), number_format($alpha, 2)], $template);
59
    }
60
61
    /**
62
     * Get the Twig filters.
63
     *
64
     * @return TwigFilter[] Returns the Twig filters.
65
     */
66
    public function getFilters() {
67
        return [
68
            new TwigFilter("cssRgba", [$this, "cssRgba"], ["is_safe" => ["html"]]),
69
        ];
70
    }
71
72
    /**
73
     * Get the Twig functions.
74
     *
75
     * @return TwigFunction[] Returns the Twig functions.
76
     */
77
    public function getFunctions() {
78
        return [
79
            new TwigFunction("cssRgba", [$this, "cssRgba"], ["is_safe" => ["html"]]),
80
        ];
81
    }
82
}
83