ee470cacdb9036bb16dab528d6a082801754831c
[GitHub/WoltLab/WCF.git] /
1 <?php
2
3 declare(strict_types=1);
4
5 namespace CuyZ\Valinor\Mapper\Tree\Exception;
6
7 use CuyZ\Valinor\Mapper\Tree\Message\ErrorMessage;
8 use CuyZ\Valinor\Mapper\Tree\Message\HasParameters;
9 use CuyZ\Valinor\Type\Types\UnionType;
10 use CuyZ\Valinor\Utility\String\StringFormatter;
11 use CuyZ\Valinor\Utility\TypeHelper;
12 use RuntimeException;
13
14 use function array_map;
15 use function implode;
16
17 /** @internal */
18 final class CannotResolveTypeFromUnion extends RuntimeException implements ErrorMessage, HasParameters
19 {
20 private string $body;
21
22 /** @var array<string, string> */
23 private array $parameters;
24
25 public function __construct(mixed $source, UnionType $unionType)
26 {
27 $this->parameters = [
28 'allowed_types' => implode(
29 ', ',
30 // PHP8.1 First-class callable syntax
31 array_map([TypeHelper::class, 'dump'], $unionType->types())
32 ),
33 ];
34
35 if ($source === null) {
36 $this->body = TypeHelper::containsObject($unionType)
37 ? 'Cannot be empty.'
38 : 'Cannot be empty and must be filled with a value matching any of {allowed_types}.';
39 } else {
40 $this->body = TypeHelper::containsObject($unionType)
41 ? 'Invalid value {source_value}.'
42 : 'Value {source_value} does not match any of {allowed_types}.';
43 }
44
45 parent::__construct(StringFormatter::for($this), 1607027306);
46 }
47
48 public function body(): string
49 {
50 return $this->body;
51 }
52
53 public function parameters(): array
54 {
55 return $this->parameters;
56 }
57 }