|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace ShlinkioApiTest\Shlink\Rest\Utils; |
| 6 | + |
| 7 | +use PHPUnit\Event\Test\PreparationStarted; |
| 8 | +use PHPUnit\Event\Test\PreparationStartedSubscriber; |
| 9 | +use ReflectionMethod; |
| 10 | +use Symfony\Component\Process\Process; |
| 11 | +use Webimpress\SafeWriter\FileWriter; |
| 12 | + |
| 13 | +use function sprintf; |
| 14 | +use function var_export; |
| 15 | + |
| 16 | +use const ShlinkioTest\Shlink\DYNAMIC_ENV_VARS_FILE; |
| 17 | + |
| 18 | +/** |
| 19 | + * Checks if a test to be executed has the WithEnvVars attribute, and if so, creates a file with the env vars it defines |
| 20 | + * and restarts RoadRunner test server so that those env vars are applied. |
| 21 | + */ |
| 22 | +class EnvSpecificTestListener implements PreparationStartedSubscriber |
| 23 | +{ |
| 24 | + public function notify(PreparationStarted $event): void |
| 25 | + { |
| 26 | + $test = $event->test(); |
| 27 | + $className = $test->className(); |
| 28 | + $methodName = $test->methodName(); |
| 29 | + |
| 30 | + $reflection = new ReflectionMethod($className, $methodName); |
| 31 | + $attributes = $reflection->getAttributes(WithEnvVars::class); |
| 32 | + |
| 33 | + // If the method has the attribute, generate a temporary env file, and restart the RoadRunner server |
| 34 | + if (! empty($attributes)) { |
| 35 | + /** @var WithEnvVars $withEnvVars */ |
| 36 | + $withEnvVars = $attributes[0]->newInstance(); |
| 37 | + $this->createDynamicEnvVarsFile($withEnvVars->envVars); |
| 38 | + $this->restartServer(); |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + private function createDynamicEnvVarsFile(array $envVars): void |
| 43 | + { |
| 44 | + $template = <<<TEMPLATE |
| 45 | + <?php |
| 46 | + |
| 47 | + /* Shlink config generated by %s */ |
| 48 | + |
| 49 | + return %s; |
| 50 | + |
| 51 | + TEMPLATE; |
| 52 | + $content = sprintf($template, self::class, var_export($envVars, return: true)); |
| 53 | + |
| 54 | + FileWriter::writeFile(DYNAMIC_ENV_VARS_FILE, $content); |
| 55 | + } |
| 56 | + |
| 57 | + private function restartServer(): void |
| 58 | + { |
| 59 | + (new Process(['bin/rr', 'reset', '-c=config/roadrunner/.rr.test.yml']))->mustRun(); |
| 60 | + } |
| 61 | +} |
0 commit comments