diff --git a/CHANGELOG.md b/CHANGELOG.md index 5eae076..9ee40cf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,8 @@ ### Unreleased +* [BREAKING]: Added strict types and array shapes throughout. +* [BREAKING]: FactoryFunction::call() no longer accepts or passes arguments to the callable. * [Internal] Bump dev dependencies * Require PHP 8.5 * Require ingenerator/php-utils version 3 diff --git a/phpstan.neon b/phpstan.neon new file mode 100644 index 0000000..1cf356e --- /dev/null +++ b/phpstan.neon @@ -0,0 +1,7 @@ +parameters: + level: 10 + paths: + - src + - test + excludePaths: + - test/blackbox/implementation/htdocs/dynamic diff --git a/rector.php b/rector.php index 6b91a68..7907d00 100644 --- a/rector.php +++ b/rector.php @@ -12,4 +12,9 @@ ->withSkipPath(__DIR__.'/test/blackbox/implementation/htdocs/dynamic') ->withComposerBased(phpunit: true) ->withPhpSets() + ->withPreparedSets( + codeQuality: true, + typeDeclarations: true, + typeDeclarationDocblocks: true, + ) ->withImportNames(); diff --git a/src/DefaultStackdriverLoggerProvider.php b/src/DefaultStackdriverLoggerProvider.php index 8ebb841..471108c 100644 --- a/src/DefaultStackdriverLoggerProvider.php +++ b/src/DefaultStackdriverLoggerProvider.php @@ -3,6 +3,7 @@ namespace Ingenerator\MicroFramework; use Ingenerator\PHPUtils\Logging\DefaultLogMetadata; +use Ingenerator\PHPUtils\Logging\LogMetadataProvider; use Ingenerator\PHPUtils\Logging\StackdriverApplicationLogger; use Psr\Log\LoggerInterface; @@ -29,6 +30,9 @@ public function getLogger(): LoggerInterface return StackdriverApplicationLogger::instance(); } + /** + * @return list> + */ protected function getMetadataProviders(): array { return [ diff --git a/src/FactoryFunction.php b/src/FactoryFunction.php index cd87ec5..d926c0f 100644 --- a/src/FactoryFunction.php +++ b/src/FactoryFunction.php @@ -18,17 +18,16 @@ class FactoryFunction * // Whereas this will throw an UnexpectedValueException * $stdclass = FactoryFunction::call(fn() => new DateTimeImmutable, stdClass::class) * - * @psalm-template T + * @template T of object * - * @psalm-param callable():T $callable - * @psalm-param class-string $expect_class - * @psalm-param array $arguments that will be passed to the function + * @param callable():T $factory + * @param class-string $expect_class * - * @psalm-return T + * @return T */ - public static function call(callable $factory, string $expect_class, array $arguments = []): object + public static function call(callable $factory, string $expect_class): object { - $object = $factory(...$arguments); + $object = $factory(); if (!$object instanceof $expect_class) { throw new UnexpectedValueException( diff --git a/src/MicroFramework.php b/src/MicroFramework.php index ba570ea..a9e1e17 100644 --- a/src/MicroFramework.php +++ b/src/MicroFramework.php @@ -30,7 +30,7 @@ class MicroFramework { - public static function throwingErrorHandler($code, $error, $file = null, $line = null): bool + public static function throwingErrorHandler(int $code, string $error, ?string $file = null, ?int $line = null): bool { if (error_reporting() & $code) { // This error is not suppressed by current error reporting settings @@ -78,7 +78,7 @@ public function execute( : ServerRequest::fromGlobals(); // Hand off to the application for execution - $response = FactoryFunction::call($handler_factory, RequestHandler::class, [$logger]) + $response = FactoryFunction::call(fn () => $handler_factory($logger), RequestHandler::class) ->handle($request); // Render the application result diff --git a/test/blackbox/BaseBlackboxTestCase.php b/test/blackbox/BaseBlackboxTestCase.php index 8bccd19..4603d0d 100644 --- a/test/blackbox/BaseBlackboxTestCase.php +++ b/test/blackbox/BaseBlackboxTestCase.php @@ -4,9 +4,9 @@ use GuzzleHttp\Client; use GuzzleHttp\RequestOptions; -use PHPUnit\Framework\Assert; use PHPUnit\Framework\TestCase; use Psr\Http\Message\ResponseInterface; +use RuntimeException; use Symfony\Component\Filesystem\Filesystem; use UnexpectedValueException; @@ -40,7 +40,12 @@ protected function setUp(): void private function getTestSubjectBaseUrl(): string { $subject_url = getenv('TEST_SUBJECT_BASE_URI'); - Assert::assertNotEmpty($subject_url, 'Expect an environment variable TEST_SUBJECT_BASE_URI'); + if (!is_string($subject_url)) { + throw new RuntimeException('Expect an environment variable TEST_SUBJECT_BASE_URI as a string'); + } + if (empty($subject_url)) { + throw new RuntimeException('Expect an environment variable TEST_SUBJECT_BASE_URI not to be empty string'); + } return $subject_url; } @@ -55,6 +60,9 @@ protected function truncateTestSubjectLogs(): void } } + /** + * @return list + */ protected function getTestSubjectLogEntriesDuringTest(): array { // Wait a moment for logs to be written - they aren't always absolutely immediate @@ -67,9 +75,14 @@ protected function getTestSubjectLogEntriesDuringTest(): array // Each line in the file is in syslog RFC3164 format. The details of the message header not relevant to us, we // are only using syslog format to be able to capture the underlying container STDOUT/STDERR in a docker compose // environment. So we just split the lines on the end of the HEADER and return the CONTENT + $lines = file(self::$test_subject_logs_file, FILE_IGNORE_NEW_LINES); + if ($lines === false) { + throw new RuntimeException('Could not read '.self::$test_subject_logs_file); + } + return array_map( self::extractSyslogRFC3164MessageBody(...), - file(self::$test_subject_logs_file, FILE_IGNORE_NEW_LINES), + $lines, ); } @@ -138,4 +151,14 @@ protected static function provisionDynamicHandler(string $code): string return '/dynamic/'.$id.'/'; } + + final protected function getLocalIp(): string + { + $hostname = gethostname(); + if ($hostname === false) { + throw new RuntimeException('Could not get hostname'); + } + + return gethostbyname($hostname); + } } diff --git a/test/blackbox/BlackboxSmokeTest.php b/test/blackbox/BlackboxSmokeTest.php index a2a4677..ac86668 100644 --- a/test/blackbox/BlackboxSmokeTest.php +++ b/test/blackbox/BlackboxSmokeTest.php @@ -1,10 +1,12 @@ assertResponseMatches( 200, diff --git a/test/blackbox/EnvironmentConfigurationTest.php b/test/blackbox/EnvironmentConfigurationTest.php index 984d22b..50b9135 100644 --- a/test/blackbox/EnvironmentConfigurationTest.php +++ b/test/blackbox/EnvironmentConfigurationTest.php @@ -1,10 +1,12 @@ provisionDynamicHandler( <<<'PHP' @@ -41,7 +43,7 @@ public function handle(ServerRequestInterface $request): ResponseInterface { ); } - public function testCanConfigureLocaleInBootstrap() + public function testCanConfigureLocaleInBootstrap(): void { $handler_url = $this->provisionDynamicHandler( <<<'PHP' diff --git a/test/blackbox/ErrorHandlingTest.php b/test/blackbox/ErrorHandlingTest.php index ea7c5af..b7faca8 100644 --- a/test/blackbox/ErrorHandlingTest.php +++ b/test/blackbox/ErrorHandlingTest.php @@ -1,11 +1,16 @@ > + */ public static function provider_error_handling(): array { return [ @@ -73,7 +78,7 @@ private function doThings(string $uhoh): ResponseInterface { } #[DataProvider('provider_error_handling')] - public function testItCapturesErrorsAndExceptions(string $handler_code) + public function testItCapturesErrorsAndExceptions(string $handler_code): void { $handler_url = self::provisionDynamicHandlerFactoryWithDefaultBootstrap($handler_code); diff --git a/test/blackbox/HttpHeadersTest.php b/test/blackbox/HttpHeadersTest.php index b4ebf60..540b925 100644 --- a/test/blackbox/HttpHeadersTest.php +++ b/test/blackbox/HttpHeadersTest.php @@ -1,5 +1,7 @@ , array>}> + */ public static function provider_headers(): array { return [ @@ -63,8 +68,12 @@ public static function provider_headers(): array ]; } + /** + * @param array $specified_headers + * @param array> $expected_headers + */ #[DataProvider('provider_headers')] - public function testItReturnsExpectedHeaders(array $specified_headers, array $expected_headers) + public function testItReturnsExpectedHeaders(array $specified_headers, array $expected_headers): void { $response = $this->guzzle->post( self::$handler_url, @@ -82,7 +91,7 @@ public function testItReturnsExpectedHeaders(array $specified_headers, array $ex $this->assertSame($expected_headers, $all_headers); } - public function testItGivesErrorOnUnsupportedUseOfDuplicateOutputHeaders() + public function testItGivesErrorOnUnsupportedUseOfDuplicateOutputHeaders(): void { // We can't support multiples for the same header because we can't reliably guess whether to pass // replace => true or replace => false into the `header()` call and it's more important that we diff --git a/test/blackbox/HttpResponseCodesTest.php b/test/blackbox/HttpResponseCodesTest.php index e042936..338b1bd 100644 --- a/test/blackbox/HttpResponseCodesTest.php +++ b/test/blackbox/HttpResponseCodesTest.php @@ -1,5 +1,7 @@ assertResponseMatches( $status_code, @@ -38,7 +40,7 @@ public function testItReturnsStatusCodeFromHandler(int $status_code) ); } - public function testItCanOptionallyUseCustomStatusCodesIfReasonPhraseProvided() + public function testItCanOptionallyUseCustomStatusCodesIfReasonPhraseProvided(): void { $handler_url = self::provisionDynamicHandlerFactoryWithDefaultBootstrap( <<<'PHP' diff --git a/test/blackbox/OutputBufferingTest.php b/test/blackbox/OutputBufferingTest.php index 7c60ed0..1699d0a 100644 --- a/test/blackbox/OutputBufferingTest.php +++ b/test/blackbox/OutputBufferingTest.php @@ -1,12 +1,14 @@ provisionDynamicHandler( <<<'PHP' @@ -44,7 +46,7 @@ public function handle(ServerRequestInterface $request): ResponseInterface ); } - public function testItReturnsErrorWithoutOutputIfAnyCodeWritesOutputDuringRequestHandling() + public function testItReturnsErrorWithoutOutputIfAnyCodeWritesOutputDuringRequestHandling(): void { $handler_url = self::provisionDynamicHandlerFactoryWithDefaultBootstrap( <<<'PHP' @@ -65,7 +67,7 @@ public function handle(ServerRequestInterface $request): ResponseInterface ); } - public function testItTreatsAsErrorIfUserLeavesOutputBuffersOpen() + public function testItTreatsAsErrorIfUserLeavesOutputBuffersOpen(): void { $handler_url = self::provisionDynamicHandlerFactoryWithDefaultBootstrap( <<<'PHP' @@ -87,7 +89,7 @@ public function handle(ServerRequestInterface $request): ResponseInterface ); } - public function testItTreatsAsErrorIfUserFlushesOutputBuffers() + public function testItTreatsAsErrorIfUserFlushesOutputBuffers(): void { $handler_url = self::provisionDynamicHandlerFactoryWithDefaultBootstrap( <<<'PHP' @@ -110,7 +112,7 @@ public function handle(ServerRequestInterface $request): ResponseInterface ); } - public function testItDoesNotTreatAsErrorIfUserHandlesOutputBufferingCorrectly() + public function testItDoesNotTreatAsErrorIfUserHandlesOutputBufferingCorrectly(): void { $handler_url = self::provisionDynamicHandlerFactoryWithDefaultBootstrap( <<<'PHP' @@ -132,7 +134,7 @@ public function handle(ServerRequestInterface $request): ResponseInterface ); } - public function testItDoesNotTreatAsErrorIfUserHandlesOutputBufferingCorrectlyWithoutRendering() + public function testItDoesNotTreatAsErrorIfUserHandlesOutputBufferingCorrectlyWithoutRendering(): void { $handler_url = self::provisionDynamicHandlerFactoryWithDefaultBootstrap( <<<'PHP' diff --git a/test/blackbox/RequestParsingTest.php b/test/blackbox/RequestParsingTest.php index f4b1d45..096c952 100644 --- a/test/blackbox/RequestParsingTest.php +++ b/test/blackbox/RequestParsingTest.php @@ -1,10 +1,15 @@ |scalar|null>, json?: mixed} + */ class RequestParsingTest extends BaseBlackboxTestCase { private static string $handler_url; @@ -32,6 +37,9 @@ public function handle(ServerRequestInterface $request): ResponseInterface ); } + /** + * @return array}}> + */ public static function provider_request_bodies(): array { return [ @@ -109,8 +117,12 @@ public static function provider_request_bodies(): array ]; } + /** + * @param TGuzzleRequestOptions $options + * @param array{method: string, body: string, parsed_body: array} $expect + */ #[DataProvider('provider_request_bodies')] - public function testItCanReceiveIncomingRequestBodiesInExpectedFormats($method, $options, $expect): void + public function testItCanReceiveIncomingRequestBodiesInExpectedFormats(string $method, array $options, array $expect): void { $response = $this->guzzle->request($method, self::$handler_url, $options); $received_payload = JSON::decodeArray($response->getBody()->getContents()); @@ -118,6 +130,9 @@ public function testItCanReceiveIncomingRequestBodiesInExpectedFormats($method, $this->assertSame($expect, $received_payload); } + /** + * @return array>, array>}> + */ public static function provider_request_headers(): array { return [ @@ -152,8 +167,12 @@ public static function provider_request_headers(): array ]; } + /** + * @param array> $send_headers + * @param array> $expect + */ #[DataProvider('provider_request_headers')] - public function testItCanReceiveIncomingHeaders($send_headers, $expect): void + public function testItCanReceiveIncomingHeaders(array $send_headers, array $expect): void { $response = $this->guzzle->get(self::$handler_url, ['headers' => [ 'User-Agent' => self::class, @@ -163,7 +182,7 @@ public function testItCanReceiveIncomingHeaders($send_headers, $expect): void $this->assertSame($expect, $received_payload['headers']); } - public function testItCanDetectIncomingUrlsWhenRewriting() + public function testItCanDetectIncomingUrlsWhenRewriting(): void { $handler_url = self::provisionDynamicHandlerFactoryWithDefaultBootstrap( <<<'PHP' diff --git a/test/blackbox/StackdriverLoggingTest.php b/test/blackbox/StackdriverLoggingTest.php index 4bc411f..8dc1c23 100644 --- a/test/blackbox/StackdriverLoggingTest.php +++ b/test/blackbox/StackdriverLoggingTest.php @@ -10,7 +10,7 @@ class StackdriverLoggingTest extends BaseBlackboxTestCase // a blackbox test we should be as explicit as we can be about the detail of the log messages that are written - // but the log messages include filenames, line numbers, and other semi-dynamic content. - public function testItLogsRequestsOnCompletionInStackdriverFormat() + public function testItLogsRequestsOnCompletionInStackdriverFormat(): void { $handler_url = self::provisionDynamicHandler( <<<'PHP' @@ -56,17 +56,23 @@ public function handle(ServerRequestInterface $request): ResponseInterface $request_log_msg = JSON::decodeArray($messages[0]); // Assert things that are dynamic and can't be exactly asserted + $this->assertIsArray($request_log_msg['httpRequest']); + $this->assertIsString($request_log_msg['httpRequest']['latency']); $this->assertMatchesRegularExpression('/^0.00\d{4}s$/', $request_log_msg['httpRequest']['latency']); unset($request_log_msg['httpRequest']['latency']); + $this->assertIsArray($request_log_msg['context']); + $this->assertIsString($request_log_msg['context']['req']); $this->assertMatchesRegularExpression('/^\w+\.\w+$/', $request_log_msg['context']['req']); unset($request_log_msg['context']['req']); + $this->assertIsString($request_log_msg['logging.googleapis.com/trace']); $this->assertMatchesRegularExpression('/^\w+\.\w+$/', $request_log_msg['logging.googleapis.com/trace']); unset($request_log_msg['logging.googleapis.com/trace']); // Currently the test handler is taking around 2.1Mb, just assert it's close to that - $this->assertSame(2.0, round($request_log_msg['context']['mem_mb'])); + $this->assertIsNumeric($request_log_msg['context']['mem_mb']); + $this->assertSame(2.0, round((float) $request_log_msg['context']['mem_mb'])); unset($request_log_msg['context']['mem_mb']); $this->assertSame( @@ -76,7 +82,7 @@ public function handle(ServerRequestInterface $request): ResponseInterface 'httpRequest' => [ 'requestMethod' => 'GET', 'requestUrl' => parse_url($handler_url, PHP_URL_PATH), - 'remoteIp' => gethostbyname(gethostname()), + 'remoteIp' => $this->getLocalIp(), 'status' => 203, 'userAgent' => 'My Test UA', // 'latency' => '0.002811s', @@ -95,7 +101,7 @@ public function handle(ServerRequestInterface $request): ResponseInterface ); } - public function testItLogsUncaughtExceptionsAndRequestInStackdriverFormat() + public function testItLogsUncaughtExceptionsAndRequestInStackdriverFormat(): void { $handler_url = self::provisionDynamicHandler( <<<'PHP' @@ -142,7 +148,10 @@ public function handle(ServerRequestInterface $request): ResponseInterface $request_log_msg = JSON::decodeArray($messages[1]); // Assert the things that vary and can't easily be asserted directly + $this->assertIsArray($error_log_msg['context']); + $this->assertIsString($error_log_msg['context']['req']); $this->assertMatchesRegularExpression('/^\w+\.\w+$/', $error_log_msg['context']['req']); + $this->assertIsArray($request_log_msg['context']); $this->assertSame( $error_log_msg['context']['req'], $request_log_msg['context']['req'], @@ -151,6 +160,8 @@ public function handle(ServerRequestInterface $request): ResponseInterface unset($error_log_msg['context']['req']); unset($request_log_msg['context']['req']); + $this->assertIsString($error_log_msg['logging.googleapis.com/trace']); + $this->assertIsString($request_log_msg['logging.googleapis.com/trace']); $this->assertMatchesRegularExpression('/^\w+\.\w+$/', $request_log_msg['logging.googleapis.com/trace']); $this->assertSame( $error_log_msg['logging.googleapis.com/trace'], @@ -160,11 +171,14 @@ public function handle(ServerRequestInterface $request): ResponseInterface unset($error_log_msg['logging.googleapis.com/trace']); unset($request_log_msg['logging.googleapis.com/trace']); + $this->assertIsArray($request_log_msg['httpRequest']); + $this->assertIsString($request_log_msg['httpRequest']['latency']); $this->assertMatchesRegularExpression('/^0.00\d{4}s$/', $request_log_msg['httpRequest']['latency']); unset($request_log_msg['httpRequest']['latency']); // Currently the test handler is taking around 2.1Mb, just assert it's close to that - $this->assertSame(2.0, round($request_log_msg['context']['mem_mb'])); + $this->assertIsNumeric($request_log_msg['context']['mem_mb']); + $this->assertSame(2.0, round((float) $request_log_msg['context']['mem_mb'])); unset($request_log_msg['context']['mem_mb']); $this->assertSame( @@ -181,7 +195,7 @@ public function handle(ServerRequestInterface $request): ResponseInterface 'httpRequest' => [ 'requestMethod' => 'POST', 'requestUrl' => parse_url($handler_url, PHP_URL_PATH), - 'remoteIp' => gethostbyname(gethostname()), + 'remoteIp' => $this->getLocalIp(), ], 'reportLocation' => [ 'filePath' => '/var/www/vendor/ingenerator/microframework/src/MicroFramework.php', @@ -226,7 +240,7 @@ public function handle(ServerRequestInterface $request): ResponseInterface 'httpRequest' => [ 'requestMethod' => 'POST', 'requestUrl' => parse_url($handler_url, PHP_URL_PATH), - 'remoteIp' => gethostbyname(gethostname()), + 'remoteIp' => $this->getLocalIp(), 'status' => 500, 'userAgent' => 'My Test UA', // 'latency' => '0.002811s', @@ -245,7 +259,7 @@ public function handle(ServerRequestInterface $request): ResponseInterface ); } - public function testItOutputsCustomAppLogsInStackdriverFormat() + public function testItOutputsCustomAppLogsInStackdriverFormat(): void { $handler_url = self::provisionDynamicHandler( <<<'PHP' @@ -295,7 +309,10 @@ public function handle(ServerRequestInterface $request): ResponseInterface $request_log_msg = JSON::decodeArray($messages[1]); // Assert the things that vary and can't easily be asserted directly + $this->assertIsArray($error_log_msg['context']); + $this->assertIsString($error_log_msg['context']['req']); $this->assertMatchesRegularExpression('/^\w+\.\w+$/', $error_log_msg['context']['req']); + $this->assertIsArray($request_log_msg['context']); $this->assertSame( $error_log_msg['context']['req'], $request_log_msg['context']['req'], @@ -304,6 +321,8 @@ public function handle(ServerRequestInterface $request): ResponseInterface unset($error_log_msg['context']['req']); unset($request_log_msg['context']['req']); + $this->assertIsString($error_log_msg['logging.googleapis.com/trace']); + $this->assertIsString($request_log_msg['logging.googleapis.com/trace']); $this->assertMatchesRegularExpression('/^\w+\.\w+$/', $request_log_msg['logging.googleapis.com/trace']); $this->assertSame( $error_log_msg['logging.googleapis.com/trace'], @@ -313,11 +332,14 @@ public function handle(ServerRequestInterface $request): ResponseInterface unset($error_log_msg['logging.googleapis.com/trace']); unset($request_log_msg['logging.googleapis.com/trace']); + $this->assertIsArray($request_log_msg['httpRequest']); + $this->assertIsString($request_log_msg['httpRequest']['latency']); $this->assertMatchesRegularExpression('/^0.00\d{4}s$/', $request_log_msg['httpRequest']['latency']); unset($request_log_msg['httpRequest']['latency']); // Currently the test handler is taking around 2.1Mb, just assert it's close to that - $this->assertSame(2.0, round($request_log_msg['context']['mem_mb'])); + $this->assertIsNumeric($request_log_msg['context']['mem_mb']); + $this->assertSame(2.0, round((float) $request_log_msg['context']['mem_mb'])); unset($request_log_msg['context']['mem_mb']); $this->assertSame( @@ -334,7 +356,7 @@ public function handle(ServerRequestInterface $request): ResponseInterface 'httpRequest' => [ 'requestMethod' => 'POST', 'requestUrl' => parse_url($handler_url, PHP_URL_PATH), - 'remoteIp' => gethostbyname(gethostname()), + 'remoteIp' => $this->getLocalIp(), ], ], // 'logging.googleapis.com/trace' => '66991537308e16.07573263', @@ -357,7 +379,7 @@ public function handle(ServerRequestInterface $request): ResponseInterface 'httpRequest' => [ 'requestMethod' => 'POST', 'requestUrl' => parse_url($handler_url, PHP_URL_PATH), - 'remoteIp' => gethostbyname(gethostname()), + 'remoteIp' => $this->getLocalIp(), 'status' => 200, 'userAgent' => 'My Test UA', // 'latency' => '0.002811s', diff --git a/test/blackbox/implementation/htdocs/index.php b/test/blackbox/implementation/htdocs/index.php index 651c4d1..80da1c5 100644 --- a/test/blackbox/implementation/htdocs/index.php +++ b/test/blackbox/implementation/htdocs/index.php @@ -12,11 +12,11 @@ require_once __DIR__.'/../vendor/autoload.php'; new MicroFramework()->execute( - logger_provider_factory: fn () => new DefaultStackdriverLoggerProvider( + logger_provider_factory: fn (): DefaultStackdriverLoggerProvider => new DefaultStackdriverLoggerProvider( service_name: 'ig-micro', version_file_path: __DIR__.'/../version.php', ), - handler_factory: fn () => new class implements RequestHandler { + handler_factory: fn (): RequestHandler => new class implements RequestHandler { public function handle(ServerRequestInterface $request): ResponseInterface { return new Response(200, body: 'Blackbox is alive'); diff --git a/test/blackbox/implementation/version.php b/test/blackbox/implementation/version.php index fb2a919..3f7b2db 100644 --- a/test/blackbox/implementation/version.php +++ b/test/blackbox/implementation/version.php @@ -1,3 +1,5 @@ assertInstanceOf(LoggerProvider::class, $this->newSubject()); } - public function testItProvidesExpectedLoggerAndRequestLogger() + public function testItProvidesExpectedLoggerAndRequestLogger(): void { $subject = $this->newSubject(); $this->assertInstanceOf(StackdriverApplicationLogger::class, $subject->getLogger()); diff --git a/test/unit/FactoryFunctionTest.php b/test/unit/FactoryFunctionTest.php index 89d8ee0..f94499d 100644 --- a/test/unit/FactoryFunctionTest.php +++ b/test/unit/FactoryFunctionTest.php @@ -3,43 +3,28 @@ namespace test\unit; use DateTimeImmutable; -use DateTimeZone; use Ingenerator\MicroFramework\FactoryFunction; -use Ingenerator\PHPUtils\DateTime\DateString; use PHPUnit\Framework\TestCase; use stdClass; use UnexpectedValueException; class FactoryFunctionTest extends TestCase { - public function testItCallsFunctionAndReturnsResult() + public function testItCallsFunctionAndReturnsResult(): void { $instance = new stdClass(); - $this->assertSame($instance, FactoryFunction::call(fn () => $instance, stdClass::class)); + $this->assertSame($instance, FactoryFunction::call(fn (): stdClass => $instance, stdClass::class)); } - public function testItOptionallyCallsFunctionWithProvidedArgs() - { - $result = FactoryFunction::call( - fn ($date, $timezone) => new DateTimeImmutable($date, $timezone), - DateTimeImmutable::class, - [ - '2024-03-01 08:23:20', - new DateTimeZone('Europe/Paris'), - ] - ); - $this->assertSame('2024-03-01T08:23:20.000000+01:00', DateString::isoMS($result)); - } - - public function testItAllowsFactoryToReturnSubclass() + public function testItAllowsFactoryToReturnSubclass(): void { $instance = new class extends DateTimeImmutable { }; - $this->assertSame($instance, FactoryFunction::call(fn () => $instance, DateTimeImmutable::class)); + $this->assertSame($instance, FactoryFunction::call(fn (): object => $instance, DateTimeImmutable::class)); } - public function testItThrowsIfReturnedValueIsNotExpectedType() + public function testItThrowsIfReturnedValueIsNotExpectedType(): void { - $fn = fn () => new stdClass(); + $fn = fn (): stdClass => new stdClass(); $this->expectException(UnexpectedValueException::class); $this->expectExceptionMessageIsOrContains('Factory for DateTimeImmutable incorrectly returned stdClass'); FactoryFunction::call($fn, DateTimeImmutable::class); diff --git a/test/unit/StackdriverRequestLoggerTest.php b/test/unit/StackdriverRequestLoggerTest.php index 3aba2dd..d25b09a 100644 --- a/test/unit/StackdriverRequestLoggerTest.php +++ b/test/unit/StackdriverRequestLoggerTest.php @@ -9,15 +9,16 @@ use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; use Psr\Log\Test\TestLogger; +use RuntimeException; class StackdriverRequestLoggerTest extends TestCase { - public function testItIsInitialisableRequestLogger() + public function testItIsInitialisableRequestLogger(): void { $this->assertInstanceOf(RequestLogger::class, $this->newSubject()); } - public function testItsLogRequestLogsAnExceptionAndReturnsOnUnknownLoggerType() + public function testItsLogRequestLogsAnExceptionAndReturnsOnUnknownLoggerType(): void { $logger = new TestLogger(); $this->newSubject()->logRequest($logger, 0); @@ -25,6 +26,9 @@ public function testItsLogRequestLogsAnExceptionAndReturnsOnUnknownLoggerType() $this->assertTrue($logger->hasErrorThatContains('Could not log request details - got a '.$logger::class)); } + /** + * @return array> + */ public static function provider_calculate_request_start(): array { return [ @@ -49,7 +53,7 @@ public function testItCalculatesRequestStartTimeFromElapsedHighResTime( int|float $hrtime_now, float $microtime_now, float $expect_start_time, - ) { + ): void { $subject = $this->stubSubjectWithHrTimeAndMicrotime($hrtime_now, $microtime_now); $logger = $this->makeLoggerSpy(); @@ -61,7 +65,7 @@ public function testItCalculatesRequestStartTimeFromElapsedHighResTime( ); } - public function testItLogsSaneValueForRequestTimeWithDefaultImplementation() + public function testItLogsSaneValueForRequestTimeWithDefaultImplementation(): void { $actual_start_microtime = microtime(true); $start_hrtime = hrtime(true); @@ -119,10 +123,16 @@ protected function getMicrotime(): float return $subject; } + /** + * @return StackdriverApplicationLogger&object{request_log_calls: array{server: ServerGlobal, request_start_time: ?float}} + */ public function makeLoggerSpy(): StackdriverApplicationLogger { return new class extends StackdriverApplicationLogger { - public readonly array $request_log_calls; + /** + * @var array{server: ServerGlobal, request_start_time: ?float} + */ + public private(set) array $request_log_calls; public function __construct() { @@ -130,6 +140,9 @@ public function __construct() public function logRequest(ServerGlobal $server = new ServerGlobal(), ?float $request_start_time = null): void { + if (isset($this->request_log_calls)) { + throw new RuntimeException('logRequest called more than once'); + } $this->request_log_calls = get_defined_vars(); } };