|
| 1 | +<?php declare(strict_types=1); |
| 2 | + |
| 3 | +namespace PHPStan\Drupal; |
| 4 | + |
| 5 | +use Drupal\Core\DependencyInjection\ContainerNotInitializedException; |
| 6 | +use PHPStan\Analyser\Analyser; |
| 7 | +use PHPStan\DependencyInjection\ContainerFactory; |
| 8 | +use PHPStan\File\FileHelper; |
| 9 | +use PHPUnit\Framework\TestCase; |
| 10 | + |
| 11 | +abstract class AnalyzerTestBase extends TestCase { |
| 12 | + |
| 13 | + protected function runAnalyze(string $path) { |
| 14 | + $rootDir = __DIR__ . '/../fixtures/drupal'; |
| 15 | + $tmpDir = sys_get_temp_dir() . '/' . time() . 'phpstan'; |
| 16 | + $containerFactory = new ContainerFactory($rootDir); |
| 17 | + $container = $containerFactory->create( |
| 18 | + $tmpDir, |
| 19 | + [__DIR__ . '/../fixtures/config/phpunit-drupal-phpstan.neon'], |
| 20 | + [] |
| 21 | + ); |
| 22 | + $fileHelper = $container->getByType(FileHelper::class); |
| 23 | + assert($fileHelper !== null); |
| 24 | + |
| 25 | + $bootstrapFile = $container->parameters['bootstrap']; |
| 26 | + $this->assertEquals(dirname(__DIR__, 2) . '/phpstan-bootstrap.php', $bootstrapFile); |
| 27 | + // Mock the autoloader. |
| 28 | + $GLOBALS['drupalVendorDir'] = dirname(__DIR__, 2) . '/vendor'; |
| 29 | + if ($bootstrapFile !== null) { |
| 30 | + $bootstrapFile = $fileHelper->normalizePath($bootstrapFile); |
| 31 | + if (!is_file($bootstrapFile)) { |
| 32 | + $this->fail('Bootstrap file not found'); |
| 33 | + } |
| 34 | + try { |
| 35 | + (static function (string $file): void { |
| 36 | + require_once $file; |
| 37 | + })($bootstrapFile); |
| 38 | + } catch (ContainerNotInitializedException $e) { |
| 39 | + $trace = $e->getTrace(); |
| 40 | + $offending_file = $trace[1]; |
| 41 | + $this->fail(sprintf('%s called the Drupal container from unscoped code.', $offending_file['file'])); |
| 42 | + } |
| 43 | + catch (\Throwable $e) { |
| 44 | + $this->fail('Could not load the bootstrap file'); |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + $analyser = $container->getByType(Analyser::class); |
| 49 | + assert($analyser !== null); |
| 50 | + |
| 51 | + $file = $fileHelper->normalizePath($path); |
| 52 | + $errors = $analyser->analyse( |
| 53 | + [$file], |
| 54 | + false, |
| 55 | + null, |
| 56 | + null, |
| 57 | + true |
| 58 | + ); |
| 59 | + foreach ($errors as $error) { |
| 60 | + $this->assertSame($fileHelper->normalizePath($file), $error->getFile()); |
| 61 | + } |
| 62 | + return $errors; |
| 63 | + } |
| 64 | + |
| 65 | + |
| 66 | +} |
0 commit comments