| 1 |
<?php |
| 2 |
|
| 3 |
/* |
| 4 |
* This file is part of the Symfony package. |
| 5 |
* |
| 6 |
* (c) Fabien Potencier <[email protected]> |
| 7 |
* |
| 8 |
* For the full copyright and license information, please view the LICENSE |
| 9 |
* file that was distributed with this source code. |
| 10 |
*/ |
| 11 |
|
| 12 |
namespace Symfony\Component\TypeInfo\Type; |
| 13 |
|
| 14 |
use Symfony\Component\TypeInfo\Exception\InvalidArgumentException; |
| 15 |
use Symfony\Component\TypeInfo\Type; |
| 16 |
|
| 17 |
/** |
| 18 |
* @author Mathias Arlaud <[email protected]> |
| 19 |
* @author Baptiste Leduc <[email protected]> |
| 20 |
* |
| 21 |
* @template T of ObjectType|GenericType<ObjectType>|CollectionType<GenericType<ObjectType>> |
| 22 |
* |
| 23 |
* @implements CompositeTypeInterface<T> |
| 24 |
*/ |
| 25 |
final class IntersectionType extends Type implements CompositeTypeInterface |
| 26 |
{ |
| 27 |
/** |
| 28 |
* @var list<T> |
| 29 |
*/ |
| 30 |
private readonly array $types; |
| 31 |
|
| 32 |
/** |
| 33 |
* @param list<T> $types |
| 34 |
*/ |
| 35 |
public function __construct(Type ...$types) |
| 36 |
{ |
| 37 |
if (\count($types) < 2) { |
| 38 |
throw new InvalidArgumentException(\sprintf('"%s" expects at least 2 types.', self::class)); |
| 39 |
} |
| 40 |
|
| 41 |
foreach ($types as $type) { |
| 42 |
if ($type instanceof CompositeTypeInterface || $type instanceof NullableType) { |
| 43 |
throw new InvalidArgumentException(\sprintf('Cannot set "%s" as a "%s" part.', $type, self::class)); |
| 44 |
} |
| 45 |
|
| 46 |
while ($type instanceof WrappingTypeInterface) { |
| 47 |
$type = $type->getWrappedType(); |
| 48 |
} |
| 49 |
|
| 50 |
if (!$type instanceof ObjectType) { |
| 51 |
throw new InvalidArgumentException(\sprintf('Cannot set "%s" as a "%s" part.', $type, self::class)); |
| 52 |
} |
| 53 |
} |
| 54 |
|
| 55 |
usort($types, static fn (Type $a, Type $b): int => (string) $a <=> (string) $b); |
| 56 |
$this->types = array_values(array_unique($types)); |
| 57 |
} |
| 58 |
|
| 59 |
/** |
| 60 |
* @return list<T> |
| 61 |
*/ |
| 62 |
public function getTypes(): array |
| 63 |
{ |
| 64 |
return $this->types; |
| 65 |
} |
| 66 |
|
| 67 |
public function composedTypesAreSatisfiedBy(callable $specification): bool |
| 68 |
{ |
| 69 |
foreach ($this->types as $type) { |
| 70 |
if (!$type->isSatisfiedBy($specification)) { |
| 71 |
return false; |
| 72 |
} |
| 73 |
} |
| 74 |
|
| 75 |
return true; |
| 76 |
} |
| 77 |
|
| 78 |
public function __toString(): string |
| 79 |
{ |
| 80 |
$string = ''; |
| 81 |
$glue = ''; |
| 82 |
|
| 83 |
foreach ($this->types as $t) { |
| 84 |
$string .= $glue.($t instanceof CompositeTypeInterface ? '('.$t.')' : $t); |
| 85 |
$glue = '&'; |
| 86 |
} |
| 87 |
|
| 88 |
return $string; |
| 89 |
} |
| 90 |
} |