| 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 |
use Symfony\Component\TypeInfo\TypeIdentifier; |
| 17 |
|
| 18 |
/** |
| 19 |
* @author Mathias Arlaud <[email protected]> |
| 20 |
* |
| 21 |
* @template T of Type |
| 22 |
* |
| 23 |
* @extends UnionType<T|BuiltinType<TypeIdentifier::NULL>> |
| 24 |
* |
| 25 |
* @implements WrappingTypeInterface<T> |
| 26 |
*/ |
| 27 |
final class NullableType extends UnionType implements WrappingTypeInterface |
| 28 |
{ |
| 29 |
/** |
| 30 |
* @param T $type |
| 31 |
*/ |
| 32 |
public function __construct( |
| 33 |
private readonly Type $type, |
| 34 |
) { |
| 35 |
if ($type->isNullable()) { |
| 36 |
throw new InvalidArgumentException(\sprintf('Cannot create a "%s" with "%s" because it is already nullable.', self::class, $type)); |
| 37 |
} |
| 38 |
|
| 39 |
if ($type instanceof UnionType) { |
| 40 |
parent::__construct(Type::null(), ...$type->getTypes()); |
| 41 |
|
| 42 |
return; |
| 43 |
} |
| 44 |
|
| 45 |
parent::__construct(Type::null(), $type); |
| 46 |
} |
| 47 |
|
| 48 |
public function getWrappedType(): Type |
| 49 |
{ |
| 50 |
return $this->type; |
| 51 |
} |
| 52 |
|
| 53 |
public function wrappedTypeIsSatisfiedBy(callable $specification): bool |
| 54 |
{ |
| 55 |
return $this->getWrappedType()->isSatisfiedBy($specification); |
| 56 |
} |
| 57 |
|
| 58 |
public function isNullable(): bool |
| 59 |
{ |
| 60 |
return true; |
| 61 |
} |
| 62 |
|
| 63 |
public function accepts(mixed $value): bool |
| 64 |
{ |
| 65 |
return null === $value || parent::accepts($value); |
| 66 |
} |
| 67 |
} |