Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
24 / 24 |
|
100.00% |
4 / 4 |
CRAP | |
100.00% |
1 / 1 |
| Checkbox | |
100.00% |
24 / 24 |
|
100.00% |
4 / 4 |
14 | |
100.00% |
1 / 1 |
| control | |
100.00% |
6 / 6 |
|
100.00% |
1 / 1 |
3 | |||
| value | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| structure | |
100.00% |
10 / 10 |
|
100.00% |
1 / 1 |
8 | |||
| shape | |
100.00% |
7 / 7 |
|
100.00% |
1 / 1 |
2 | |||
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace Cosray\Field; |
| 6 | |
| 7 | use Celema\Sire\Shape; |
| 8 | use Cosray\Schema\StateLabels; |
| 9 | use Cosray\Validation\Shapes; |
| 10 | use Cosray\Value\Boolean; |
| 11 | use Override; |
| 12 | |
| 13 | class Checkbox extends Field |
| 14 | { |
| 15 | public bool $nullable = false; |
| 16 | public ?StateLabels $stateLabels = null; |
| 17 | |
| 18 | #[Override] |
| 19 | public function control(): Control |
| 20 | { |
| 21 | $labels = []; |
| 22 | |
| 23 | foreach (['true', 'false', 'null'] as $state) { |
| 24 | $label = $this->stateLabels?->{$state}; |
| 25 | |
| 26 | if ($label !== null) { |
| 27 | $labels[$state] = __($label); |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | return Control::checkbox(nullable: $this->nullable)->prop('labels', $labels); |
| 32 | } |
| 33 | |
| 34 | #[Override] |
| 35 | public function value(): Boolean |
| 36 | { |
| 37 | return new Boolean($this->owner, $this, $this->valueContext); |
| 38 | } |
| 39 | |
| 40 | #[Override] |
| 41 | public function structure(mixed $value = null): array |
| 42 | { |
| 43 | // A nullable field must be able to clear a configured default. |
| 44 | if ($value === null && (!$this->nullable || func_num_args() === 0)) { |
| 45 | $value = $this->default; |
| 46 | } |
| 47 | |
| 48 | if ($value === null && !$this->nullable) { |
| 49 | $value = false; |
| 50 | } |
| 51 | |
| 52 | return [ |
| 53 | 'type' => $this::class, |
| 54 | 'value' => is_array($value) && array_key_exists(self::NEUTRAL_LOCALE, $value) |
| 55 | ? $value |
| 56 | : [self::NEUTRAL_LOCALE => $value], |
| 57 | ]; |
| 58 | } |
| 59 | |
| 60 | #[Override] |
| 61 | public function shape(): Shape |
| 62 | { |
| 63 | $shape = Shapes::create(); |
| 64 | $this->addType($shape); |
| 65 | |
| 66 | $value = $shape->add('value', $this->zxxShape('bool', $this->validators)); |
| 67 | |
| 68 | if (!$this->isRequired()) { |
| 69 | $value->optional()->nullable(); |
| 70 | } |
| 71 | |
| 72 | $this->addMeta($shape); |
| 73 | |
| 74 | return $shape; |
| 75 | } |
| 76 | } |