diff --git a/module/Rest/config/initial-api-key.config.php b/module/Rest/config/initial-api-key.config.php index 57114479..a44f877f 100644 --- a/module/Rest/config/initial-api-key.config.php +++ b/module/Rest/config/initial-api-key.config.php @@ -11,6 +11,8 @@ use const PHP_SAPI; return [ + // We will try to load the initial API key only for openswoole and RoadRunner. + // For php-fpm, the check against the database would happen on every request, resulting in a very bad performance. 'initial_api_key' => PHP_SAPI !== 'cli' ? null : EnvVars::INITIAL_API_KEY->loadFromEnv(), 'dependencies' => [ diff --git a/module/Rest/test/ApiKey/InitialApiKeyDelegatorTest.php b/module/Rest/test/ApiKey/InitialApiKeyDelegatorTest.php new file mode 100644 index 00000000..7614fc9d --- /dev/null +++ b/module/Rest/test/ApiKey/InitialApiKeyDelegatorTest.php @@ -0,0 +1,61 @@ +delegator = new InitialApiKeyDelegator(); + $this->container = $this->prophesize(ContainerInterface::class); + } + + /** + * @test + * @dataProvider provideConfigs + */ + public function apiKeyIsInitializedWhenAppropriate(array $config, int $expectedCalls): void + { + $app = $this->prophesize(Application::class)->reveal(); + $apiKeyRepo = $this->prophesize(ApiKeyRepositoryInterface::class); + $em = $this->prophesize(EntityManagerInterface::class); + + $getConfig = $this->container->get('config')->willReturn($config); + $getRepo = $em->getRepository(ApiKey::class)->willReturn($apiKeyRepo->reveal()); + $getEm = $this->container->get(EntityManager::class)->willReturn($em->reveal()); + + $result = ($this->delegator)($this->container->reveal(), '', fn () => $app); + + self::assertSame($result, $app); + $getConfig->shouldHaveBeenCalledOnce(); + $getRepo->shouldHaveBeenCalledTimes($expectedCalls); + $getEm->shouldHaveBeenCalledTimes($expectedCalls); + $apiKeyRepo->createInitialApiKey(Argument::any())->shouldHaveBeenCalledTimes($expectedCalls); + } + + public function provideConfigs(): iterable + { + yield [[], 0]; + yield [['initial_api_key' => null], 0]; + yield [['initial_api_key' => 'the_initial_key'], 1]; + } +}