1: <?php declare(strict_types = 1);
2:
3: namespace PHPStan\Testing;
4:
5: use PhpParser\Node;
6: use PhpParser\Node\Expr\StaticCall;
7: use PhpParser\Node\Name;
8: use PHPStan\Analyser\NodeScopeResolver;
9: use PHPStan\Analyser\Scope;
10: use PHPStan\Analyser\ScopeContext;
11: use PHPStan\DependencyInjection\Type\DynamicThrowTypeExtensionProvider;
12: use PHPStan\DependencyInjection\Type\ParameterClosureTypeExtensionProvider;
13: use PHPStan\DependencyInjection\Type\ParameterOutTypeExtensionProvider;
14: use PHPStan\File\FileHelper;
15: use PHPStan\File\SystemAgnosticSimpleRelativePathHelper;
16: use PHPStan\Php\PhpVersion;
17: use PHPStan\PhpDoc\PhpDocInheritanceResolver;
18: use PHPStan\PhpDoc\StubPhpDocProvider;
19: use PHPStan\Reflection\InitializerExprTypeResolver;
20: use PHPStan\Reflection\SignatureMap\SignatureMapProvider;
21: use PHPStan\Rules\Properties\ReadWritePropertiesExtensionProvider;
22: use PHPStan\TrinaryLogic;
23: use PHPStan\Type\ConstantScalarType;
24: use PHPStan\Type\FileTypeMapper;
25: use PHPStan\Type\Type;
26: use PHPStan\Type\VerbosityLevel;
27: use Symfony\Component\Finder\Finder;
28: use function array_map;
29: use function array_merge;
30: use function count;
31: use function fclose;
32: use function fgets;
33: use function fopen;
34: use function in_array;
35: use function is_dir;
36: use function is_string;
37: use function preg_match;
38: use function sprintf;
39: use function stripos;
40: use function strpos;
41: use function strtolower;
42: use function version_compare;
43: use const PHP_VERSION;
44:
45: /** @api */
46: abstract class TypeInferenceTestCase extends PHPStanTestCase
47: {
48:
49: /**
50: * @param callable(Node , Scope ): void $callback
51: * @param string[] $dynamicConstantNames
52: */
53: public static function processFile(
54: string $file,
55: callable $callback,
56: array $dynamicConstantNames = [],
57: ): void
58: {
59: $reflectionProvider = self::createReflectionProvider();
60: $typeSpecifier = self::getContainer()->getService('typeSpecifier');
61: $fileHelper = self::getContainer()->getByType(FileHelper::class);
62: $resolver = new NodeScopeResolver(
63: $reflectionProvider,
64: self::getContainer()->getByType(InitializerExprTypeResolver::class),
65: self::getReflector(),
66: self::getClassReflectionExtensionRegistryProvider(),
67: self::getContainer()->getByType(ParameterOutTypeExtensionProvider::class),
68: self::getParser(),
69: self::getContainer()->getByType(FileTypeMapper::class),
70: self::getContainer()->getByType(StubPhpDocProvider::class),
71: self::getContainer()->getByType(PhpVersion::class),
72: self::getContainer()->getByType(SignatureMapProvider::class),
73: self::getContainer()->getByType(PhpDocInheritanceResolver::class),
74: self::getContainer()->getByType(FileHelper::class),
75: $typeSpecifier,
76: self::getContainer()->getByType(DynamicThrowTypeExtensionProvider::class),
77: self::getContainer()->getByType(ReadWritePropertiesExtensionProvider::class),
78: self::getContainer()->getByType(ParameterClosureTypeExtensionProvider::class),
79: self::createScopeFactory($reflectionProvider, $typeSpecifier),
80: self::getContainer()->getParameter('polluteScopeWithLoopInitialAssignments'),
81: self::getContainer()->getParameter('polluteScopeWithAlwaysIterableForeach'),
82: self::getContainer()->getParameter('polluteScopeWithBlock'),
83: static::getEarlyTerminatingMethodCalls(),
84: static::getEarlyTerminatingFunctionCalls(),
85: self::getContainer()->getParameter('universalObjectCratesClasses'),
86: self::getContainer()->getParameter('exceptions')['implicitThrows'],
87: self::getContainer()->getParameter('treatPhpDocTypesAsCertain'),
88: );
89: $resolver->setAnalysedFiles(array_map(static fn (string $file): string => $fileHelper->normalizePath($file), array_merge([$file], static::getAdditionalAnalysedFiles())));
90:
91: $scopeFactory = self::createScopeFactory($reflectionProvider, $typeSpecifier, $dynamicConstantNames);
92: $scope = $scopeFactory->create(ScopeContext::create($file));
93:
94: $resolver->processNodes(
95: self::getParser()->parseFile($file),
96: $scope,
97: $callback,
98: );
99: }
100:
101: /**
102: * @api
103: * @param mixed ...$args
104: */
105: public function assertFileAsserts(
106: string $assertType,
107: string $file,
108: ...$args,
109: ): void
110: {
111: if ($assertType === 'type') {
112: if ($args[0] instanceof Type) {
113: // backward compatibility
114: $expectedType = $args[0];
115: $this->assertInstanceOf(ConstantScalarType::class, $expectedType);
116: $expected = $expectedType->getValue();
117: $actualType = $args[1];
118: $actual = $actualType->describe(VerbosityLevel::precise());
119: } else {
120: $expected = $args[0];
121: $actual = $args[1];
122: }
123:
124: $this->assertSame(
125: $expected,
126: $actual,
127: sprintf('Expected type %s, got type %s in %s on line %d.', $expected, $actual, $file, $args[2]),
128: );
129: } elseif ($assertType === 'variableCertainty') {
130: $expectedCertainty = $args[0];
131: $actualCertainty = $args[1];
132: $variableName = $args[2];
133: $this->assertTrue(
134: $expectedCertainty->equals($actualCertainty),
135: sprintf('Expected %s, actual certainty of %s is %s in %s on line %d.', $expectedCertainty->describe(), $variableName, $actualCertainty->describe(), $file, $args[3]),
136: );
137: }
138: }
139:
140: /**
141: * @api
142: * @return array<string, mixed[]>
143: */
144: public static function gatherAssertTypes(string $file): array
145: {
146: $fileHelper = self::getContainer()->getByType(FileHelper::class);
147:
148: $relativePathHelper = new SystemAgnosticSimpleRelativePathHelper($fileHelper);
149:
150: $file = $fileHelper->normalizePath($file);
151:
152: $asserts = [];
153: self::processFile($file, static function (Node $node, Scope $scope) use (&$asserts, $file, $relativePathHelper): void {
154: if (!$node instanceof Node\Expr\FuncCall) {
155: return;
156: }
157:
158: $nameNode = $node->name;
159: if (!$nameNode instanceof Name) {
160: return;
161: }
162:
163: $functionName = $nameNode->toString();
164: if (in_array(strtolower($functionName), ['asserttype', 'assertnativetype', 'assertvariablecertainty'], true)) {
165: self::fail(sprintf(
166: 'Missing use statement for %s() in %s on line %d.',
167: $functionName,
168: $relativePathHelper->getRelativePath($file),
169: $node->getStartLine(),
170: ));
171: } elseif ($functionName === 'PHPStan\\Testing\\assertType') {
172: $expectedType = $scope->getType($node->getArgs()[0]->value);
173: if (!$expectedType instanceof ConstantScalarType) {
174: self::fail(sprintf(
175: 'Expected type must be a literal string, %s given in %s on line %d.',
176: $expectedType->describe(VerbosityLevel::precise()),
177: $relativePathHelper->getRelativePath($file),
178: $node->getStartLine(),
179: ));
180: }
181: $actualType = $scope->getType($node->getArgs()[1]->value);
182: $assert = ['type', $file, $expectedType->getValue(), $actualType->describe(VerbosityLevel::precise()), $node->getStartLine()];
183: } elseif ($functionName === 'PHPStan\\Testing\\assertNativeType') {
184: $expectedType = $scope->getType($node->getArgs()[0]->value);
185: if (!$expectedType instanceof ConstantScalarType) {
186: self::fail(sprintf(
187: 'Expected type must be a literal string, %s given in %s on line %d.',
188: $expectedType->describe(VerbosityLevel::precise()),
189: $relativePathHelper->getRelativePath($file),
190: $node->getStartLine(),
191: ));
192: }
193:
194: $actualType = $scope->getNativeType($node->getArgs()[1]->value);
195: $assert = ['type', $file, $expectedType->getValue(), $actualType->describe(VerbosityLevel::precise()), $node->getStartLine()];
196: } elseif ($functionName === 'PHPStan\\Testing\\assertVariableCertainty') {
197: $certainty = $node->getArgs()[0]->value;
198: if (!$certainty instanceof StaticCall) {
199: self::fail(sprintf('First argument of %s() must be TrinaryLogic call', $functionName));
200: }
201: if (!$certainty->class instanceof Node\Name) {
202: self::fail(sprintf('ERROR: Invalid TrinaryLogic call.'));
203: }
204:
205: if ($certainty->class->toString() !== 'PHPStan\\TrinaryLogic') {
206: self::fail(sprintf('ERROR: Invalid TrinaryLogic call.'));
207: }
208:
209: if (!$certainty->name instanceof Node\Identifier) {
210: self::fail(sprintf('ERROR: Invalid TrinaryLogic call.'));
211: }
212:
213: // @phpstan-ignore staticMethod.dynamicName
214: $expectedertaintyValue = TrinaryLogic::{$certainty->name->toString()}();
215: $variable = $node->getArgs()[1]->value;
216: if ($variable instanceof Node\Expr\Variable && is_string($variable->name)) {
217: $actualCertaintyValue = $scope->hasVariableType($variable->name);
218: $variableDescription = sprintf('variable $%s', $variable->name);
219: } elseif ($variable instanceof Node\Expr\ArrayDimFetch && $variable->dim !== null) {
220: $offset = $scope->getType($variable->dim);
221: $actualCertaintyValue = $scope->getType($variable->var)->hasOffsetValueType($offset);
222: $variableDescription = sprintf('offset %s', $offset->describe(VerbosityLevel::precise()));
223: } else {
224: self::fail(sprintf('ERROR: Invalid assertVariableCertainty call.'));
225: }
226:
227: $assert = ['variableCertainty', $file, $expectedertaintyValue, $actualCertaintyValue, $variableDescription, $node->getStartLine()];
228: } else {
229: $correctFunction = null;
230:
231: $assertFunctions = [
232: 'assertType' => 'PHPStan\\Testing\\assertType',
233: 'assertNativeType' => 'PHPStan\\Testing\\assertNativeType',
234: 'assertVariableCertainty' => 'PHPStan\\Testing\\assertVariableCertainty',
235: ];
236: foreach ($assertFunctions as $assertFn => $fqFunctionName) {
237: if (stripos($functionName, $assertFn) === false) {
238: continue;
239: }
240:
241: $correctFunction = $fqFunctionName;
242: }
243:
244: if ($correctFunction === null) {
245: return;
246: }
247:
248: self::fail(sprintf(
249: 'Function %s imported with wrong namespace %s called in %s on line %d.',
250: $correctFunction,
251: $functionName,
252: $relativePathHelper->getRelativePath($file),
253: $node->getStartLine(),
254: ));
255: }
256:
257: if (count($node->getArgs()) !== 2) {
258: self::fail(sprintf(
259: 'ERROR: Wrong %s() call in %s on line %d.',
260: $functionName,
261: $relativePathHelper->getRelativePath($file),
262: $node->getStartLine(),
263: ));
264: }
265:
266: $asserts[$file . ':' . $node->getStartLine()] = $assert;
267: });
268:
269: if (count($asserts) === 0) {
270: self::fail(sprintf('File %s does not contain any asserts', $file));
271: }
272:
273: return $asserts;
274: }
275:
276: /**
277: * @api
278: * @return array<string, mixed[]>
279: */
280: public static function gatherAssertTypesFromDirectory(string $directory): array
281: {
282: $asserts = [];
283: foreach (self::findTestDataFilesFromDirectory($directory) as $path) {
284: foreach (self::gatherAssertTypes($path) as $key => $assert) {
285: $asserts[$key] = $assert;
286: }
287: }
288:
289: return $asserts;
290: }
291:
292: /**
293: * @return list<string>
294: */
295: public static function findTestDataFilesFromDirectory(string $directory): array
296: {
297: if (!is_dir($directory)) {
298: self::fail(sprintf('Directory %s does not exist.', $directory));
299: }
300:
301: $finder = new Finder();
302: $finder->followLinks();
303: $files = [];
304: foreach ($finder->files()->name('*.php')->in($directory) as $fileInfo) {
305: $path = $fileInfo->getPathname();
306: if (self::isFileLintSkipped($path)) {
307: continue;
308: }
309: $files[] = $path;
310: }
311:
312: return $files;
313: }
314:
315: /**
316: * From https://github.com/php-parallel-lint/PHP-Parallel-Lint/blob/0c2706086ac36dce31967cb36062ff8915fe03f7/bin/skip-linting.php
317: *
318: * Copyright (c) 2012, Jakub Onderka
319: */
320: private static function isFileLintSkipped(string $file): bool
321: {
322: $f = @fopen($file, 'r');
323: if ($f !== false) {
324: $firstLine = fgets($f);
325: if ($firstLine === false) {
326: return false;
327: }
328:
329: // ignore shebang line
330: if (strpos($firstLine, '#!') === 0) {
331: $firstLine = fgets($f);
332: if ($firstLine === false) {
333: return false;
334: }
335: }
336:
337: @fclose($f);
338:
339: if (preg_match('~<?php\\s*\\/\\/\s*lint\s*([^\d\s]+)\s*([^\s]+)\s*~i', $firstLine, $m) === 1) {
340: return version_compare(PHP_VERSION, $m[2], $m[1]) === false;
341: }
342: }
343:
344: return false;
345: }
346:
347: /** @return string[] */
348: protected static function getAdditionalAnalysedFiles(): array
349: {
350: return [];
351: }
352:
353: /** @return string[][] */
354: protected static function getEarlyTerminatingMethodCalls(): array
355: {
356: return [];
357: }
358:
359: /** @return string[] */
360: protected static function getEarlyTerminatingFunctionCalls(): array
361: {
362: return [];
363: }
364:
365: }
366: