1: <?php declare(strict_types = 1);
2:
3: namespace PHPStan\Testing;
4:
5: use Override;
6: use PHPStan\Analyser\ConstantResolver;
7: use PHPStan\Analyser\DirectInternalScopeFactoryFactory;
8: use PHPStan\Analyser\Error;
9: use PHPStan\Analyser\ScopeFactory;
10: use PHPStan\Analyser\TypeSpecifier;
11: use PHPStan\Analyser\ValueDependencyCollector;
12: use PHPStan\BetterReflection\Reflector\Reflector;
13: use PHPStan\DependencyInjection\Reflection\ClassReflectionExtensionRegistryProvider;
14: use PHPStan\Node\Printer\ExprPrinter;
15: use PHPStan\Parser\Parser;
16: use PHPStan\Php\ComposerPhpVersionFactory;
17: use PHPStan\Php\ConfiguredPhpVersionRangeHelper;
18: use PHPStan\Php\PhpVersion;
19: use PHPStan\PhpDoc\TypeNodeResolver;
20: use PHPStan\PhpDocParser\Lexer\Lexer;
21: use PHPStan\PhpDocParser\Parser\TypeParser;
22: use PHPStan\Reflection\AttributeReflectionFactory;
23: use PHPStan\Reflection\InitializerExprTypeResolver;
24: use PHPStan\Reflection\ReflectionProvider;
25: use PHPStan\Reflection\ReflectionProvider\DirectReflectionProviderProvider;
26: use PHPStan\Rules\Properties\PropertyReflectionFinder;
27: use PHPStan\Testing\PHPUnit\ContainerInitializer;
28: use PHPStan\Type\Constant\OversizedArrayBuilder;
29: use PHPStan\Type\ExpressionTypeResolverExtension;
30: use PHPStan\Type\OperatorTypeSpecifyingExtensionRegistry;
31: use PHPStan\Type\TypeAliasResolver;
32: use PHPStan\Type\UnaryOperatorTypeSpecifyingExtensionRegistry;
33: use PHPStan\Type\UsefulTypeAliasResolver;
34: use PHPUnit\Framework\ExpectationFailedException;
35: use PHPUnit\Framework\TestCase;
36: use function count;
37: use function implode;
38: use function rtrim;
39: use function sprintf;
40: use const DIRECTORY_SEPARATOR;
41:
42: /** @api */
43: abstract class PHPStanTestCase extends TestCase
44: {
45:
46: use PHPStanTestCaseTrait;
47:
48: /**
49: * Re-register this test class's container as the owner of the global static state
50: * (the reflection provider, the PhpVersion, the bleeding edge toggle) before every
51: * test, so a container another test class installed can't flake tests that build
52: * Type objects directly. See https://github.com/phpstan/phpstan/issues/14860
53: *
54: * This is the only hook that does it, on every PHPUnit version. Data providers
55: * are covered separately - see PHPStanTestCaseTrait::restoreBaseContainer().
56: */
57: #[Override]
58: protected function setUp(): void
59: {
60: ContainerInitializer::initialize(static::class);
61: }
62:
63: #[Override]
64: public static function tearDownAfterClass(): void
65: {
66: parent::tearDownAfterClass();
67:
68: // The next test class's data providers run before any hook this test case has
69: // on PHPUnit 9, in the same ParaTest worker process - see restoreBaseContainer().
70: self::restoreBaseContainer();
71: }
72:
73: public static function getParser(): Parser
74: {
75: /** @var Parser $parser */
76: $parser = self::getContainer()->getService('defaultAnalysisParser');
77: return $parser;
78: }
79:
80: /** @api */
81: public static function createReflectionProvider(): ReflectionProvider
82: {
83: return self::getContainer()->getByType(ReflectionProvider::class);
84: }
85:
86: public static function getReflector(): Reflector
87: {
88: return self::getContainer()->getService('betterReflectionReflector');
89: }
90:
91: public static function getClassReflectionExtensionRegistryProvider(): ClassReflectionExtensionRegistryProvider
92: {
93: return self::getContainer()->getByType(ClassReflectionExtensionRegistryProvider::class);
94: }
95:
96: /**
97: * @param string[] $dynamicConstantNames
98: */
99: public static function createScopeFactory(ReflectionProvider $reflectionProvider, TypeSpecifier $typeSpecifier, array $dynamicConstantNames = []): ScopeFactory
100: {
101: $container = self::getContainer();
102:
103: if (count($dynamicConstantNames) === 0) {
104: $dynamicConstantNames = $container->getParameter('dynamicConstantNames');
105: }
106:
107: $reflectionProviderProvider = new DirectReflectionProviderProvider($reflectionProvider);
108: $composerPhpVersionFactory = $container->getByType(ComposerPhpVersionFactory::class);
109: $constantResolver = new ConstantResolver($reflectionProviderProvider, $dynamicConstantNames, new ConfiguredPhpVersionRangeHelper(null, $composerPhpVersionFactory), container: $container);
110:
111: $initializerExprTypeResolver = new InitializerExprTypeResolver(
112: $constantResolver,
113: $reflectionProviderProvider,
114: $container->getByType(PhpVersion::class),
115: $container->getByType(OperatorTypeSpecifyingExtensionRegistry::class),
116: $container->getByType(UnaryOperatorTypeSpecifyingExtensionRegistry::class),
117: new OversizedArrayBuilder(),
118: $container->getParameter('usePathConstantsAsConstantString'),
119: $container->getByType(ValueDependencyCollector::class),
120: );
121:
122: return new ScopeFactory(
123: new DirectInternalScopeFactoryFactory(
124: $container,
125: $reflectionProvider,
126: $initializerExprTypeResolver,
127: $container->getExtensionsCollection(ExpressionTypeResolverExtension::class),
128: $container->getByType(ExprPrinter::class),
129: $typeSpecifier,
130: new PropertyReflectionFinder(),
131: self::getParser(),
132: $container->getByType(PhpVersion::class),
133: $container->getByType(AttributeReflectionFactory::class),
134: $container->getByType(ConfiguredPhpVersionRangeHelper::class),
135: $constantResolver,
136: ),
137: );
138: }
139:
140: /**
141: * @param array<string, string> $globalTypeAliases
142: */
143: public static function createTypeAliasResolver(array $globalTypeAliases, ReflectionProvider $reflectionProvider): TypeAliasResolver
144: {
145: $container = self::getContainer();
146:
147: return new UsefulTypeAliasResolver(
148: $globalTypeAliases,
149: $container->getByType(Lexer::class),
150: $container->getByType(TypeParser::class),
151: $container->getByType(TypeNodeResolver::class),
152: $reflectionProvider,
153: 0,
154: );
155: }
156:
157: protected function shouldTreatPhpDocTypesAsCertain(): bool
158: {
159: return true;
160: }
161:
162: /**
163: * Provides a DIRECTORY_SEPARATOR agnostic assertion helper, to compare file paths.
164: *
165: */
166: protected function assertSamePaths(string $expected, string $actual, string $message = ''): void
167: {
168: $expected = $this->getFileHelper()->normalizePath($expected);
169: $actual = $this->getFileHelper()->normalizePath($actual);
170:
171: $this->assertSame($expected, $actual, $message);
172: }
173:
174: /**
175: * @param Error[]|string[] $errors
176: */
177: protected function assertNoErrors(array $errors): void
178: {
179: try {
180: $this->assertCount(0, $errors);
181: } catch (ExpectationFailedException $e) {
182: $messages = [];
183: foreach ($errors as $error) {
184: if ($error instanceof Error) {
185: $messages[] = sprintf("- %s\n in %s on line %d%s\n", rtrim($error->getMessage(), '.'), $error->getFile(), $error->getLine() ?? 0, $error->getTip() !== null ? sprintf("\n💡 %s", $error->getTip()) : '');
186: } else {
187: $messages[] = $error;
188: }
189: }
190:
191: $this->fail($e->getMessage() . "\n\nEmitted errors:\n" . implode("\n", $messages));
192: }
193: }
194:
195: protected function skipIfNotOnWindows(): void
196: {
197: if (DIRECTORY_SEPARATOR === '\\') {
198: return;
199: }
200:
201: self::markTestSkipped();
202: }
203:
204: protected function skipIfNotOnUnix(): void
205: {
206: if (DIRECTORY_SEPARATOR === '/') {
207: return;
208: }
209:
210: self::markTestSkipped();
211: }
212:
213: }
214: