diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index d6a3f6f..f978d91 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -40,3 +40,24 @@ jobs: - name: Run blackbox tests run: test/run-blackbox-tests.sh + + php-cs-fixer: + runs-on: ubuntu-latest + name: PHP-CS-Fixer + + steps: + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: 8.5 + tools: composer:v2 + + - name: Checkout + uses: actions/checkout@v4 + with: + show-progress: false + + - run: composer install + + - name: PHP-CS-Fixer + run: vendor/bin/php-cs-fixer check --diff diff --git a/.gitignore b/.gitignore index d8ba2db..43945cb 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,4 @@ Thumbs.db thumbs.db /composer.lock .phpunit.cache +.php-cs-fixer.cache diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php new file mode 100644 index 0000000..98ef8c0 --- /dev/null +++ b/.php-cs-fixer.dist.php @@ -0,0 +1,34 @@ +in(__DIR__) + ->exclude([ + 'vendor', + 'test/blackbox/implementation/htdocs/dynamic', + ]) +; + +return new Config() + ->setParallelConfig(ParallelConfigFactory::detect()) + ->setRules([ + '@Symfony' => true, + 'concat_space' => false, // override Symfony + 'global_namespace_import' => [ // override Symfony + 'import_classes' => true, + 'import_constants' => true, + 'import_functions' => true, + ], + 'phpdoc_align' => false, // override Symfony + 'single_line_throw' => false, // override Symfony + 'yoda_style' => false, // override Symfony + 'phpdoc_to_comment' => [ // Keep as a phpdoc if it contains the `@var` annotation + 'ignored_tags' => ['var'], + ], + ]) + ->setFinder($finder); diff --git a/composer.json b/composer.json index ffbaace..119d5c3 100644 --- a/composer.json +++ b/composer.json @@ -5,12 +5,14 @@ "type": "library", "require": { "php": "~8.5.0", + "guzzlehttp/psr7": "^2.7 | ^3.2", "ingenerator/php-utils": "^3.0", - "guzzlehttp/psr7": "^2.7 | ^3.2" + "php-cs-fixer/shim": "^3.95" }, "require-dev": { "fig/log-test": "^1.1", "guzzlehttp/guzzle": "^7.9.1 | ^8.3", + "phpstan/phpstan": "^2.3", "phpunit/phpunit": "^13.4", "rector/rector": "2.8.4", "symfony/filesystem": "^8.1" @@ -39,5 +41,22 @@ "config": { "preferred-install": "dist", "sort-packages": true + }, + "scripts": { + "precommit": [ + "@test:unit", + "@test:integration", + "@phpstan", + "@rector:fix", + "@cs:fix" + ], + "test:unit": "vendor/bin/phpunit --testsuite unit", + "test:integration": "vendor/bin/phpunit --testsuite integration", + "test:blackbox": "test/run-blackbox-tests.sh", + "phpstan": "vendor/bin/phpstan analyse", + "rector": "vendor/bin/rector process --dry-run", + "rector:fix": "vendor/bin/rector process", + "cs": "vendor/bin/php-cs-fixer check --diff", + "cs:fix": "vendor/bin/php-cs-fixer fix" } } diff --git a/rector.php b/rector.php index d74a553..6b91a68 100644 --- a/rector.php +++ b/rector.php @@ -11,4 +11,5 @@ ->withRootFiles() ->withSkipPath(__DIR__.'/test/blackbox/implementation/htdocs/dynamic') ->withComposerBased(phpunit: true) + ->withPhpSets() ->withImportNames(); diff --git a/src/DefaultStackdriverLoggerProvider.php b/src/DefaultStackdriverLoggerProvider.php index 8f5a840..8ebb841 100644 --- a/src/DefaultStackdriverLoggerProvider.php +++ b/src/DefaultStackdriverLoggerProvider.php @@ -8,18 +8,16 @@ class DefaultStackdriverLoggerProvider implements LoggerProvider { - public function __construct( protected readonly string $service_name, protected readonly string $version_file_path, protected readonly string $log_destination = 'php://stdout', ) { - } public function getLogger(): LoggerInterface { - if ( ! StackdriverApplicationLogger::isInitialised()) { + if (!StackdriverApplicationLogger::isInitialised()) { StackdriverApplicationLogger::initialise( fn () => new StackdriverApplicationLogger( $this->log_destination, diff --git a/src/FactoryFunction.php b/src/FactoryFunction.php index 364108e..cd87ec5 100644 --- a/src/FactoryFunction.php +++ b/src/FactoryFunction.php @@ -6,9 +6,8 @@ class FactoryFunction { - /** - * Wraps a callable to ensure that it returns an instance of an expected type + * Wraps a callable to ensure that it returns an instance of an expected type. * * So for example: * @@ -20,19 +19,20 @@ class FactoryFunction * $stdclass = FactoryFunction::call(fn() => new DateTimeImmutable, stdClass::class) * * @psalm-template T + * * @psalm-param callable():T $callable * @psalm-param class-string $expect_class * @psalm-param array $arguments that will be passed to the function - * @psalm-return T * + * @psalm-return T */ public static function call(callable $factory, string $expect_class, array $arguments = []): object { $object = $factory(...$arguments); - if ( ! $object instanceof $expect_class) { + if (!$object instanceof $expect_class) { throw new UnexpectedValueException( - sprintf("Factory for %s incorrectly returned %s", $expect_class, get_debug_type($object)) + sprintf('Factory for %s incorrectly returned %s', $expect_class, get_debug_type($object)) ); } diff --git a/src/LoggerProvider.php b/src/LoggerProvider.php index 3d388a7..03298e5 100644 --- a/src/LoggerProvider.php +++ b/src/LoggerProvider.php @@ -5,7 +5,7 @@ use Psr\Log\LoggerInterface; /** - * The LoggerProvider is responsible for providing a suitable PSR Logger and a compatible RequestLogger + * The LoggerProvider is responsible for providing a suitable PSR Logger and a compatible RequestLogger. * * It should be essentially impossible for these services to produce runtime errors under any * conditions. If they could produce errors, these must be handled & ideally logged internally. @@ -15,9 +15,7 @@ interface LoggerProvider { /** - * Get a usable LoggerInterface - either by creating, or e.g. accessing from a DI container / singleton / factory etc - * - * @return LoggerInterface + * Get a usable LoggerInterface - either by creating, or e.g. accessing from a DI container / singleton / factory etc. */ public function getLogger(): LoggerInterface; diff --git a/src/MicroFramework.php b/src/MicroFramework.php index 7d0b633..ba570ea 100644 --- a/src/MicroFramework.php +++ b/src/MicroFramework.php @@ -1,18 +1,21 @@ getStatusCode(). '"', ); @@ -139,7 +140,7 @@ private function renderResponseToClient(ResponseInterface $response): void foreach ($response->getHeaders() as $header => $header_values) { if (count($header_values) > 1) { - throw new \UnexpectedValueException('Cannot specify multiple values for the '.$header.' header'); + throw new UnexpectedValueException('Cannot specify multiple values for the '.$header.' header'); } header($header.': '.array_shift($header_values), replace: true); } @@ -163,11 +164,10 @@ private function logUncaughtException(LoggerInterface $logger, Throwable $e): vo private function renderErrorResponse(): void { - if ( ! headers_sent()) { + if (!headers_sent()) { // We can't send these if they've already been sent... header('Content-Type: text/plain', response_code: 500); } echo "Unexpected fatal error\n"; } - } diff --git a/src/RequestHandler.php b/src/RequestHandler.php index d2ba545..fe53d06 100644 --- a/src/RequestHandler.php +++ b/src/RequestHandler.php @@ -6,7 +6,7 @@ use Psr\Http\Message\ServerRequestInterface; /** - * The RequestHandler is the main implementation of the function / app code + * The RequestHandler is the main implementation of the function / app code. * * As far as MicroFramework is concerned, there is only one RequestHandler class / instance - there * is no (and never will be) built-in support for routing etc. If a function needs to route / handle diff --git a/src/RequestLogger.php b/src/RequestLogger.php index 674e54d..3374277 100644 --- a/src/RequestLogger.php +++ b/src/RequestLogger.php @@ -5,7 +5,7 @@ use Psr\Log\LoggerInterface; /** - * Responsible for logging requests on completion + * Responsible for logging requests on completion. * * This allows for a custom request log decorated with the same metadata etc as any entries in * the event log. It is called by MicroFramework at the very end of request execution, after the @@ -16,8 +16,6 @@ interface RequestLogger /** * @param LoggerInterface $logger destination to log to * @param int|float $start_hr_time the high-resolution time that the PHP execution began - useful for calculating latency - * - * @return void */ public function logRequest(LoggerInterface $logger, int|float $start_hr_time): void; } diff --git a/src/StackdriverRequestLogger.php b/src/StackdriverRequestLogger.php index 6660827..190a42c 100644 --- a/src/StackdriverRequestLogger.php +++ b/src/StackdriverRequestLogger.php @@ -7,20 +7,20 @@ use Psr\Log\LoggerInterface; /** - * Logs requests using the functionality built into StackdriverApplicationLogger + * Logs requests using the functionality built into StackdriverApplicationLogger. */ class StackdriverRequestLogger implements RequestLogger { public function logRequest(LoggerInterface $logger, float|int $start_hr_time): void { - if ( ! $logger instanceof StackdriverApplicationLogger) { + if (!$logger instanceof StackdriverApplicationLogger) { // This should never happen in any normal usecase, only if there's been an error in the way the // dependencies are wired up - e.g. someone has made a LoggerProvider that provides a // StackdriverRequestLogger with some other type of LoggerInterface. Just report it as an error // but don't interrupt request processing. $e = new InvalidArgumentException( sprintf( - "Could not log request details - got a %s instead of a %s", + 'Could not log request details - got a %s instead of a %s', $logger::class, StackdriverApplicationLogger::class ) @@ -45,5 +45,4 @@ protected function getMicrotime(): float { return microtime(true); } - } diff --git a/test/blackbox/BaseBlackboxTestCase.php b/test/blackbox/BaseBlackboxTestCase.php index fa5d20a..8bccd19 100644 --- a/test/blackbox/BaseBlackboxTestCase.php +++ b/test/blackbox/BaseBlackboxTestCase.php @@ -2,13 +2,13 @@ namespace test\blackbox; -use UnexpectedValueException; use GuzzleHttp\Client; use GuzzleHttp\RequestOptions; use PHPUnit\Framework\Assert; use PHPUnit\Framework\TestCase; use Psr\Http\Message\ResponseInterface; use Symfony\Component\Filesystem\Filesystem; +use UnexpectedValueException; class BaseBlackboxTestCase extends TestCase { @@ -60,7 +60,7 @@ protected function getTestSubjectLogEntriesDuringTest(): array // Wait a moment for logs to be written - they aren't always absolutely immediate usleep(100_000); - if ( ! is_file(self::$test_subject_logs_file)) { + if (!is_file(self::$test_subject_logs_file)) { return []; } @@ -76,7 +76,7 @@ protected function getTestSubjectLogEntriesDuringTest(): array private function extractSyslogRFC3164MessageBody(string $line): string { // https://datatracker.ietf.org/doc/html/rfc3164 - if ( ! preg_match('/^<\d+>\w+\s+\d+ \d\d:\d\d:\d\d [^ ]+ \w+\[\w+\]:(.+)$/', $line, $matches)) { + if (!preg_match('/^<\d+>\w+\s+\d+ \d\d:\d\d:\d\d [^ ]+ \w+\[\w+\]:(.+)$/', $line, $matches)) { throw new UnexpectedValueException('Unexpected log line format: `'.$line.'`'); } @@ -86,7 +86,7 @@ private function extractSyslogRFC3164MessageBody(string $line): string protected function assertResponseMatches( int $expect_code, string $expect_body, - ResponseInterface $response + ResponseInterface $response, ): void { $this->assertSame( [ @@ -100,7 +100,7 @@ protected function assertResponseMatches( ); } - protected static function provisionDynamicHandlerFactoryWithDefaultBootstrap(string $handler_factory_implementation + protected static function provisionDynamicHandlerFactoryWithDefaultBootstrap(string $handler_factory_implementation, ): string { $template = <<<'PHP' assertResponseMatches( 200, @@ -12,5 +12,4 @@ public function test_test_subject_responds_from_default_handler() $this->guzzle->get('/'), ); } - } diff --git a/test/blackbox/EnvironmentConfigurationTest.php b/test/blackbox/EnvironmentConfigurationTest.php index fb635db..984d22b 100644 --- a/test/blackbox/EnvironmentConfigurationTest.php +++ b/test/blackbox/EnvironmentConfigurationTest.php @@ -4,8 +4,7 @@ class EnvironmentConfigurationTest extends BaseBlackboxTestCase { - - public function test_can_configure_custom_timezone_in_bootstrap() + public function testCanConfigureCustomTimezoneInBootstrap() { $handler_url = $this->provisionDynamicHandler( <<<'PHP' @@ -42,7 +41,7 @@ public function handle(ServerRequestInterface $request): ResponseInterface { ); } - public function test_can_configure_locale_in_bootstrap() + public function testCanConfigureLocaleInBootstrap() { $handler_url = $this->provisionDynamicHandler( <<<'PHP' @@ -78,5 +77,4 @@ public function handle(ServerRequestInterface $request): ResponseInterface { $this->guzzle->get($handler_url), ); } - } diff --git a/test/blackbox/ErrorHandlingTest.php b/test/blackbox/ErrorHandlingTest.php index 8187fea..ea7c5af 100644 --- a/test/blackbox/ErrorHandlingTest.php +++ b/test/blackbox/ErrorHandlingTest.php @@ -6,7 +6,6 @@ class ErrorHandlingTest extends BaseBlackboxTestCase { - public static function provider_error_handling(): array { return [ @@ -74,7 +73,7 @@ private function doThings(string $uhoh): ResponseInterface { } #[DataProvider('provider_error_handling')] - public function test_it_captures_errors_and_exceptions(string $handler_code) + public function testItCapturesErrorsAndExceptions(string $handler_code) { $handler_url = self::provisionDynamicHandlerFactoryWithDefaultBootstrap($handler_code); @@ -84,5 +83,4 @@ public function test_it_captures_errors_and_exceptions(string $handler_code) $this->guzzle->get($handler_url), ); } - } diff --git a/test/blackbox/HttpHeadersTest.php b/test/blackbox/HttpHeadersTest.php index b542b01..b4ebf60 100644 --- a/test/blackbox/HttpHeadersTest.php +++ b/test/blackbox/HttpHeadersTest.php @@ -2,8 +2,8 @@ namespace test\blackbox; -use PHPUnit\Framework\Attributes\DataProvider; use GuzzleHttp\RequestOptions; +use PHPUnit\Framework\Attributes\DataProvider; class HttpHeadersTest extends BaseBlackboxTestCase { @@ -13,7 +13,7 @@ public static function setUpBeforeClass(): void { parent::setUpBeforeClass(); self::$handler_url = self::provisionDynamicHandlerFactoryWithDefaultBootstrap( - <<<'PHP' + <<<'PHP_WRAP' fn (LoggerInterface $logger) => new class implements RequestHandler { public function handle(ServerRequestInterface $request): ResponseInterface { @@ -21,7 +21,7 @@ public function handle(ServerRequestInterface $request): ResponseInterface return new Response(202, headers: $body, body: 'Headers from POST'); } } - PHP, + PHP_WRAP, ); } @@ -64,7 +64,7 @@ public static function provider_headers(): array } #[DataProvider('provider_headers')] - public function test_it_returns_expected_headers(array $specified_headers, array $expected_headers) + public function testItReturnsExpectedHeaders(array $specified_headers, array $expected_headers) { $response = $this->guzzle->post( self::$handler_url, @@ -82,7 +82,7 @@ public function test_it_returns_expected_headers(array $specified_headers, array $this->assertSame($expected_headers, $all_headers); } - public function test_it_gives_error_on_unsupported_use_of_duplicate_output_headers() + public function testItGivesErrorOnUnsupportedUseOfDuplicateOutputHeaders() { // 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 @@ -99,5 +99,4 @@ public function test_it_gives_error_on_unsupported_use_of_duplicate_output_heade $this->assertResponseMatches(500, "Unexpected fatal error\n", $response); } - } diff --git a/test/blackbox/HttpResponseCodesTest.php b/test/blackbox/HttpResponseCodesTest.php index 28c2b30..e042936 100644 --- a/test/blackbox/HttpResponseCodesTest.php +++ b/test/blackbox/HttpResponseCodesTest.php @@ -29,7 +29,7 @@ public function handle(ServerRequestInterface $request): ResponseInterface #[TestWith([404])] #[TestWith([500])] #[TestWith([502])] - public function test_it_returns_status_code_from_handler(int $status_code) + public function testItReturnsStatusCodeFromHandler(int $status_code) { $this->assertResponseMatches( $status_code, @@ -38,7 +38,7 @@ public function test_it_returns_status_code_from_handler(int $status_code) ); } - public function test_it_can_optionally_use_custom_status_codes_if_reason_phrase_provided() + public function testItCanOptionallyUseCustomStatusCodesIfReasonPhraseProvided() { $handler_url = self::provisionDynamicHandlerFactoryWithDefaultBootstrap( <<<'PHP' @@ -57,5 +57,4 @@ public function handle(ServerRequestInterface $request): ResponseInterface $this->assertResponseMatches(599, '', $this->guzzle->get($handler_url)); } - } diff --git a/test/blackbox/OutputBufferingTest.php b/test/blackbox/OutputBufferingTest.php index e708d5d..7c60ed0 100644 --- a/test/blackbox/OutputBufferingTest.php +++ b/test/blackbox/OutputBufferingTest.php @@ -6,8 +6,7 @@ class OutputBufferingTest extends BaseBlackboxTestCase { - - public function test_it_handles_error_even_if_output_began_before_framework() + public function testItHandlesErrorEvenIfOutputBeganBeforeFramework() { $handler_url = $this->provisionDynamicHandler( <<<'PHP' @@ -45,7 +44,7 @@ public function handle(ServerRequestInterface $request): ResponseInterface ); } - public function test_it_returns_error_without_output_if_any_code_writes_output_during_request_handling() + public function testItReturnsErrorWithoutOutputIfAnyCodeWritesOutputDuringRequestHandling() { $handler_url = self::provisionDynamicHandlerFactoryWithDefaultBootstrap( <<<'PHP' @@ -66,7 +65,7 @@ public function handle(ServerRequestInterface $request): ResponseInterface ); } - public function test_it_treats_as_error_if_user_leaves_output_buffers_open() + public function testItTreatsAsErrorIfUserLeavesOutputBuffersOpen() { $handler_url = self::provisionDynamicHandlerFactoryWithDefaultBootstrap( <<<'PHP' @@ -88,7 +87,7 @@ public function handle(ServerRequestInterface $request): ResponseInterface ); } - public function test_it_treats_as_error_if_user_flushes_output_buffers() + public function testItTreatsAsErrorIfUserFlushesOutputBuffers() { $handler_url = self::provisionDynamicHandlerFactoryWithDefaultBootstrap( <<<'PHP' @@ -111,7 +110,7 @@ public function handle(ServerRequestInterface $request): ResponseInterface ); } - public function test_it_does_not_treat_as_error_if_user_handles_output_buffering_correctly() + public function testItDoesNotTreatAsErrorIfUserHandlesOutputBufferingCorrectly() { $handler_url = self::provisionDynamicHandlerFactoryWithDefaultBootstrap( <<<'PHP' @@ -133,7 +132,7 @@ public function handle(ServerRequestInterface $request): ResponseInterface ); } - public function test_it_does_not_treat_as_error_if_user_handles_output_buffering_correctly_without_rendering() + public function testItDoesNotTreatAsErrorIfUserHandlesOutputBufferingCorrectlyWithoutRendering() { $handler_url = self::provisionDynamicHandlerFactoryWithDefaultBootstrap( <<<'PHP' @@ -155,5 +154,4 @@ public function handle(ServerRequestInterface $request): ResponseInterface $this->guzzle->get($handler_url), ); } - } diff --git a/test/blackbox/RequestParsingTest.php b/test/blackbox/RequestParsingTest.php index 4faec82..f4b1d45 100644 --- a/test/blackbox/RequestParsingTest.php +++ b/test/blackbox/RequestParsingTest.php @@ -2,8 +2,8 @@ namespace test\blackbox; -use PHPUnit\Framework\Attributes\DataProvider; use Ingenerator\PHPUtils\StringEncoding\JSON; +use PHPUnit\Framework\Attributes\DataProvider; class RequestParsingTest extends BaseBlackboxTestCase { @@ -106,12 +106,11 @@ public static function provider_request_bodies(): array 'parsed_body' => [], ], ], - ]; } #[DataProvider('provider_request_bodies')] - public function test_it_can_receive_incoming_request_bodies_in_expected_formats($method, $options, $expect): void + public function testItCanReceiveIncomingRequestBodiesInExpectedFormats($method, $options, $expect): void { $response = $this->guzzle->request($method, self::$handler_url, $options); $received_payload = JSON::decodeArray($response->getBody()->getContents()); @@ -126,7 +125,7 @@ public static function provider_request_headers(): array [], [ 'Host' => ['test_subject'], - 'User-Agent' => [__CLASS__], + 'User-Agent' => [self::class], ], ], 'with custom headers' => [ @@ -146,7 +145,7 @@ public static function provider_request_headers(): array ], [ 'Host' => ['test_subject'], - 'User-Agent' => [__CLASS__], + 'User-Agent' => [self::class], 'X-My-Header' => ['test1, test2'], ], ], @@ -154,17 +153,17 @@ public static function provider_request_headers(): array } #[DataProvider('provider_request_headers')] - public function test_it_can_receive_incoming_headers($send_headers, $expect): void + public function testItCanReceiveIncomingHeaders($send_headers, $expect): void { $response = $this->guzzle->get(self::$handler_url, ['headers' => [ - 'User-Agent' => __CLASS__, - ...$send_headers + 'User-Agent' => self::class, + ...$send_headers, ]]); $received_payload = JSON::decodeArray($response->getBody()->getContents()); $this->assertSame($expect, $received_payload['headers']); } - public function test_it_can_detect_incoming_urls_when_rewriting() + public function testItCanDetectIncomingUrlsWhenRewriting() { $handler_url = self::provisionDynamicHandlerFactoryWithDefaultBootstrap( <<<'PHP' @@ -186,5 +185,4 @@ public function handle(ServerRequestInterface $request): ResponseInterface $this->guzzle->get($handler_url), ); } - } diff --git a/test/blackbox/StackdriverLoggingTest.php b/test/blackbox/StackdriverLoggingTest.php index 366dfde..4bc411f 100644 --- a/test/blackbox/StackdriverLoggingTest.php +++ b/test/blackbox/StackdriverLoggingTest.php @@ -6,12 +6,11 @@ class StackdriverLoggingTest extends BaseBlackboxTestCase { - // Note, these tests are necessarily verbose and fairly tightly coupled to the code structure, because I think for // 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 test_it_logs_requests_on_completion_in_stackdriver_format() + public function testItLogsRequestsOnCompletionInStackdriverFormat() { $handler_url = self::provisionDynamicHandler( <<<'PHP' @@ -90,13 +89,13 @@ public function handle(ServerRequestInterface $request): ResponseInterface 'service' => 'my-service', 'version' => 'ab28372', ], - //'logging.googleapis.com/trace' => '66991537308e16.07573263', + // 'logging.googleapis.com/trace' => '66991537308e16.07573263', ], $request_log_msg, ); } - public function test_it_logs_uncaught_exceptions_and_request_in_stackdriver_format() + public function testItLogsUncaughtExceptionsAndRequestInStackdriverFormat() { $handler_url = self::provisionDynamicHandler( <<<'PHP' @@ -186,11 +185,11 @@ public function handle(ServerRequestInterface $request): ResponseInterface ], 'reportLocation' => [ 'filePath' => '/var/www/vendor/ingenerator/microframework/src/MicroFramework.php', - 'lineNumber' => 152, + 'lineNumber' => 153, 'functionName' => 'Ingenerator\MicroFramework\MicroFramework->logUncaughtException', ], ], - //'logging.googleapis.com/trace' => '66991537308e16.07573263', + // 'logging.googleapis.com/trace' => '66991537308e16.07573263', 'exception' => [ 'class' => 'RuntimeException', 'msg' => 'I broke', @@ -198,21 +197,21 @@ public function handle(ServerRequestInterface $request): ResponseInterface 'file' => '/var/www/htdocs/dynamic/StackdriverLoggingTest_54a57cd69e4889f9c6cfdde12f4607f1461dec3e/index.php', 'line' => 17, 'trace' => <<<'TEXT' - #0 /var/www/vendor/ingenerator/microframework/src/MicroFramework.php(80): MyHandler->handle() + #0 /var/www/vendor/ingenerator/microframework/src/MicroFramework.php(82): MyHandler->handle() #1 /var/www/htdocs/dynamic/StackdriverLoggingTest_54a57cd69e4889f9c6cfdde12f4607f1461dec3e/index.php(21): Ingenerator\MicroFramework\MicroFramework->execute() #2 {main} TEXT, ], 'logging.googleapis.com/sourceLocation' => [ 'file' => '/var/www/vendor/ingenerator/microframework/src/MicroFramework.php', - 'line' => 152, + 'line' => 153, 'function' => 'Ingenerator\MicroFramework\MicroFramework->logUncaughtException', ], '@type' => 'type.googleapis.com/google.devtools.clouderrorreporting.v1beta1.ReportedErrorEvent', 'stack_trace' => <<<'TEXT' PHP Warning: RuntimeException: I broke in /var/www/htdocs/dynamic/StackdriverLoggingTest_54a57cd69e4889f9c6cfdde12f4607f1461dec3e/index.php:17 Stack trace: - #0 /var/www/vendor/ingenerator/microframework/src/MicroFramework.php(80): MyHandler->handle() + #0 /var/www/vendor/ingenerator/microframework/src/MicroFramework.php(82): MyHandler->handle() #1 /var/www/htdocs/dynamic/StackdriverLoggingTest_54a57cd69e4889f9c6cfdde12f4607f1461dec3e/index.php(21): Ingenerator\MicroFramework\MicroFramework->execute() #2 {main} TEXT, @@ -240,13 +239,13 @@ public function handle(ServerRequestInterface $request): ResponseInterface 'service' => 'my-service', 'version' => 'a-version', ], - //'logging.googleapis.com/trace' => '66991537308e16.07573263', + // 'logging.googleapis.com/trace' => '66991537308e16.07573263', ], $request_log_msg, ); } - public function test_it_outputs_custom_app_logs_in_stackdriver_format() + public function testItOutputsCustomAppLogsInStackdriverFormat() { $handler_url = self::provisionDynamicHandler( <<<'PHP' @@ -285,7 +284,7 @@ public function handle(ServerRequestInterface $request): ResponseInterface $this->assertResponseMatches( 200, - "OK", + 'OK', $this->guzzle->post($handler_url, ['headers' => ['User-Agent' => 'My Test UA']]), ); @@ -338,7 +337,7 @@ public function handle(ServerRequestInterface $request): ResponseInterface 'remoteIp' => gethostbyname(gethostname()), ], ], - //'logging.googleapis.com/trace' => '66991537308e16.07573263', + // 'logging.googleapis.com/trace' => '66991537308e16.07573263', 'logging.googleapis.com/sourceLocation' => [ 'file' => '/var/www/htdocs/dynamic/StackdriverLoggingTest_0ba32a129fbc45c0d394a95f76d7bdf405c84692/index.php', 'line' => 18, @@ -371,10 +370,9 @@ public function handle(ServerRequestInterface $request): ResponseInterface 'service' => 'my-service', 'version' => 'a-version', ], - //'logging.googleapis.com/trace' => '66991537308e16.07573263', + // 'logging.googleapis.com/trace' => '66991537308e16.07573263', ], $request_log_msg, ); } - } diff --git a/test/blackbox/implementation/htdocs/index.php b/test/blackbox/implementation/htdocs/index.php index 00be34c..651c4d1 100644 --- a/test/blackbox/implementation/htdocs/index.php +++ b/test/blackbox/implementation/htdocs/index.php @@ -9,9 +9,9 @@ $start_time = hrtime(as_number: true); -require_once(__DIR__.'/../vendor/autoload.php'); +require_once __DIR__.'/../vendor/autoload.php'; -(new MicroFramework)->execute( +new MicroFramework()->execute( logger_provider_factory: fn () => new DefaultStackdriverLoggerProvider( service_name: 'ig-micro', version_file_path: __DIR__.'/../version.php', diff --git a/test/blackbox/implementation/version.php b/test/blackbox/implementation/version.php index a671b51..fb2a919 100644 --- a/test/blackbox/implementation/version.php +++ b/test/blackbox/implementation/version.php @@ -1,2 +1,3 @@ assertInstanceOf(LoggerProvider::class, $this->newSubject()); } - public function test_it_provides_expected_logger_and_request_logger() + public function testItProvidesExpectedLoggerAndRequestLogger() { $subject = $this->newSubject(); $this->assertInstanceOf(StackdriverApplicationLogger::class, $subject->getLogger()); @@ -34,6 +34,4 @@ private function newSubject(): DefaultStackdriverLoggerProvider '/path/to/any/file', ); } - - -} \ No newline at end of file +} diff --git a/test/unit/FactoryFunctionTest.php b/test/unit/FactoryFunctionTest.php index e1f3b40..89d8ee0 100644 --- a/test/unit/FactoryFunctionTest.php +++ b/test/unit/FactoryFunctionTest.php @@ -2,8 +2,8 @@ namespace test\unit; -use DateTimeZone; use DateTimeImmutable; +use DateTimeZone; use Ingenerator\MicroFramework\FactoryFunction; use Ingenerator\PHPUtils\DateTime\DateString; use PHPUnit\Framework\TestCase; @@ -12,14 +12,13 @@ class FactoryFunctionTest extends TestCase { - - public function test_it_calls_function_and_returns_result() + public function testItCallsFunctionAndReturnsResult() { $instance = new stdClass(); $this->assertSame($instance, FactoryFunction::call(fn () => $instance, stdClass::class)); } - public function test_it_optionally_calls_function_with_provided_args() + public function testItOptionallyCallsFunctionWithProvidedArgs() { $result = FactoryFunction::call( fn ($date, $timezone) => new DateTimeImmutable($date, $timezone), @@ -32,19 +31,17 @@ public function test_it_optionally_calls_function_with_provided_args() $this->assertSame('2024-03-01T08:23:20.000000+01:00', DateString::isoMS($result)); } - public function test_it_allows_factory_to_return_subclass() + public function testItAllowsFactoryToReturnSubclass() { $instance = new class extends DateTimeImmutable { }; $this->assertSame($instance, FactoryFunction::call(fn () => $instance, DateTimeImmutable::class)); - } - public function test_it_throws_if_returned_value_is_not_expected_type() + public function testItThrowsIfReturnedValueIsNotExpectedType() { $fn = fn () => new stdClass(); $this->expectException(UnexpectedValueException::class); $this->expectExceptionMessageIsOrContains('Factory for DateTimeImmutable incorrectly returned stdClass'); FactoryFunction::call($fn, DateTimeImmutable::class); } - -} \ No newline at end of file +} diff --git a/test/unit/StackdriverRequestLoggerTest.php b/test/unit/StackdriverRequestLoggerTest.php index fb9d871..3aba2dd 100644 --- a/test/unit/StackdriverRequestLoggerTest.php +++ b/test/unit/StackdriverRequestLoggerTest.php @@ -2,22 +2,22 @@ namespace test\unit; -use PHPUnit\Framework\Attributes\DataProvider; use Ingenerator\MicroFramework\RequestLogger; use Ingenerator\MicroFramework\StackdriverRequestLogger; use Ingenerator\PHPUtils\Logging\StackdriverApplicationLogger; use Ingenerator\PHPUtils\Superglobals\ServerGlobal; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; use Psr\Log\Test\TestLogger; class StackdriverRequestLoggerTest extends TestCase { - public function test_it_is_initialisable_request_logger() + public function testItIsInitialisableRequestLogger() { $this->assertInstanceOf(RequestLogger::class, $this->newSubject()); } - public function test_its_log_request_logs_an_exception_and_returns_on_unknown_logger_type() + public function testItsLogRequestLogsAnExceptionAndReturnsOnUnknownLoggerType() { $logger = new TestLogger(); $this->newSubject()->logRequest($logger, 0); @@ -44,7 +44,7 @@ public static function provider_calculate_request_start(): array } #[DataProvider('provider_calculate_request_start')] - public function test_it_calculates_request_start_time_from_elapsed_high_res_time( + public function testItCalculatesRequestStartTimeFromElapsedHighResTime( int|float $hrtime_start, int|float $hrtime_now, float $microtime_now, @@ -61,7 +61,7 @@ public function test_it_calculates_request_start_time_from_elapsed_high_res_time ); } - public function test_it_logs_sane_value_for_request_time_with_default_implementation() + public function testItLogsSaneValueForRequestTimeWithDefaultImplementation() { $actual_start_microtime = microtime(true); $start_hrtime = hrtime(true); @@ -90,10 +90,9 @@ public function test_it_logs_sane_value_for_request_time_with_default_implementa ); } - public function stubSubjectWithHrTimeAndMicrotime( float|int $hrtime_now, - float $microtime_now + float $microtime_now, ): StackdriverRequestLogger { /* * As we don't currently have a defined mock for hrtime, and it's not possible to use a callable as a default @@ -125,7 +124,9 @@ public function makeLoggerSpy(): StackdriverApplicationLogger return new class extends StackdriverApplicationLogger { public readonly array $request_log_calls; - public function __construct() { } + public function __construct() + { + } public function logRequest(ServerGlobal $server = new ServerGlobal(), ?float $request_start_time = null): void { @@ -138,6 +139,4 @@ private function newSubject(): StackdriverRequestLogger { return new StackdriverRequestLogger(); } - - }