Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
2 / 2
CRAP
100.00% covered (success)
100.00%
1 / 1
When
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
2 / 2
5
100.00% covered (success)
100.00%
1 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 condition
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
4
1<?php
2
3declare(strict_types=1);
4
5namespace Cosray\Schema;
6
7use Attribute;
8
9/**
10 * Conditional field visibility: the field is only active while the
11 * referenced sibling field's value satisfies the condition.
12 *
13 *     #[When('multi_day')]                    truthy
14 *     #[When('layout', 'hero')]               equality
15 *     #[When('template', in: ['a', 'b'])]     membership
16 *     #[When('teaser', op: 'empty')]          explicit operator
17 *
18 * The value of an inactive field is kept in the database — the editor
19 * merely hides it and the frontend presents it as empty (read-time
20 * enforcement); `Field::raw()` bypasses deliberately. Condition sources
21 * are limited to primitive, non-translated fields.
22 */
23#[Attribute(Attribute::TARGET_PROPERTY)]
24final class When
25{
26    public function __construct(
27        public readonly string $field,
28        public readonly string|int|float|bool|null $value = null,
29        public readonly ?array $in = null,
30        public readonly string $op = '',
31    ) {}
32
33    /** @return array{field: string, op: string, value: mixed} */
34    public function condition(): array
35    {
36        if ($this->in !== null) {
37            return ['field' => $this->field, 'op' => 'in', 'value' => array_values($this->in)];
38        }
39
40        if ($this->op !== '') {
41            return ['field' => $this->field, 'op' => $this->op, 'value' => $this->value];
42        }
43
44        if ($this->value !== null) {
45            return ['field' => $this->field, 'op' => 'eq', 'value' => $this->value];
46        }
47
48        return ['field' => $this->field, 'op' => 'truthy', 'value' => null];
49    }
50}