|
| 1 | +<?php declare(strict_types = 1); |
| 2 | + |
| 3 | +namespace PHPStan\Rules\RestrictedUsage; |
| 4 | + |
| 5 | +use PHPStan\Type\Type; |
| 6 | +use PHPStan\Type\UnionType; |
| 7 | +use function array_values; |
| 8 | + |
| 9 | +final class RestrictedUsageObjectClassNames |
| 10 | +{ |
| 11 | + |
| 12 | + /** |
| 13 | + * Class names of the members of the type, so that the object part of a union |
| 14 | + * is still checked when it is combined with null, false, string, ... |
| 15 | + * Members without a class name contribute nothing. |
| 16 | + * |
| 17 | + * Iterates the members directly instead of intersecting with `object`, |
| 18 | + * as this runs for every method call and property fetch. |
| 19 | + * |
| 20 | + * @return list<string> |
| 21 | + */ |
| 22 | + public static function get(Type $type): array |
| 23 | + { |
| 24 | + return self::collect($type, false); |
| 25 | + } |
| 26 | + |
| 27 | + /** |
| 28 | + * Same as get(), for the class expression of a static access (`$expr::foo()`), |
| 29 | + * where a member can also be a class-string. |
| 30 | + * |
| 31 | + * @return list<string> |
| 32 | + */ |
| 33 | + public static function getFromClassExpression(Type $type): array |
| 34 | + { |
| 35 | + return self::collect($type, true); |
| 36 | + } |
| 37 | + |
| 38 | + /** |
| 39 | + * @return list<string> |
| 40 | + */ |
| 41 | + private static function collect(Type $type, bool $acceptClassStrings): array |
| 42 | + { |
| 43 | + $members = $type instanceof UnionType ? $type->getTypes() : [$type]; |
| 44 | + |
| 45 | + $classNames = []; |
| 46 | + foreach ($members as $member) { |
| 47 | + if ($acceptClassStrings) { |
| 48 | + $member = $member->getObjectTypeOrClassStringObjectType(); |
| 49 | + } |
| 50 | + |
| 51 | + foreach ($member->getObjectClassNames() as $className) { |
| 52 | + $classNames[$className] = $className; |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + return array_values($classNames); |
| 57 | + } |
| 58 | + |
| 59 | +} |
0 commit comments