Spaces:
Runtime error

File size: 5,717 Bytes
7a66774
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Config\Definition;

use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;

/**
 * Node which only allows a finite set of values.
 *
 * @author Johannes M. Schmitt <schmittjoh@gmail.com>
 */
class EnumNode extends ScalarNode
{
    private array $values;
    private ?string $enumFqcn = null;

    /**
     * @param class-string<\UnitEnum>|null $enumFqcn
     */
    public function __construct(?string $name, ?NodeInterface $parent = null, array $values = [], string $pathSeparator = BaseNode::DEFAULT_PATH_SEPARATOR, ?string $enumFqcn = null)
    {
        if (!$values && !$enumFqcn) {
            throw new \InvalidArgumentException('$values must contain at least one element.');
        }

        if ($values && $enumFqcn) {
            throw new \InvalidArgumentException('$values or $enumFqcn cannot be both set.');
        }

        if (null !== $enumFqcn) {
            if (!enum_exists($enumFqcn)) {
                throw new \InvalidArgumentException(\sprintf('The "%s" enum does not exist.', $enumFqcn));
            }

            $values = $enumFqcn::cases();
            $this->enumFqcn = $enumFqcn;
        }

        foreach ($values as $value) {
            if (null === $value || \is_scalar($value)) {
                continue;
            }

            if (!$value instanceof \UnitEnum) {
                throw new \InvalidArgumentException(\sprintf('"%s" only supports scalar, enum, or null values, "%s" given.', __CLASS__, get_debug_type($value)));
            }

            if ($value::class !== ($enumClass ??= $value::class)) {
                throw new \InvalidArgumentException(\sprintf('"%s" only supports one type of enum, "%s" and "%s" passed.', __CLASS__, $enumClass, $value::class));
            }
        }

        parent::__construct($name, $parent, $pathSeparator);
        $this->values = $values;
    }

    public function getValues(): array
    {
        return $this->values;
    }

    public function getEnumFqcn(): ?string
    {
        return $this->enumFqcn;
    }

    /**
     * @internal
     */
    public function getPermissibleValues(string $separator, bool $trim = true): string
    {
        if (is_subclass_of($this->enumFqcn, \BackedEnum::class)) {
            if (!$trim) {
                return 'value-of<\\'.$this->enumFqcn.'>'.$separator.'\\'.$this->enumFqcn;
            }

            $values = array_column($this->enumFqcn::cases(), 'value');

            return implode($separator, array_map(static fn ($value) => json_encode($value, \JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE), $values));
        }

        return implode($separator, array_unique(array_map(static function ($value) use ($trim) {
            if (!$value instanceof \UnitEnum) {
                return json_encode($value, \JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE | \JSON_PRESERVE_ZERO_FRACTION);
            }

            return $trim ? ltrim(var_export($value, true), '\\') : var_export($value, true);
        }, $this->values)));
    }

    protected function validateType(mixed $value): void
    {
        if ($value instanceof \UnitEnum) {
            return;
        }

        parent::validateType($value);
    }

    protected function finalizeValue(mixed $value): mixed
    {
        $value = parent::finalizeValue($value);

        if (null === $value && $this->enumFqcn) {
            return null;
        }

        if (!$this->enumFqcn) {
            if (!\in_array($value, $this->values, true)) {
                throw $this->createInvalidValueException($value);
            }

            return $value;
        }

        if ($value instanceof $this->enumFqcn) {
            return $value;
        }

        if (!is_subclass_of($this->enumFqcn, \BackedEnum::class)) {
            // value is not an instance of the enum, and the enum is not
            // backed, meaning no cast is possible
            throw $this->createInvalidValueException($value);
        }

        if ($value instanceof \UnitEnum && !$value instanceof $this->enumFqcn) {
            throw new InvalidConfigurationException(\sprintf('The value should be part of the "%s" enum, got a value from the "%s" enum.', $this->enumFqcn, get_debug_type($value)));
        }

        if (!\is_string($value) && !\is_int($value)) {
            throw new InvalidConfigurationException(\sprintf('Only strings and integers can be cast to a case of the "%s" enum, got value of type "%s".', $this->enumFqcn, get_debug_type($value)));
        }

        try {
            return $this->enumFqcn::from($value);
        } catch (\TypeError|\ValueError) {
            throw $this->createInvalidValueException($value);
        }
    }

    private function createInvalidValueException(mixed $value): InvalidConfigurationException
    {
        $displayValue = match (true) {
            \is_int($value) => $value,
            \is_string($value) => \sprintf('"%s"', $value),
            default => \sprintf('of type "%s"', get_debug_type($value)),
        };

        $message = \sprintf('The value %s is not allowed for path "%s". Permissible values: %s.', $displayValue, $this->getPath(), $this->getPermissibleValues(', '));
        if ($this->enumFqcn) {
            $message = substr_replace($message, \sprintf(' (cases of the "%s" enum)', $this->enumFqcn), -1, 0);
        }

        $e = new InvalidConfigurationException($message);
        $e->setPath($this->getPath());

        return $e;
    }
}