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    /**
17     * @param array{field: string, op: string, value: mixed} $condition
18     * @param array<string, mixed> $content
19     */
20    public static function active(array $condition, array $content): bool
21    {
22        $raw = $content[$condition['field']]['value'][Field::NEUTRAL_LOCALE] ?? null;
23        $value = self::normalize($raw);
24
25        return match ($condition['op']) {
26            'truthy' => $value !== '' && $value !== '0',
27            'eq' => $value === self::normalize($condition['value']),
28            'neq' => $value !== self::normalize($condition['value']),
29            'in' => in_array(
30                $value,
31                array_map(self::normalize(...), is_array($condition['value']) ? $condition['value'] : []),
32                true,
33            ),
34            'empty' => $value === '',
35            'notEmpty' => $value !== '',
36            default => true,
37        };
38    }
39
40    private static function normalize(mixed $value): string
41    {
42        if (is_bool($value)) {
43            return $value ? '1' : '';
44        }
45
46        return is_scalar($value) ? (string) $value : '';
47    }
48}