Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
93.75% covered (success)
93.75%
15 / 16
80.00% covered (warning)
80.00%
4 / 5
CRAP
0.00% covered (danger)
0.00%
0 / 1
Color
93.75% covered (success)
93.75%
15 / 16
80.00% covered (warning)
80.00%
4 / 5
8.02
0.00% covered (danger)
0.00%
0 / 1
 control
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 value
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 structure
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 shape
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
2
 normalize
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
3.14
1<?php
2
3declare(strict_types=1);
4
5namespace Cosray\Field;
6
7use Celema\Sire\Shape;
8use Cosray\Validation\Shapes;
9use Cosray\Value\Color as ColorValue;
10use Override;
11
12class Color extends Field
13{
14    #[Override]
15    public function control(): Control
16    {
17        return Control::color();
18    }
19
20    #[Override]
21    public function value(): ColorValue
22    {
23        return new ColorValue($this->owner, $this, $this->valueContext);
24    }
25
26    #[Override]
27    public function structure(mixed $value = null): array
28    {
29        return $this->getSimpleStructure('color', $value);
30    }
31
32    #[Override]
33    public function shape(): Shape
34    {
35        $shape = Shapes::create();
36        $this->addType($shape);
37
38        $value = $shape
39            ->add('value', $this->zxxShape('string', ['color', ...$this->validators]))
40            ->finalize(self::normalize(...));
41
42        if (!$this->isRequired()) {
43            $value->optional()->nullable();
44        }
45
46        $this->addMeta($shape);
47
48        return $shape;
49    }
50
51    /** Stores the canonical form of whatever hex notation the rule accepted. */
52    private static function normalize(mixed $value): mixed
53    {
54        if (!is_array($value)) {
55            return $value;
56        }
57
58        $color = ColorValue::normalize($value[self::NEUTRAL_LOCALE] ?? null);
59
60        return $color === null ? $value : [...$value, self::NEUTRAL_LOCALE => $color];
61    }
62}