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