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