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_SimpleFilter; |
15
|
|
|
use Twig_SimpleFunction; |
16
|
|
|
use WBW\Library\Core\Argument\StringHelper; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* Stylesheet Twig extension. |
20
|
|
|
* |
21
|
|
|
* @author webeweb <https://github.com/webeweb/> |
22
|
|
|
* @package WBW\Bundle\CoreBundle\Twig\Extension\CSS |
23
|
|
|
*/ |
24
|
|
|
class StylesheetTwigExtension extends AbstractTwigExtension { |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* Service name. |
28
|
|
|
* |
29
|
|
|
* @var string |
30
|
|
|
*/ |
31
|
|
|
const SERVICE_NAME = "webeweb.core.twig.extension.stylesheet"; |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* Displays a rgba(). |
35
|
|
|
* |
36
|
|
|
* @param string $color The hexadecimal color. |
37
|
|
|
* @param float $alpha The alpha channel. |
38
|
|
|
* @return string Returns the rgba(). |
39
|
|
|
*/ |
40
|
|
|
public function cssRGBA($color, $alpha) { |
41
|
|
|
|
42
|
|
|
if (0 === preg_match_all("/^#?([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/", strtolower($color), $hex)) { |
43
|
|
|
return ""; |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
$length = strlen($hex[1][0]); |
47
|
|
|
|
48
|
|
|
$pattern = "/[A-Fa-f0-9]{" . intval($length / 3) . "}/"; |
49
|
|
|
preg_match_all($pattern, $hex[1][0], $channels); |
50
|
|
|
|
51
|
|
|
if (3 === $length) { |
52
|
|
|
$channels[0][0] = str_repeat($channels[0][0], 2); |
53
|
|
|
$channels[0][1] = str_repeat($channels[0][1], 2); |
54
|
|
|
$channels[0][2] = str_repeat($channels[0][2], 2); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
$template = "rgba(%r%, %g%, %b%, %a%)"; |
58
|
|
|
|
59
|
|
|
return StringHelper::replace($template, ["%r%", "%g%", "%b%", "%a%"], [hexdec($channels[0][0]), hexdec($channels[0][1]), hexdec($channels[0][2]), number_format($alpha, 2)]); |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
/** |
63
|
|
|
* Get the Twig filters. |
64
|
|
|
* |
65
|
|
|
* @return Twig_SimpleFilter[] Returns the Twig filters. |
66
|
|
|
*/ |
67
|
|
|
public function getFilters() { |
68
|
|
|
return [ |
69
|
|
|
new Twig_SimpleFilter("cssRGBA", [$this, "cssRGBA"], ["is_safe" => ["html"]]), |
70
|
|
|
]; |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
/** |
74
|
|
|
* Get the Twig functions. |
75
|
|
|
* |
76
|
|
|
* @return array Returns the Twig functions. |
77
|
|
|
*/ |
78
|
|
|
public function getFunctions() { |
79
|
|
|
return [ |
80
|
|
|
new Twig_SimpleFunction("cssRGBA", [$this, "cssRGBA"], ["is_safe" => ["html"]]), |
81
|
|
|
]; |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
|