Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
18 / 18
100.00% covered (success)
100.00%
2 / 2
CRAP
100.00% covered (success)
100.00%
1 / 1
Condition
100.00% covered (success)
100.00%
18 / 18
100.00% covered (success)
100.00%
2 / 2
14
100.00% covered (success)
100.00%
1 / 1
 active
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
1 / 1
10
 normalize
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
4
1<?php
2
3declare(strict_types=1);
4
5namespace Cosray\Field;
6
7/**
8 * Evaluates a When condition against stored node content. The editor
9 * behavior evaluates the identical condition against form state — the
10 * two implementations must stay in lockstep, which is why the value
11 * normalization mirrors form semantics (bools become '1'/'', scalars
12 * become strings).
13 */
14final class Condition
15{
16    /** @param array{field: string, op: string, value: mixed} $condition */
17    public static function active(array $condition, array $content): bool
18    {
19        $raw = $content[$condition['field']]['value'][Field::NEUTRAL_LOCALE] ?? null;
20        $value = self::normalize($raw);
21
22        return match ($condition['op']) {
23            'truthy' => $value !== '' && $value !== '0',
24            'eq' => $value === self::normalize($condition['value']),
25            'neq' => $value !== self::normalize($condition['value']),
26            'in' => in_array(
27                $value,
28                array_map(self::normalize(...), is_array($condition['value']) ? $condition['value'] : []),
29                true,
30            ),
31            'empty' => $value === '',
32            'notEmpty' => $value !== '',
33            default => true,
34        };
35    }
36
37    private static function normalize(mixed $value): string
38    {
39        if (is_bool($value)) {
40            return $value ? '1' : '';
41        }
42
43        return is_scalar($value) ? (string) $value : '';
44    }
45}