-
-
Notifications
You must be signed in to change notification settings - Fork 9.4k
/
CompositeTypeTrait.php
98 lines (84 loc) · 2.28 KB
/
CompositeTypeTrait.php
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
<?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\TypeInfo\Type;
use Symfony\Component\TypeInfo\Exception\InvalidArgumentException;
use Symfony\Component\TypeInfo\Exception\LogicException;
use Symfony\Component\TypeInfo\Type;
use Symfony\Component\TypeInfo\TypeIdentifier;
/**
* @author Mathias Arlaud <mathias.arlaud@gmail.com>
* @author Baptiste Leduc <baptiste.leduc@gmail.com>
*
* @internal
*
* @template T of Type
*/
trait CompositeTypeTrait
{
/**
* @var list<T>
*/
private readonly array $types;
/**
* @param list<T> $types
*/
public function __construct(Type ...$types)
{
if (\count($types) < 2) {
throw new InvalidArgumentException(sprintf('"%s" expects at least 2 types.', self::class));
}
foreach ($types as $t) {
if ($t instanceof self) {
throw new InvalidArgumentException(sprintf('Cannot set "%s" as a "%1$s" part.', self::class));
}
}
usort($types, fn (Type $a, Type $b): int => (string) $a <=> (string) $b);
$this->types = array_values(array_unique($types));
}
public function getBaseType(): BuiltinType|ObjectType
{
throw new LogicException(sprintf('Cannot get base type on "%s" compound type.', $this));
}
public function isA(TypeIdentifier|string $subject): bool
{
return $this->is(fn (Type $type) => $type->isA($subject));
}
/**
* @return list<T>
*/
public function getTypes(): array
{
return $this->types;
}
/**
* @param callable(T): bool $callable
*/
public function atLeastOneTypeIs(callable $callable): bool
{
foreach ($this->types as $t) {
if ($callable($t)) {
return true;
}
}
return false;
}
/**
* @param callable(T): bool $callable
*/
public function everyTypeIs(callable $callable): bool
{
foreach ($this->types as $t) {
if (!$callable($t)) {
return false;
}
}
return true;
}
}