1: <?php declare(strict_types = 1);
2:
3: namespace PHPStan\Rules;
4:
5: use PhpParser\Node\Expr;
6: use PHPStan\Analyser\Scope;
7: use PHPStan\DependencyInjection\AutowiredParameter;
8: use PHPStan\DependencyInjection\AutowiredService;
9: use PHPStan\Reflection\ParametersAcceptor;
10: use PHPStan\Reflection\ReflectionProvider;
11: use PHPStan\Turbo\ShadowedByTurboExtension;
12: use PHPStan\Type\BenevolentUnionType;
13: use PHPStan\Type\CallableType;
14: use PHPStan\Type\ClosureType;
15: use PHPStan\Type\ErrorType;
16: use PHPStan\Type\Generic\GenericObjectType;
17: use PHPStan\Type\Generic\TemplateMixedType;
18: use PHPStan\Type\Generic\TemplateType;
19: use PHPStan\Type\Generic\TemplateTypeVariance;
20: use PHPStan\Type\IntersectionType;
21: use PHPStan\Type\MixedType;
22: use PHPStan\Type\NeverType;
23: use PHPStan\Type\NullType;
24: use PHPStan\Type\StrictMixedType;
25: use PHPStan\Type\Type;
26: use PHPStan\Type\TypeCombinator;
27: use PHPStan\Type\TypeTraverser;
28: use PHPStan\Type\TypeUtils;
29: use PHPStan\Type\UnionType;
30: use function count;
31: use function sprintf;
32:
33: #[AutowiredService]
34: #[ShadowedByTurboExtension(implementation: __DIR__ . '/../../turbo-ext/src/RuleLevelHelper.cpp')]
35: final class RuleLevelHelper
36: {
37:
38: public function __construct(
39: private ReflectionProvider $reflectionProvider,
40: #[AutowiredParameter]
41: private bool $checkNullables,
42: #[AutowiredParameter]
43: private bool $checkThisOnly,
44: #[AutowiredParameter]
45: private bool $checkUnionTypes,
46: #[AutowiredParameter]
47: private bool $checkExplicitMixed,
48: #[AutowiredParameter]
49: private bool $checkImplicitMixed,
50: #[AutowiredParameter]
51: private bool $checkBenevolentUnionTypes,
52: #[AutowiredParameter(ref: '%tips.discoveringSymbols%')]
53: private bool $discoveringSymbolsTip,
54: #[AutowiredParameter(ref: '%featureToggles.checkMixedWitnessTypes%')]
55: private bool $checkMixedWitnessTypes = false,
56: )
57: {
58: }
59:
60: /**
61: * @param callable(Type): Type $traverse
62: */
63: private function traverseWithoutMapping(Type $type, ?Type $acceptingType, callable $traverse): Type
64: {
65: if ($type instanceof GenericObjectType && $acceptingType !== null) {
66: return $type->traverseSimultaneously($acceptingType, function (Type $type, Type $acceptingType) use ($traverse): Type {
67: if (
68: !$this->checkNullables
69: && !$type instanceof BenevolentUnionType
70: && TypeCombinator::containsNull($type)
71: && !TypeCombinator::containsNull($acceptingType)
72: ) {
73: return $traverse(TypeCombinator::removeNull($type));
74: }
75:
76: return $type;
77: });
78: }
79:
80: return $traverse($type);
81: }
82:
83: /** @api */
84: public function isThis(Expr $expression): bool
85: {
86: return $expression instanceof Expr\Variable && $expression->name === 'this';
87: }
88:
89: private function transformCommonType(Type $type): Type
90: {
91: if (!$this->checkExplicitMixed && !$this->checkImplicitMixed) {
92: return $type;
93: }
94:
95: return TypeTraverser::map($type, function (Type $type, callable $traverse): Type {
96: if ($type instanceof GenericObjectType && !$type instanceof TemplateType) {
97: return $this->transformGenericObjectTypeArguments($type, $traverse);
98: }
99:
100: return $this->transformMixedType($type) ?? $traverse($type);
101: });
102: }
103:
104: private function transformMixedType(Type $type): ?Type
105: {
106: if ($type instanceof TemplateMixedType) {
107: if ($this->checkExplicitMixed) {
108: return $type->toStrictMixedType();
109: }
110: }
111: if (
112: $type instanceof MixedType
113: && (
114: ($type->isExplicitMixed() && $this->checkExplicitMixed)
115: || (!$type->isExplicitMixed() && $this->checkImplicitMixed)
116: )
117: ) {
118: return new StrictMixedType();
119: }
120:
121: return null;
122: }
123:
124: /**
125: * Invariant type arguments are compared with equals(), so mapping mixed nested in them
126: * only changes the outcome when one side is mapped and the other is not - like the
127: * type arguments an accepted object type inherits through @extends, which a traversal
128: * does not reach. A top-level mixed is still mapped, as variance checks treat it leniently.
129: *
130: * @param callable(Type): Type $traverse
131: */
132: private function transformGenericObjectTypeArguments(GenericObjectType $type, callable $traverse): Type
133: {
134: $classReflection = $type->getClassReflection();
135: if ($classReflection === null) {
136: return $traverse($type);
137: }
138:
139: $templateTypes = $classReflection->typeMapToList($classReflection->getTemplateTypeMap());
140: $variances = $type->getVariances();
141: $typesChanged = false;
142: $types = [];
143: foreach ($type->getTypes() as $i => $argument) {
144: $templateType = $templateTypes[$i] ?? null;
145: if (
146: ($variances[$i] ?? TemplateTypeVariance::createInvariant())->invariant()
147: && $templateType instanceof TemplateType
148: && $templateType->getVariance()->invariant()
149: ) {
150: $newArgument = $this->transformMixedType($argument) ?? $argument;
151: } else {
152: $newArgument = $traverse($argument);
153: }
154:
155: $types[] = $newArgument;
156: if ($newArgument === $argument) {
157: continue;
158: }
159:
160: $typesChanged = true;
161: }
162:
163: $subtractedType = $type->getSubtractedType();
164: $newSubtractedType = $subtractedType !== null ? $traverse($subtractedType) : null;
165: if (!$typesChanged && $newSubtractedType === $subtractedType) {
166: return $type;
167: }
168:
169: return new GenericObjectType($type->getClassName(), $types, $newSubtractedType, variances: $variances);
170: }
171:
172: /**
173: * @return array{Type, bool}
174: */
175: private function transformAcceptedType(Type $acceptingType, Type $acceptedType): array
176: {
177: $checkForUnion = $this->checkUnionTypes;
178: $acceptedType = TypeTraverser::mapMemoized($acceptedType, function (Type $acceptedType, callable $traverse) use ($acceptingType, &$checkForUnion): Type {
179: if ($acceptedType instanceof CallableType) {
180: if ($acceptedType->isCommonCallable()) {
181: return $acceptedType;
182: }
183:
184: $acceptingReturnType = $acceptingType instanceof ParametersAcceptor ? $acceptingType->getReturnType() : null;
185: return new CallableType(
186: $acceptedType->getParameters(),
187: $this->traverseWithoutMapping($acceptedType->getReturnType(), $acceptingReturnType, $traverse),
188: $acceptedType->isVariadic(),
189: $acceptedType->getTemplateTypeMap(),
190: $acceptedType->getResolvedTemplateTypeMap(),
191: $acceptedType->getTemplateTags(),
192: $acceptedType->isPure(),
193: );
194: }
195:
196: if ($acceptedType instanceof ClosureType) {
197: if ($acceptedType->isCommonCallable()) {
198: return $acceptedType;
199: }
200:
201: $acceptingReturnType = $acceptingType instanceof ParametersAcceptor ? $acceptingType->getReturnType() : null;
202: return new ClosureType(
203: $acceptedType->getParameters(),
204: $this->traverseWithoutMapping($acceptedType->getReturnType(), $acceptingReturnType, $traverse),
205: $acceptedType->isVariadic(),
206: $acceptedType->getTemplateTypeMap(),
207: $acceptedType->getResolvedTemplateTypeMap(),
208: $acceptedType->getCallSiteVarianceMap(),
209: $acceptedType->getTemplateTags(),
210: $acceptedType->getThrowPoints(),
211: $acceptedType->getImpurePoints(),
212: $acceptedType->getInvalidateExpressions(),
213: $acceptedType->getUsedVariables(),
214: $acceptedType->acceptsNamedArguments(),
215: $acceptedType->mustUseReturnValue(),
216: isStatic: $acceptedType->isStaticClosure(),
217: origin: $acceptedType->getOrigin(),
218: );
219: }
220:
221: if ($acceptedType instanceof GenericObjectType) {
222: return $this->traverseWithoutMapping($acceptedType, $acceptingType, $traverse);
223: }
224:
225: if (
226: !$this->checkNullables
227: && !$acceptingType instanceof NullType
228: && !$acceptedType instanceof NullType
229: && !$acceptedType instanceof BenevolentUnionType
230: ) {
231: return $traverse(TypeCombinator::removeNull($acceptedType));
232: }
233:
234: if ($this->checkBenevolentUnionTypes) {
235: if ($acceptedType instanceof BenevolentUnionType) {
236: $checkForUnion = true;
237: return $traverse(TypeUtils::toStrictUnion($acceptedType));
238: }
239: }
240:
241: return $traverse($acceptedType);
242: });
243:
244: return [$this->transformCommonType($acceptedType), $checkForUnion];
245: }
246:
247: /** @api */
248: public function accepts(Type $acceptingType, Type $acceptedType, bool $strictTypes): RuleLevelHelperAcceptsResult
249: {
250: [$transformedAcceptedType, $checkForUnion] = $this->transformAcceptedType($acceptingType, $acceptedType);
251: $transformedAcceptingType = $this->transformCommonType($acceptingType);
252:
253: $accepts = $transformedAcceptingType->accepts($transformedAcceptedType, $strictTypes);
254: $result = $checkForUnion ? $accepts->yes() : !$accepts->no();
255: if (!$result) {
256: return new RuleLevelHelperAcceptsResult(false, $accepts->reasons);
257: }
258:
259: return $this->acceptsWitnessType($acceptingType, $acceptedType, $strictTypes)
260: ?? new RuleLevelHelperAcceptsResult(true, $accepts->reasons);
261: }
262:
263: /**
264: * A mixed that absorbed other types is accepted like mixed, but what some
265: * path is known to produce is checked like any member of a union.
266: */
267: private function acceptsWitnessType(Type $acceptingType, Type $acceptedType, bool $strictTypes): ?RuleLevelHelperAcceptsResult
268: {
269: if (!$this->checkMixedWitnessTypes || !$this->checkUnionTypes || !$acceptedType instanceof MixedType) {
270: return null;
271: }
272:
273: $witnessType = $acceptedType->getWitnessType();
274: if ($witnessType === null) {
275: return null;
276: }
277:
278: $checkedWitnessType = $witnessType;
279: if (!$this->checkNullables && !TypeCombinator::containsNull($acceptingType)) {
280: $checkedWitnessType = TypeCombinator::removeNull($witnessType);
281: if ($checkedWitnessType instanceof NeverType) {
282: return null;
283: }
284: }
285:
286: $accepts = $this->accepts($acceptingType, $checkedWitnessType, $strictTypes);
287: if ($accepts->result) {
288: return null;
289: }
290:
291: return new RuleLevelHelperAcceptsResult(false, $accepts->reasons, $witnessType);
292: }
293:
294: /**
295: * @api
296: * @param callable(Type $type): bool $unionTypeCriteriaCallback
297: */
298: public function findTypeToCheck(
299: Scope $scope,
300: Expr $var,
301: string $unknownClassErrorPattern,
302: callable $unionTypeCriteriaCallback,
303: ): FoundTypeResult
304: {
305: if ($this->checkThisOnly && !$this->isThis($var)) {
306: return new FoundTypeResult(new ErrorType(), [], [], null);
307: }
308: $type = $scope->getType($var);
309:
310: return $this->findTypeToCheckImplementation($scope, $var, $type, $unknownClassErrorPattern, $unionTypeCriteriaCallback, true);
311: }
312:
313: /** @param callable(Type $type): bool $unionTypeCriteriaCallback */
314: private function findTypeToCheckImplementation(
315: Scope $scope,
316: Expr $var,
317: Type $type,
318: string $unknownClassErrorPattern,
319: callable $unionTypeCriteriaCallback,
320: bool $isTopLevel = false,
321: ): FoundTypeResult
322: {
323: if (
324: !$this->checkNullables
325: && !$type->isNull()->yes()
326: && !$unionTypeCriteriaCallback(new NullType())
327: ) {
328: $type = TypeCombinator::removeNull($type);
329: }
330:
331: if (
332: ($this->checkExplicitMixed || $this->checkImplicitMixed)
333: && $type instanceof MixedType
334: && ($type->isExplicitMixed() ? $this->checkExplicitMixed : $this->checkImplicitMixed)
335: ) {
336: return new FoundTypeResult(
337: $type instanceof TemplateMixedType
338: ? $type->toStrictMixedType()
339: : new StrictMixedType(),
340: [],
341: [],
342: null,
343: );
344: }
345:
346: if ($type instanceof MixedType || $type instanceof NeverType) {
347: return new FoundTypeResult(new ErrorType(), [], [], null);
348: }
349:
350: $errors = [];
351: $hasClassExistsClass = false;
352: $directClassNames = [];
353:
354: if ($isTopLevel) {
355: $directClassNames = $type->getObjectClassNames();
356: foreach ($directClassNames as $referencedClass) {
357: if ($this->reflectionProvider->hasClass($referencedClass)) {
358: $classReflection = $this->reflectionProvider->getClass($referencedClass);
359: if (!$classReflection->isTrait()) {
360: continue;
361: }
362: }
363:
364: if ($scope->isInClassExists($referencedClass)) {
365: $hasClassExistsClass = true;
366: continue;
367: }
368:
369: $errorBuilder = RuleErrorBuilder::message(sprintf($unknownClassErrorPattern, $referencedClass))
370: ->line($var->getStartLine())
371: ->identifier('class.notFound');
372:
373: if ($this->discoveringSymbolsTip) {
374: $errorBuilder->discoveringSymbolsTip();
375: }
376:
377: $errors[] = $errorBuilder->build();
378: }
379: }
380:
381: if (count($errors) > 0 || $hasClassExistsClass) {
382: return new FoundTypeResult(new ErrorType(), [], $errors, null);
383: }
384:
385: if (!$this->checkUnionTypes && $type->isObject()->yes() && count($type->getObjectClassNames()) === 0) {
386: return new FoundTypeResult(new ErrorType(), [], [], null);
387: }
388:
389: if ($type instanceof UnionType) {
390: $shouldFilterUnion = (
391: !$this->checkUnionTypes
392: && !$type instanceof BenevolentUnionType
393: ) || (
394: !$this->checkBenevolentUnionTypes
395: && $type instanceof BenevolentUnionType
396: );
397:
398: $newTypes = [];
399:
400: foreach ($type->getTypes() as $innerType) {
401: if ($shouldFilterUnion && !$unionTypeCriteriaCallback($innerType)) {
402: continue;
403: }
404:
405: $newTypes[] = $this->findTypeToCheckImplementation(
406: $scope,
407: $var,
408: $innerType,
409: $unknownClassErrorPattern,
410: $unionTypeCriteriaCallback,
411: )->getType();
412: }
413:
414: if (count($newTypes) > 0) {
415: $newUnion = TypeCombinator::union(...$newTypes);
416: if (
417: !$this->checkBenevolentUnionTypes
418: && $type instanceof BenevolentUnionType
419: ) {
420: $newUnion = TypeUtils::toBenevolentUnion($newUnion);
421: }
422:
423: return new FoundTypeResult($newUnion, $directClassNames, [], null);
424: }
425: }
426:
427: if ($type instanceof IntersectionType) {
428: $newTypes = [];
429:
430: $changed = false;
431: foreach ($type->getTypes() as $innerType) {
432: if ($innerType instanceof TemplateMixedType) {
433: $changed = true;
434: $newTypes[] = $this->findTypeToCheckImplementation(
435: $scope,
436: $var,
437: $innerType->toStrictMixedType(),
438: $unknownClassErrorPattern,
439: $unionTypeCriteriaCallback,
440: )->getType();
441: continue;
442: }
443: $newTypes[] = $innerType;
444: }
445:
446: if ($changed) {
447: return new FoundTypeResult(TypeCombinator::intersect(...$newTypes), $directClassNames, [], null);
448: }
449: }
450:
451: $tip = null;
452: if (
453: $type instanceof UnionType
454: && count($type->getTypes()) === 2
455: && $type->isObject()->yes()
456: && $type->getTypes()[0]->getObjectClassNames() === ['PhpParser\\Node\\Arg']
457: && $type->getTypes()[1]->getObjectClassNames() === ['PhpParser\\Node\\VariadicPlaceholder']
458: && !$unionTypeCriteriaCallback($type)
459: ) {
460: $tip = 'Use <fg=cyan>->getArgs()</> instead of <fg=cyan>->args</>.';
461: }
462:
463: return new FoundTypeResult($type, $directClassNames, [], $tip);
464: }
465:
466: }
467: