/
ColorStyle.php
80 lines (73 loc) · 2.67 KB
/
ColorStyle.php
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
<?php
namespace Concrete\Core\StyleCustomizer\Style;
use Concrete\Core\StyleCustomizer\Normalizer\ColorVariable;
use Concrete\Core\StyleCustomizer\Normalizer\NormalizedVariableCollection;
use Concrete\Core\StyleCustomizer\Normalizer\Variable;
use Concrete\Core\StyleCustomizer\Normalizer\VariableInterface;
use Concrete\Core\StyleCustomizer\Style\Value\ColorValue;
use Concrete\Core\StyleCustomizer\Style\Value\ValueInterface;
use Primal\Color\Parser;
use Primal\Color\RGBColor;
class ColorStyle extends Style
{
public function createValueFromVariableCollection(NormalizedVariableCollection $collection): ?ValueInterface
{
$variable = $collection->getVariable($this->getVariableToInspect());
if ($variable) {
try {
$color = new Parser($variable->getValue());
} catch (\Exception $e) {
$color = new Parser(
(new ColorVariable(255, 255, 255, 255, 0))
->getValue()
);
}
if ($color) {
$result = $color->getResult();
$alpha = 1;
if (is_numeric($result->alpha) && $result->alpha >= 0 && $result->alpha < 1) {
$alpha = $result->alpha;
}
$colorValue = new ColorValue();
$colorValue
->setRed($result->red)
->setGreen($result->green)
->setBlue($result->blue)
->setAlpha($alpha)
;
return $colorValue;
}
}
return null;
}
public function createValueFromRequestDataCollection(array $styles): ?ValueInterface
{
foreach ($styles as $style) {
if (isset($style['variable']) && $style['variable'] == $this->getVariable()) {
$value = new ColorValue();
$value->setRed($style['value']['r'] ?? null);
$value->setGreen($style['value']['g'] ?? null);
$value->setBlue($style['value']['b'] ?? null);
$value->setAlpha($style['value']['a'] ?? null);
return $value;
}
}
return null;
}
/**
* @param ColorValue $value
* @return VariableInterface|null
*/
public function createVariableFromValue(ValueInterface $value): ?VariableInterface
{
$variableValue = sprintf(
'rgba(%s, %s, %s, %s)',
$value->getRed(),
$value->getGreen(),
$value->getBlue(),
$value->getAlpha()
);
$variable = new Variable($this->getVariableToInspect(), $variableValue);
return $variable;
}
}