Re: [DISCUSSION] ReflectionType::accepts
| From: | Pierre R. | Date: | Fri, 29 Jan 2021 08:18:17 +0000 |
| Subject: | Re: [DISCUSSION] ReflectionType::accepts | ||
| References: | 1 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-113017@lists.php.net to get a copy of this message | ||
Le 29/01/2021 à 09:14, Brent Roose a écrit :
Hi Internals Since the addition of union types, it has become a little more cumbersome to determine whether a given parameter type accepts specific input. Personally I've been reusing this code blob in several places because of it:Hello, I think this would be a good addition. I personally had to write the exact same algorithm to solve this exact same problem yesterday night. Cheers, -- Pierre/** @var \ReflectionNamedType[] $types */ $types = match ($type::class) { ReflectionUnionType::class => $type->getTypes(), ReflectionNamedType::class => [$type], }; foreach ($types as $type) { if (! is_subclass_of($type->getName(), ShouldBeStored::class)) { continue; } // … }I wonder whether we would discuss adding a method on ReflectionType that accepts any given input, and tells you whether that input is valid for that type or not. I was thinking aboutReflectionType::accepts(string|object $input): boolbut we could discuss another name. With it, the above example could be refactored like so:if (! $type->accepts(ShouldBeStored::class)) { return; } // …I believe this method should accept both class names and objects to be consistent with the existing reflection API. It would also work with intersection types, if they are to be added some day. What do you think? Kind regards Brent