Debian Codegraph @

vendor/symfony/type-info/Type.php

raw
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;
13
14 use Symfony\Component\TypeInfo\Type\CompositeTypeInterface;
15 use Symfony\Component\TypeInfo\Type\WrappingTypeInterface;
16
17 /**
18 * @author Mathias Arlaud <[email protected]>
19 * @author Baptiste Leduc <[email protected]>
20 */
21 abstract class Type implements \Stringable
22 {
23 use TypeFactoryTrait;
24
25 /**
26 * Tells if the type is satisfied by the $specification callable.
27 *
28 * @param callable(self): bool $specification
29 */
30 public function isSatisfiedBy(callable $specification): bool
31 {
32 if ($this instanceof WrappingTypeInterface && $this->wrappedTypeIsSatisfiedBy($specification)) {
33 return true;
34 }
35
36 if ($this instanceof CompositeTypeInterface && $this->composedTypesAreSatisfiedBy($specification)) {
37 return true;
38 }
39
40 return $specification($this);
41 }
42
43 /**
44 * Tells if the type (or one of its wrapped/composed parts) is identified by one of the $identifiers.
45 */
46 public function isIdentifiedBy(TypeIdentifier|string ...$identifiers): bool
47 {
48 $specification = static fn (Type $type): bool => $type->isIdentifiedBy(...$identifiers);
49
50 if ($this instanceof WrappingTypeInterface && $this->wrappedTypeIsSatisfiedBy($specification)) {
51 return true;
52 }
53
54 if ($this instanceof CompositeTypeInterface && $this->composedTypesAreSatisfiedBy($specification)) {
55 return true;
56 }
57
58 return false;
59 }
60
61 public function isNullable(): bool
62 {
63 return false;
64 }
65
66 /**
67 * Tells if the type (or one of its wrapped/composed parts) accepts the given $value.
68 */
69 public function accepts(mixed $value): bool
70 {
71 $specification = static function (Type $type) use (&$specification, $value): bool {
72 if ($type instanceof WrappingTypeInterface) {
73 return $type->wrappedTypeIsSatisfiedBy($specification);
74 }
75
76 if ($type instanceof CompositeTypeInterface) {
77 return $type->composedTypesAreSatisfiedBy($specification);
78 }
79
80 return $type->accepts($value);
81 };
82
83 return $this->isSatisfiedBy($specification);
84 }
85
86 /**
87 * Traverses the whole type tree.
88 *
89 * @return iterable<self>
90 */
91 public function traverse(bool $traverseComposite = true, bool $traverseWrapped = true): iterable
92 {
93 yield $this;
94
95 if ($this instanceof CompositeTypeInterface && $traverseComposite) {
96 foreach ($this->getTypes() as $type) {
97 yield $type;
98 }
99
100 // prevent yielding twice when having a type that is both composite and wrapped
101 return;
102 }
103
104 if ($this instanceof WrappingTypeInterface && $traverseWrapped) {
105 yield $this->getWrappedType();
106 }
107 }
108 }