From e9a30c9e24e16fdfa6c47ff90b3a6a06ff30ed6e Mon Sep 17 00:00:00 2001 From: acoulton Date: Mon, 26 Oct 2026 17:30:02 +0000 Subject: [PATCH 01/16] ci: Enable PHPStan level 9 --- phpstan.dist.neon | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/phpstan.dist.neon b/phpstan.dist.neon index 6509806..848775d 100644 --- a/phpstan.dist.neon +++ b/phpstan.dist.neon @@ -1,6 +1,6 @@ parameters: treatPhpDocTypesAsCertain: false - level: 8 + level: 9 paths: - src - test From b189b52079222734ccd2edfeb0f7e2040b8db1c5 Mon Sep 17 00:00:00 2001 From: acoulton Date: Mon, 26 Oct 2026 17:56:29 +0000 Subject: [PATCH 02/16] fix: Imprecise param types in tests --- test/unit/DeploymentConfig/ConfigMapDeclarationParserTest.php | 3 ++- test/unit/Validation/ValidNumberTest.php | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/test/unit/DeploymentConfig/ConfigMapDeclarationParserTest.php b/test/unit/DeploymentConfig/ConfigMapDeclarationParserTest.php index a352b98..bb9b323 100644 --- a/test/unit/DeploymentConfig/ConfigMapDeclarationParserTest.php +++ b/test/unit/DeploymentConfig/ConfigMapDeclarationParserTest.php @@ -114,8 +114,9 @@ public static function provider_invalid_declarations(): array return array_map(fn (array $declarations): array => [$declarations], $invalid); } + /** @param array $declarations */ #[DataProvider('provider_invalid_declarations')] - public function testItThrowsIfAnyDeclarationsDoNotHaveExactlyTwoValues(mixed $declarations): void + public function testItThrowsIfAnyDeclarationsDoNotHaveExactlyTwoValues(array $declarations): void { $subject = $this->newSubject(); $this->expectException(InvalidConfigException::class); diff --git a/test/unit/Validation/ValidNumberTest.php b/test/unit/Validation/ValidNumberTest.php index 68ff30d..08f1f3b 100644 --- a/test/unit/Validation/ValidNumberTest.php +++ b/test/unit/Validation/ValidNumberTest.php @@ -28,7 +28,7 @@ final class ValidNumberTest extends TestCase #[TestWith([13, 13.5, false])] #[TestWith([13.5, 13.5, true])] #[TestWith([14, 13.5, true])] - public function testItValidatesMinimumAsGreaterOrEqual(mixed $value, mixed $min, bool $expect): void + public function testItValidatesMinimumAsGreaterOrEqual(mixed $value, int|float $min, bool $expect): void { $this->assertSame($expect, ValidNumber::minimum($value, $min)); } From 801cf87062b967f9b5d8a3e165ea59205d9a2f00 Mon Sep 17 00:00:00 2001 From: acoulton Date: Mon, 26 Oct 2026 17:55:19 +0000 Subject: [PATCH 03/16] fix: AssociativeArrayUtils::setPath should not overwrite non-array paths --- src/ArrayHelpers/AssociativeArrayUtils.php | 7 ++++- .../AssociativeArrayUtilsTest.php | 31 ++++++++++++++++--- 2 files changed, 32 insertions(+), 6 deletions(-) diff --git a/src/ArrayHelpers/AssociativeArrayUtils.php b/src/ArrayHelpers/AssociativeArrayUtils.php index c893fc0..88717f9 100644 --- a/src/ArrayHelpers/AssociativeArrayUtils.php +++ b/src/ArrayHelpers/AssociativeArrayUtils.php @@ -144,8 +144,13 @@ public static function setPath(array &$array, string|array $path, mixed $value, $key = (int) $key; } - $array[$key] ??= []; + if (isset($array[$key]) && !is_array($array[$key])) { + throw new InvalidArgumentException( + sprintf('Cannot write keys within a non-array path %s (got %s)', $key, get_debug_type($array[$key])) + ); + } + $array[$key] ??= []; $array = &$array[$key]; } diff --git a/test/unit/ArrayHelpers/AssociativeArrayUtilsTest.php b/test/unit/ArrayHelpers/AssociativeArrayUtilsTest.php index ac8e6e6..051b7ee 100644 --- a/test/unit/ArrayHelpers/AssociativeArrayUtilsTest.php +++ b/test/unit/ArrayHelpers/AssociativeArrayUtilsTest.php @@ -11,6 +11,7 @@ namespace test\unit\Ingenerator\PHPUtils\ArrayHelpers; use Ingenerator\PHPUtils\ArrayHelpers\AssociativeArrayUtils; +use InvalidArgumentException; use Iterator; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; @@ -138,15 +139,32 @@ public static function provider_set_path(): Iterator /** * @param array $expected * @param array $array + * @param list|string $path */ #[DataProvider('provider_set_path')] - public function testSetPath(array $expected, array $array, mixed ...$args): void + public function testSetPath(array $expected, array $array, string|array $path, mixed $value, string $delimiter = '.'): void { - AssociativeArrayUtils::setPath($array, ...$args); + AssociativeArrayUtils::setPath($array, $path, $value, $delimiter); $this->assertSame($expected, $array); } + #[TestWith(['foo.things'])] + #[TestWith(['bil.baz.whatever'])] + #[TestWith(['bil.baz.boo.bam'])] + public function testSetPathThrowsOnOverwritingNonArray(string $path): void + { + $array = [ + 'foo' => 'bar', + 'bil' => [ + 'baz' => 15, + ], + ]; + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Cannot write keys within a non-array path '); + AssociativeArrayUtils::setPath($array, $path, 'something'); + } + /** * @return Iterator>> */ @@ -275,13 +293,16 @@ public static function provider_merge(): Iterator ]; } - /** @param array $expected */ + /** + * @param array $expected + * @param array ...$args + */ #[DataProvider('provider_merge')] - public function testDeepMerge(array $expected, mixed ...$args): void + public function testDeepMerge(array $expected, array ...$args): void { $this->assertSame( $expected, - AssociativeArrayUtils::deepMerge(...$args) + AssociativeArrayUtils::deepMerge(...$args), ); } } From 9dcc531d229e62d988186d2b8b94bee2c36d9058 Mon Sep 17 00:00:00 2001 From: acoulton Date: Tue, 27 Oct 2026 09:49:15 +0000 Subject: [PATCH 04/16] fix: Ignore INGENERATOR_ENV from $_SERVER if not a string That can't be a valid value, so treat it as not being present at all and use our safe "production" default. Note that $_SERVER is `array` because it's possible to have vars in there that are not strings e.g. the argv array. --- src/DeploymentConfig/DeploymentConfig.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/DeploymentConfig/DeploymentConfig.php b/src/DeploymentConfig/DeploymentConfig.php index db796de..649e6e7 100644 --- a/src/DeploymentConfig/DeploymentConfig.php +++ b/src/DeploymentConfig/DeploymentConfig.php @@ -44,7 +44,7 @@ private function __construct( ?ConfigValueDecrypter $decrypter = null, ) { $env_vars ??= $_SERVER; - if (isset($env_vars['INGENERATOR_ENV'])) { + if (is_string($env_vars['INGENERATOR_ENV'] ?? null)) { $this->environment = $env_vars['INGENERATOR_ENV']; } else { $this->environment = self::PRODUCTION; From 06a94247818200c7a30f88d2c82b00a63876138e Mon Sep 17 00:00:00 2001 From: acoulton Date: Tue, 27 Oct 2026 10:15:47 +0000 Subject: [PATCH 05/16] fix: CSVWriter::write should only take scalars It's not valid to write non-scalar values to fputcsv, we don't need to validate that internally (fputcsv will generate a warning if so) but the method typehint should not claim it's supported to allow static analysis to find any invalid/unsafe values passed by the caller. --- src/CSV/CSVWriter.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/CSV/CSVWriter.php b/src/CSV/CSVWriter.php index c347c15..c754bad 100644 --- a/src/CSV/CSVWriter.php +++ b/src/CSV/CSVWriter.php @@ -67,7 +67,7 @@ public function open(mixed $file, array $options = []): void $this->options = array_merge($this->options, $options); } - /** @param array $row */ + /** @param array $row */ public function write(array $row): void { if (!$this->isResourceOpen()) { From 2b8c6d38a97f52e3eff8ea3e551c011af86e0526 Mon Sep 17 00:00:00 2001 From: acoulton Date: Tue, 27 Oct 2026 10:34:37 +0000 Subject: [PATCH 06/16] fix: Don't assume cookies are always strings It's possible in PHP to parse a cookie as an arbitrarily nested array by using a name with `foo[bar]` array syntax. --- src/Cookie/CookieWrapper.php | 39 ++++++++++++++++++++++++-- test/unit/Cookie/CookieWrapperTest.php | 31 +++++++++++++------- 2 files changed, 57 insertions(+), 13 deletions(-) diff --git a/src/Cookie/CookieWrapper.php b/src/Cookie/CookieWrapper.php index 9081c9b..bb4161e 100644 --- a/src/Cookie/CookieWrapper.php +++ b/src/Cookie/CookieWrapper.php @@ -3,6 +3,7 @@ namespace Ingenerator\PHPUtils\Cookie; use DateTimeImmutable; +use UnexpectedValueException; use function array_merge; use function headers_sent; @@ -25,7 +26,15 @@ class CookieWrapper { /** - * @var mixed[] + * Note: PHP $_COOKIE is normally array however: + * - It can contain arrays following the same syntax as form-encoded fields e.g. a cookie named + * `foo[bar]` with value `ok` will produce a $_COOKIE like ['foo' => ['bar' => 'ok']] + * - It can have any level of nested array structure + * - Nested array keys can be ints e.g. cookie `foo[5]` will produce ['foo' => [5 => 'ok']] + * + * However we only support returning string values. + * + * @var array */ protected array $cookies = []; @@ -74,7 +83,19 @@ public function set(string $name, string $value = '', array $options = []): void public function get(string $name): ?string { - return $this->cookies[$name] ?? null; + if (!isset($this->cookies[$name])) { + return null; + } + + $value = $this->cookies[$name]; + + if (is_string($value)) { + return $value; + } + + throw new UnexpectedValueException( + sprintf('Cookie named %s should have been string, got %s', $name, get_debug_type($value)) + ); } public function has(string $name): bool @@ -99,7 +120,19 @@ public function delete(string $name): void /** @param array $options */ protected function set_cookie(string $name, string $value, array $options): void { - setcookie($name, $value, $options); + $cookie_options = [ + 'expires' => is_int($options['expires'] ?? null) ? $options['expires'] : 0, + 'path' => is_string($options['path'] ?? null) ? $options['path'] : '/', + 'domain' => is_string($options['domain'] ?? null) ? $options['domain'] : '', + 'secure' => (bool) ($options['secure'] ?? false), + 'httponly' => (bool) ($options['httponly'] ?? false), + ]; + $samesite = $options['samesite'] ?? null; + if (in_array($samesite, ['Lax', 'lax', 'None', 'none', 'Strict', 'strict'], true)) { + $cookie_options['samesite'] = $samesite; + } + + setcookie($name, $value, $cookie_options); } protected function headers_sent(?string &$file = null, ?int &$line = null): bool diff --git a/test/unit/Cookie/CookieWrapperTest.php b/test/unit/Cookie/CookieWrapperTest.php index 0068a20..80c2026 100644 --- a/test/unit/Cookie/CookieWrapperTest.php +++ b/test/unit/Cookie/CookieWrapperTest.php @@ -9,6 +9,7 @@ use Ingenerator\PHPUtils\Cookie\HeadersSentException; use PHPUnit\Framework\Attributes\TestWith; use PHPUnit\Framework\TestCase; +use UnexpectedValueException; final class CookieWrapperTest extends TestCase { @@ -32,10 +33,20 @@ public function testItHasCookiesFromSuperglobal(string $name, bool $expect_has, [ 'has' => $subject->has($name), 'value' => $subject->get($name), - ] + ], ); } + public function testItThrowsOnAccessToNonStringCookie(): void + { + $_COOKIE = ['somecookie' => ['one' => 'is array ']]; + $subject = $this->newSubject(); + $this->expectExceptionObject( + new UnexpectedValueException('Cookie named somecookie should have been string, got array'), + ); + $subject->get('somecookie'); + } + public function testItHasCookiesThatHaveBeenSetDuringRequest(): void { $_COOKIE = []; @@ -49,7 +60,7 @@ public function testItHasCookiesThatHaveBeenSetDuringRequest(): void [ 'has' => $subject->has('anything'), 'value' => $subject->get('anything'), - ] + ], ); } @@ -59,7 +70,7 @@ public function testItThrowsFromSetCookieIfHeadersHaveBeenSent(): void $subject->headers_sent = ['file' => 'myfile.php', 'line' => 152]; $this->expectException(HeadersSentException::class); $this->expectExceptionMessage( - 'Cannot assign cookie foo - headers have been sent by output at myfile.php:152' + 'Cannot assign cookie foo - headers have been sent by output at myfile.php:152', ); $subject->set('foo', 'anything'); } @@ -77,7 +88,7 @@ public function testItSetsCookiesUsingProvidedOptions(): void 'domain' => 'foo.bar.com', 'secure' => false, 'httponly' => false, - ] + ], ); $this->assertSame( @@ -94,7 +105,7 @@ public function testItSetsCookiesUsingProvidedOptions(): void ], ], ], - $subject->setcookie_calls + $subject->setcookie_calls, ); } @@ -118,7 +129,7 @@ public function testItAppliesSaneDefaultsWhenSettingCookies(): void ], ], ], - $subject->setcookie_calls + $subject->setcookie_calls, ); } @@ -128,11 +139,11 @@ public function testItCanSetExpiresFromDatetimeImmutable(): void $subject->set( 'any', 'thing', - ['expires' => new DateTimeImmutable('2028-03-02 10:02:02 +01:00')] + ['expires' => new DateTimeImmutable('2028-03-02 10:02:02 +01:00')], ); $this->assertSame( 1835600522, - $subject->setcookie_calls[0]['options']['expires'] + $subject->setcookie_calls[0]['options']['expires'], ); } @@ -186,7 +197,7 @@ public function testItDeletesCookieBySettingValueEmptyAndExpiresInPast(): void ], ], ], - $subject->setcookie_calls + $subject->setcookie_calls, ); $this->assertSame( [ @@ -196,7 +207,7 @@ public function testItDeletesCookieBySettingValueEmptyAndExpiresInPast(): void [ 'has' => $subject->has('myvar'), 'value' => $subject->get('myvar'), - ] + ], ); } From b013b35dd4a2b590e8e5a45a7916f5d17f4ff70c Mon Sep 17 00:00:00 2001 From: acoulton Date: Tue, 27 Oct 2026 11:12:06 +0000 Subject: [PATCH 07/16] fix: $_SERVER values are not always strings The type of a given $_SERVER value is consistent over time (e.g. an HTTP_XXX header key will always be a string) but there are a mix of value types with different keys. Make the intent of the code clear when reading string server values, and add development time assertions to prove these. This also introduces a new thin `ServerGlobal` wrapper class, to make dependency injection clearer / simpler when writing other classes that depend on the $_SERVER global state by default. --- src/DeploymentConfig/DeploymentConfig.php | 15 ++-- src/Logging/DefaultLogMetadata.php | 23 +++--- src/Logging/StackdriverApplicationLogger.php | 36 ++++++---- src/Session/MysqlSession.php | 13 ++-- src/Superglobals/ServerGlobal.php | 36 ++++++++++ .../DeploymentConfig/DeploymentConfigTest.php | 3 +- test/unit/Logging/DefaultLogMetadataTest.php | 9 +-- .../StackdriverApplicationLoggerTest.php | 23 +++--- test/unit/Superglobals/ServerGlobalTest.php | 72 +++++++++++++++++++ 9 files changed, 175 insertions(+), 55 deletions(-) create mode 100644 src/Superglobals/ServerGlobal.php create mode 100644 test/unit/Superglobals/ServerGlobalTest.php diff --git a/src/DeploymentConfig/DeploymentConfig.php b/src/DeploymentConfig/DeploymentConfig.php index 649e6e7..8934228 100644 --- a/src/DeploymentConfig/DeploymentConfig.php +++ b/src/DeploymentConfig/DeploymentConfig.php @@ -4,6 +4,7 @@ use Ingenerator\PHPUtils\StringEncoding\InvalidJSONException; use Ingenerator\PHPUtils\StringEncoding\JSON; +use Ingenerator\PHPUtils\Superglobals\ServerGlobal; final class DeploymentConfig { @@ -17,7 +18,7 @@ final class DeploymentConfig private string $config_dir = '/etc/ingenerator/conf'; - private string $environment; + private readonly string $environment; private readonly ConfigMapDeclarationParser $map_parser; @@ -36,19 +37,11 @@ public static function instance() return $instance; } - /** - * @param array|null $env_vars - if missing will default to reading from $_SERVER - */ private function __construct( - ?array $env_vars = null, + ServerGlobal $server = new ServerGlobal(), ?ConfigValueDecrypter $decrypter = null, ) { - $env_vars ??= $_SERVER; - if (is_string($env_vars['INGENERATOR_ENV'] ?? null)) { - $this->environment = $env_vars['INGENERATOR_ENV']; - } else { - $this->environment = self::PRODUCTION; - } + $this->environment = $server->getString('INGENERATOR_ENV') ?? self::PRODUCTION; $this->map_parser = new ConfigMapDeclarationParser(); $this->value_decrypter = $decrypter ?? new ConfigValueDecrypter($this->config_dir.'/app-config-keys'); } diff --git a/src/Logging/DefaultLogMetadata.php b/src/Logging/DefaultLogMetadata.php index 22193fe..913bddc 100644 --- a/src/Logging/DefaultLogMetadata.php +++ b/src/Logging/DefaultLogMetadata.php @@ -1,7 +1,10 @@ $server the $_SERVER global - * * @return array>> */ - public static function httpContext(array $server): array + public static function httpContext(ServerGlobal $server = new ServerGlobal()): array { return [ 'context' => [ 'httpRequest' => [ - 'requestMethod' => $server['REQUEST_METHOD'] ?? null, - 'requestUrl' => $server['REQUEST_URI'] ?? null, - 'remoteIp' => $server['REMOTE_ADDR'] ?? '{na}', + 'requestMethod' => $server->getString('REQUEST_METHOD') ?? null, + 'requestUrl' => $server->getString('REQUEST_URI') ?? null, + 'remoteIp' => $server->getString('REMOTE_ADDR') ?? '{na}', ], ], ]; @@ -53,19 +54,19 @@ public static function httpContext(array $server): array /** * Basic request tracing information including a random unique request ID and google trace if any. * - * @param array $server - * * @return array{context: array{req: string}, 'logging.googleapis.com/trace': string} */ - public static function requestTrace(array $server = [], ?string $gcp_project = null): array - { + public static function requestTrace( + ServerGlobal $server = new ServerGlobal(), + ?string $gcp_project = null, + ): array { $request_id = uniqid('', true); // Attempt to parse the GCP trace ID header as per https://cloud.google.com/run/docs/logging#writing_structured_logs // Note this only works if we have a GCP project as a constructor arg // If that doesn't work then just use the request ID as the trace ID - it won't match anything // in stackdriver but will still tie the logs for the request together. - $trace_hdr_parts = explode('/', $server['HTTP_X_CLOUD_TRACE_CONTEXT'] ?? $request_id); + $trace_hdr_parts = explode('/', $server->getString('HTTP_X_CLOUD_TRACE_CONTEXT') ?? $request_id); if ($gcp_project && count($trace_hdr_parts) === 2) { $trace_id = 'projects/'.$gcp_project.'/traces/'.$trace_hdr_parts[0]; } else { diff --git a/src/Logging/StackdriverApplicationLogger.php b/src/Logging/StackdriverApplicationLogger.php index a7b7eb6..0a1f7b4 100644 --- a/src/Logging/StackdriverApplicationLogger.php +++ b/src/Logging/StackdriverApplicationLogger.php @@ -5,6 +5,7 @@ use Ingenerator\PHPUtils\ArrayHelpers\AssociativeArrayUtils; use Ingenerator\PHPUtils\Object\InitialisableSingletonTrait; use Ingenerator\PHPUtils\StringEncoding\StringSanitiser; +use Ingenerator\PHPUtils\Superglobals\ServerGlobal; use Psr\Log\AbstractLogger; use Psr\Log\LogLevel; use RuntimeException; @@ -169,7 +170,7 @@ public function log($level, string|Stringable $message, array $context = []): vo $log_entry = AssociativeArrayUtils::deepMerge( [ - 'severity' => strtoupper($level), + 'severity' => strtoupper(is_string($level) ? $level : ''), 'message' => $message, self::PROP_INGEN_TYPE => 'app', ], @@ -315,24 +316,33 @@ protected function addStackdriverErrorReportingData(array $log_entry): array $log_entry['@type'] = self::TYPE_STACKDRIVER_ERROR; // Thanks @google for these having different keys in context.reportLocation rather than using sourceLocation - $source_location = $log_entry[self::PROP_SOURCE_LOCATION]; - $log_entry['context']['reportLocation'] = [ + $source_location = $log_entry[self::PROP_SOURCE_LOCATION] ?? []; + if (!is_array($source_location)) { + $source_location = []; + } + $context = $log_entry['context'] ?? []; + if (!is_array($context)) { + $context = []; + } + $context['reportLocation'] = [ 'filePath' => $source_location['file'] ?? null, 'lineNumber' => $source_location['line'] ?? null, 'functionName' => $source_location['function'] ?? null, ]; + $log_entry['context'] = $context; // If this was logged from an exception, add the exception info in Error Reporting's required format but with // our safe trace string. $exception = $log_entry[self::PROP_EXCEPTION] ?? null; if (is_array($exception) && isset($exception['class'])) { + $as_string = static fn (mixed $value): string => is_scalar($value) ? (string) $value : ''; $log_entry['stack_trace'] = sprintf( "PHP Warning: %s: %s in %s:%s\nStack trace:\n%s", - $exception['class'], - $exception['msg'], - $exception['file'], - $exception['line'], - $exception['trace'] + $as_string($exception['class'] ?? ''), + $as_string($exception['msg'] ?? ''), + $as_string($exception['file'] ?? ''), + $as_string($exception['line'] ?? ''), + $as_string($exception['trace'] ?? '') ); } unset($log_entry[self::PROP_REPORT_STACKDRIVER_ERROR]); @@ -373,12 +383,12 @@ protected function writeLog(array $log_entry): void * Log entries have a severity set based on http_response_code, to provide a second route for detection/altering of * 4xx and 5xx responses. * - * @param array|null $server The $_SERVER array * @param float|null $request_start_time The microtime when the request started processing - usually a const defined at the very start of your PHP */ - public function logRequest(?array $server, ?float $request_start_time = null): void - { - $server = $server ?: $_SERVER; + public function logRequest( + ServerGlobal $server = new ServerGlobal(), + ?float $request_start_time = null, + ): void { $http_code = http_response_code() ?: '{na}'; $meta = $this->getMetadata(); $log_entry = AssociativeArrayUtils::deepMerge( @@ -397,7 +407,7 @@ public function logRequest(?array $server, ?float $request_start_time = null): v // shared with application log entry context 'status' => $http_code, 'userAgent' => $this->truncate( - StringSanitiser::ensurePrintableUtf8($server['HTTP_USER_AGENT'] ?? ''), + StringSanitiser::ensurePrintableUtf8($server->getString('HTTP_USER_AGENT') ?? ''), 500 ), 'latency' => $this->calculateRequestLatency($request_start_time), diff --git a/src/Session/MysqlSession.php b/src/Session/MysqlSession.php index 0a30bd3..0517c12 100644 --- a/src/Session/MysqlSession.php +++ b/src/Session/MysqlSession.php @@ -14,6 +14,7 @@ use ErrorException; use Ingenerator\PHPUtils\DateTime\DateString; use Ingenerator\PHPUtils\StringEncoding\StringSanitiser; +use Ingenerator\PHPUtils\Superglobals\ServerGlobal; use PDO; use RuntimeException; use SessionHandlerInterface; @@ -45,15 +46,19 @@ class MysqlSession implements SessionHandlerInterface, SessionUpdateTimestampHan /** * @param int $lock_timeout seconds to wait for MySQL lock */ - public function __construct(protected PDO $db, protected string $hash_salt, protected int $lock_timeout = 20) - { + public function __construct( + protected PDO $db, + protected string $hash_salt, + protected int $lock_timeout = 20, + ServerGlobal $server = new ServerGlobal(), + ) { $lifetime = \ini_get('session.gc_maxlifetime'); if (!is_numeric($lifetime)) { throw new RuntimeException('session.gc_maxlifetime must be an integer, got '.json_encode($lifetime)); } $this->session_lifetime = (int) $lifetime; - $this->client_ip = $_SERVER['REMOTE_ADDR'] ?? ''; - $this->client_user_agent = $_SERVER['HTTP_USER_AGENT'] ?? ''; + $this->client_ip = $server->getString('REMOTE_ADDR') ?? ''; + $this->client_user_agent = $server->getString('HTTP_USER_AGENT') ?? ''; } public function initialise(): void diff --git a/src/Superglobals/ServerGlobal.php b/src/Superglobals/ServerGlobal.php new file mode 100644 index 0000000..5afda3c --- /dev/null +++ b/src/Superglobals/ServerGlobal.php @@ -0,0 +1,36 @@ + + */ + private ?array $server = null; + + /** + * @param array $server + */ + public static function fake(array $server): self + { + $i = new self(); + $i->server = $server; + + return $i; + } + + public function getString(string $key): ?string + { + $server = $this->server ?? $_SERVER; + $value = $server[$key] ?? null; + // Assume that this is only called with keys that are known to be guaranteed to be string e.g. + // - REMOTE_ADDRESS + // - HTTP_XXX (multiple headers are combined to a comma-separated string, not an array + // We therefore don't need to do runtime type checks here (the strict return type will cause a TypeError + // at runtime if the user calls with one of the few values that are allowed not to be strings. + assert($value === null || is_string($value), 'Expected '.$key.' to be a string, got '.get_debug_type($value)); + + return $value; + } +} diff --git a/test/unit/DeploymentConfig/DeploymentConfigTest.php b/test/unit/DeploymentConfig/DeploymentConfigTest.php index b831ab5..804d617 100644 --- a/test/unit/DeploymentConfig/DeploymentConfigTest.php +++ b/test/unit/DeploymentConfig/DeploymentConfigTest.php @@ -10,6 +10,7 @@ use Ingenerator\PHPUtils\DeploymentConfig\InvalidConfigException; use Ingenerator\PHPUtils\DeploymentConfig\MissingConfigException; use Ingenerator\PHPUtils\Object\ObjectPropertyPopulator; +use Ingenerator\PHPUtils\Superglobals\ServerGlobal; use Iterator; use org\bovigo\vfs\vfsStream; use PHPUnit\Framework\Attributes\DataProvider; @@ -299,7 +300,7 @@ private function newSubjectWithEnv(string $env): DeploymentConfig private function newSubject(array $env_vars): DeploymentConfig { $creator = Closure::bind( - fn (ConfigValueDecrypter $d): DeploymentConfig => new DeploymentConfig($env_vars, $d), + fn (ConfigValueDecrypter $d): DeploymentConfig => new DeploymentConfig(ServerGlobal::fake($env_vars), $d), null, DeploymentConfig::class ); diff --git a/test/unit/Logging/DefaultLogMetadataTest.php b/test/unit/Logging/DefaultLogMetadataTest.php index 05f20a5..1b7f95b 100644 --- a/test/unit/Logging/DefaultLogMetadataTest.php +++ b/test/unit/Logging/DefaultLogMetadataTest.php @@ -6,6 +6,7 @@ use Ingenerator\PHPUtils\Logging\DefaultLogMetadata; use Ingenerator\PHPUtils\Logging\DeviceIdentifier; +use Ingenerator\PHPUtils\Superglobals\ServerGlobal; use Iterator; use org\bovigo\vfs\vfsStream; use PHPUnit\Framework\Attributes\DataProvider; @@ -31,7 +32,7 @@ public function testItsDeviceIdentityProvidesDeviceIdAsDeferredValue(): void #[TestWith([[], '{na}'])] public function testItsHttpContextProvidesClientIpFromServerVars(array $server, string $expect): void { - $result = DefaultLogMetadata::httpContext($server); + $result = DefaultLogMetadata::httpContext(ServerGlobal::fake($server)); $this->assertSame($expect, $result['context']['httpRequest']['remoteIp']); } @@ -41,7 +42,7 @@ public function testItsHttpContextProvidesClientIpFromServerVars(array $server, #[TestWith([[], null])] public function testItsHttpContextProvidesRequestUrlFromServerVars(array $server, ?string $expect): void { - $result = DefaultLogMetadata::httpContext($server); + $result = DefaultLogMetadata::httpContext(ServerGlobal::fake($server)); $this->assertSame($expect, $result['context']['httpRequest']['requestUrl']); } @@ -50,7 +51,7 @@ public function testItsHttpContextProvidesRequestUrlFromServerVars(array $server #[TestWith([[], null])] public function testItsHttpContextProvidesRequestMethodFromServerVars(array $server, ?string $expect): void { - $result = DefaultLogMetadata::httpContext($server); + $result = DefaultLogMetadata::httpContext(ServerGlobal::fake($server)); $this->assertSame($expect, $result['context']['httpRequest']['requestMethod']); } @@ -125,7 +126,7 @@ public function testItsRequestTracingDataAddsTraceIdWithFromHeaderAndOptionallyP ?string $project, string $expect, ): void { - $result = DefaultLogMetadata::requestTrace($server, $project); + $result = DefaultLogMetadata::requestTrace(ServerGlobal::fake($server), $project); $this->assertArrayHasKey('logging.googleapis.com/trace', $result); $this->assertSame( $expect, diff --git a/test/unit/Logging/StackdriverApplicationLoggerTest.php b/test/unit/Logging/StackdriverApplicationLoggerTest.php index bd460c3..0f9c1df 100644 --- a/test/unit/Logging/StackdriverApplicationLoggerTest.php +++ b/test/unit/Logging/StackdriverApplicationLoggerTest.php @@ -10,6 +10,7 @@ use Ingenerator\PHPUtils\Logging\LogMetadataProvider; use Ingenerator\PHPUtils\Logging\StackdriverApplicationLogger; use Ingenerator\PHPUtils\StringEncoding\JSON; +use Ingenerator\PHPUtils\Superglobals\ServerGlobal; use InvalidArgumentException; use Iterator; use org\bovigo\vfs\vfsStream; @@ -516,7 +517,7 @@ public function testItCanOptionallyReportStackdriverErrorWithoutException(): voi public function testItsRequestLoggerLogsRequestAsIngeneratorRequestLogType(): void { - $this->newSubject()->logRequest([]); + $this->newSubject()->logRequest(ServerGlobal::fake([])); $entry = $this->assertLoggedOneLine(); $this->assertSame('rqst', $entry['@ingenType']); } @@ -540,7 +541,7 @@ public function testItsRequestLoggerAssignsLoglevelBasedOnHttpResponseCode(int $ { $logger = $this->newSubject(); http_response_code($http_status); - $logger->logRequest([]); + $logger->logRequest(ServerGlobal::fake([])); $entry = $this->assertLoggedOneLine(); $this->assertSame($expect, $entry['severity'], 'Expect correct severity'); } @@ -557,7 +558,7 @@ public function testItsRequestLoggerHoistsHttpMetadataToTopLevel(): void ]; $logger = $this->newSubject(); - $logger->logRequest([]); + $logger->logRequest(ServerGlobal::fake([])); $entry = $this->assertLoggedOneLine(); $this->assertSame( $original_http_meta, @@ -571,7 +572,7 @@ public function testItsRequestLoggerHoistsHttpMetadataToTopLevel(): void #[TestWith(['logging.googleapis.com/sourceLocation'])] public function testItsRequestLoggerDoesNotLogIrrelevantProperties(string $prop): void { - $this->newSubject()->logRequest([]); + $this->newSubject()->logRequest(ServerGlobal::fake([])); $entry = $this->assertLoggedOneLine(); $this->assertArrayNotHasKey($prop, $entry); } @@ -583,7 +584,7 @@ public function testItsRequestLoggerLogsCustomMetadata(): void ]; $logger = $this->newSubject(); - $logger->logRequest([]); + $logger->logRequest(ServerGlobal::fake([])); $entry = $this->assertLoggedOneLine(); $this->assertSame(['mem_mb', 'user'], array_keys($entry['context'])); $this->assertSame('john@do.com', $entry['context']['user']); @@ -593,7 +594,7 @@ public function testItsRequestLoggerLogsHttpResponseCode(): void { http_response_code(402); $logger = $this->newSubject(); - $logger->logRequest([]); + $logger->logRequest(ServerGlobal::fake([])); $entry = $this->assertLoggedOneLine(); $this->assertSame(402, $entry['httpRequest']['status']); } @@ -609,7 +610,7 @@ public function testItsRequestLoggerLogsUserAgentFromGlobalArray(array $server, { http_response_code(402); $logger = $this->newSubject(); - $logger->logRequest($server); + $logger->logRequest(ServerGlobal::fake($server)); $entry = $this->assertLoggedOneLine(); $this->assertSame($expect, $entry['httpRequest']['userAgent']); } @@ -619,7 +620,7 @@ public function testItsRequestLoggerTruncatesLongUserAgents(): void $ua_val = 'abcdefghijklmnopqrstuvwxyz 1234567890 abcdefghijklmnopqrstuvwxyz 1234567890 abcdefghijklmnopqrstuvwxyz 1234567890 abcdefghijklmnopqrstuvwxyz 1234567890 abcdefghijklmnopqrstuvwxyz 1234567890 abcdefghijklmnopqrstuvwxyz 1234567890 abcdefghijklmnopqrstuvwxyz 1234567890 abcdefghijklmnopqrstuvwxyz 1234567890 abcdefghijklmnopqrstuvwxyz 1234567890 abcdefghijklmnopqrstuvwxyz 1234567890 abcdefghijklmnopqrstuvwxyz 1234567890 abcdefghijklmnopqrstuvwxyz 1234567890 abcdefghijklmnopqrstuvwxyz 1234567890 long ※ note the utf8 safe truncation and trimming'; $expect = 'abcdefghijklmnopqrstuvwxyz 1234567890 abcdefghijklmnopqrstuvwxyz 1234567890 abcdefghijklmnopqrstuvwxyz 1234567890 abcdefghijklmnopqrstuvwxyz 1234567890 abcdefghijklmnopqrstuvwxyz 1234567890 abcdefghijklmnopqrstuvwxyz 1234567890 abcdefghijklmnopqrstuvwxyz 1234567890 abcdefghijklmnopqrstuvwxyz 1234567890 abcdefghijklmnopqrstuvwxyz 1234567890 abcdefghijklmnopqrstuvwxyz 1234567890 abcdefghijklmnopqrstuvwxyz 1234567890 abcdefghijklmnopqrstuvwxyz 1234567890 abcdefghijklmnopqrstuvwxyz 1234567890 long…'; $logger = $this->newSubject(); - $logger->logRequest(['HTTP_USER_AGENT' => $ua_val]); + $logger->logRequest(ServerGlobal::fake(['HTTP_USER_AGENT' => $ua_val])); $entry = $this->assertLoggedOneLine(); $this->assertSame($expect, $entry['httpRequest']['userAgent']); } @@ -628,7 +629,7 @@ public function testItsRequestLoggerLogsLatencySinceStartTimeIfProvided(): void { $start = microtime(true); $logger = $this->newSubject(); - $logger->logRequest([], $start); + $logger->logRequest(ServerGlobal::fake([]), $start); $end = microtime(true); $entry = $this->assertLoggedOneLine(); $this->assertMatchesRegularExpression('/^(0\.[0-9]+)s$/', $entry['httpRequest']['latency']); @@ -639,7 +640,7 @@ public function testItsRequestLoggerLogsLatencySinceStartTimeIfProvided(): void public function testItsRequestLoggerLogsNullLatencyIfNoStartTime(): void { $logger = $this->newSubject(); - $logger->logRequest([]); + $logger->logRequest(ServerGlobal::fake([])); $entry = $this->assertLoggedOneLine(); $this->assertNull($entry['httpRequest']['latency']); } @@ -648,7 +649,7 @@ public function testItsRequestLoggerLogsPeakMemoryUsageInMb(): void { $logger = $this->newSubject(); $peak_before = memory_get_peak_usage(true); - $logger->logRequest([]); + $logger->logRequest(ServerGlobal::fake([])); $peak_after = memory_get_peak_usage(true); $entry = $this->assertLoggedOneLine(); $this->assertIsString( diff --git a/test/unit/Superglobals/ServerGlobalTest.php b/test/unit/Superglobals/ServerGlobalTest.php new file mode 100644 index 0000000..58d4d26 --- /dev/null +++ b/test/unit/Superglobals/ServerGlobalTest.php @@ -0,0 +1,72 @@ + */ + private array $old_server; + + protected function setUp(): void + { + $this->old_server = $_SERVER; + } + + protected function tearDown(): void + { + $_SERVER = $this->old_server; + } + + #[TestWith(['REMOTE_ADDR', '127.0.0.1'])] + #[TestWith(['HTTP_USER_AGENT', ''])] + public function testItReturnsStringValuesFromFake(string $key, string $expect): void + { + $subject = ServerGlobal::fake([ + 'REMOTE_ADDR' => '127.0.0.1', + 'HTTP_USER_AGENT' => '', + ]); + + $this->assertSame($expect, $subject->getString($key)); + } + + public function testItReturnsNullForAMissingFakeValue(): void + { + $subject = ServerGlobal::fake(['REMOTE_ADDR' => '127.0.0.1']); + + $this->assertNull($subject->getString('HTTP_HOST')); + } + + public function testFakeDoesNotFallBackToServerSuperglobal(): void + { + $_SERVER = ['REMOTE_ADDR' => 'global value']; + $subject = ServerGlobal::fake([]); + + $this->assertNull($subject->getString('REMOTE_ADDR')); + } + + public function testItReadsFromServerSuperglobalByDefault(): void + { + $_SERVER = ['REMOTE_ADDR' => '127.0.0.1']; + $subject = new ServerGlobal(); + + $this->assertSame('127.0.0.1', $subject->getString('REMOTE_ADDR')); + $this->assertNull($subject->getString('HTTP_HOST')); + } + + public function testByDefaultReadsLiveSuperglobal(): void + { + // Prove that the instance doesn't take a fixed copy of $_SERVER, but instead reads from the live global array. + $_SERVER = ['HTTP_HOST' => 'foo']; + $subject = new ServerGlobal(); + + $this->assertSame('foo', $subject->getString('HTTP_HOST')); + $_SERVER['HTTP_HOST'] = 'overwritten'; + $this->assertSame('overwritten', $subject->getString('HTTP_HOST')); + } +} From c8c45f965f8f0a6a7fc485d5bd17d3d3437792f9 Mon Sep 17 00:00:00 2001 From: acoulton Date: Tue, 27 Oct 2026 11:17:57 +0000 Subject: [PATCH 08/16] fix: StrictDate methods that take collection need to be covariant They should take any type of `mixed`. This looks like it might actually be a phpstan bug - the examples they give for the covariant warning make sense when the type is an actual type / interface, but `mixed` can't ever *actually* be added to a collection... --- src/Validation/StrictDate.php | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/Validation/StrictDate.php b/src/Validation/StrictDate.php index 9d175ad..4abf578 100644 --- a/src/Validation/StrictDate.php +++ b/src/Validation/StrictDate.php @@ -19,7 +19,7 @@ class StrictDate /** * Validate that value of one field is a date after the value of another. * - * @param ArrayAccess $validation + * @param ArrayAccess $validation * * @deprecated validate input before creating DateTimeImmutable objects */ @@ -39,7 +39,7 @@ public static function date_after(ArrayAccess $validation, string $from_field, s /** * Validate that value of one field is a date on or after value of another (>= ignoring time). * - * @param ArrayAccess $validation + * @param ArrayAccess $validation * * @deprecated validate input before creating DateTimeImmutable objects */ @@ -88,7 +88,11 @@ public static function iso_date(mixed $value): bool protected static function is_datetime_format(string $format, mixed $value): bool { - $dt = DateTimeImmutable::createFromFormat($format, (string) $value); + if (!is_string($value)) { + return false; + } + + $dt = DateTimeImmutable::createFromFormat($format, $value); return $dt && $dt->format($format) === $value; } From a805d33c68edc60fd925f19cd3d8e044b37d99c5 Mon Sep 17 00:00:00 2001 From: acoulton Date: Tue, 27 Oct 2026 11:22:10 +0000 Subject: [PATCH 09/16] fix: Typehint for ScopeChangingCaller::call It had the right type for the closure, but didn't carry the closure's return type back to the function. --- src/Object/ScopeChangingCaller.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/Object/ScopeChangingCaller.php b/src/Object/ScopeChangingCaller.php index c2cfe39..71faee4 100644 --- a/src/Object/ScopeChangingCaller.php +++ b/src/Object/ScopeChangingCaller.php @@ -31,6 +31,8 @@ class ScopeChangingCaller * @param class-string $class * @param Closure(TArgs):TReturn $func * @param TArgs $args,... + * + * @return TReturn */ public static function call(string $class, Closure $func, mixed ...$args): mixed { From f44076ca6e66e266ffb32e812881db990cb1c8dd Mon Sep 17 00:00:00 2001 From: acoulton Date: Tue, 27 Oct 2026 11:23:35 +0000 Subject: [PATCH 10/16] fix: Ignore over-strict phpstan warning in test It's fine if this just TypeErrors or fails if we got the type wrong (which we didn't). --- test/unit/Repository/AbstractArrayRepositoryTest.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test/unit/Repository/AbstractArrayRepositoryTest.php b/test/unit/Repository/AbstractArrayRepositoryTest.php index 070f135..82f41a9 100644 --- a/test/unit/Repository/AbstractArrayRepositoryTest.php +++ b/test/unit/Repository/AbstractArrayRepositoryTest.php @@ -72,7 +72,8 @@ public function testItProvidesBaseLayerForCountingEntitiesByGroup(array $entitie $subject = AnyArrayRepository::withList($entities); $this->assertSame( $expect, - $subject->countWith(fn (AnyEntity $e): mixed => $e->getProp1()) + /* @phpstan-ignore return.type (we know the test data has strings here) */ + $subject->countWith(fn (AnyEntity $e): string => $e->getProp1()) ); } From 338ec6fa4eafa864fa08739183bd1e184e52eb9b Mon Sep 17 00:00:00 2001 From: acoulton Date: Tue, 27 Oct 2026 11:31:27 +0000 Subject: [PATCH 11/16] fix: AbstractArrayRepository::with should take properly typed variadic Which also allows us to eliminate the old condition that the ::with had to take at least one item. --- src/Repository/AbstractArrayRepository.php | 10 +++++----- test/unit/Repository/AbstractArrayRepositoryTest.php | 6 ++++++ 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/src/Repository/AbstractArrayRepository.php b/src/Repository/AbstractArrayRepository.php index 00183d1..2364181 100644 --- a/src/Repository/AbstractArrayRepository.php +++ b/src/Repository/AbstractArrayRepository.php @@ -22,7 +22,6 @@ use function array_pop; use function call_user_func; use function count; -use function func_get_args; use function get_object_vars; use function in_array; use function is_object; @@ -57,13 +56,13 @@ protected function onConstruct(): void /** * Create a repo with the provided entities. Pass entities, or arrays of properties to stub. * - * @param TEntityData|TEntityInstance $entity ,... + * @param TEntityData|TEntityInstance $entities * * @return static */ - public static function with(array|object $entity) + public static function with(array|object ...$entities) { - return static::withList(func_get_args()); + return static::withList(array_values($entities)); } /** @@ -162,12 +161,13 @@ protected function formatSaveLog(object $entity): string * * Used to capture a snapshot of entity state at the time it's saved to allow later comparison * - * @param WeakMap $seen_objects + * @param WeakMap|null $seen_objects * * @return array */ protected function entityToArray(object $entity, ?WeakMap $seen_objects = null): array { + /** @var WeakMap $seen_objects */ $seen_objects ??= new WeakMap(); if (isset($seen_objects[$entity])) { return ['**RECURSION**']; diff --git a/test/unit/Repository/AbstractArrayRepositoryTest.php b/test/unit/Repository/AbstractArrayRepositoryTest.php index 82f41a9..3e9e2cb 100644 --- a/test/unit/Repository/AbstractArrayRepositoryTest.php +++ b/test/unit/Repository/AbstractArrayRepositoryTest.php @@ -35,6 +35,12 @@ public function testItIsInitialisableWithSingleEntity(): void $this->assertSame([$e], $subject->getEntities()); } + public function testWithInitialisesWithNoEntities(): void + { + $subject = AnyArrayRepository::with(); + $this->assertSame([], $subject->getEntities()); + } + public function testItIsInitialisableWithArrayOfPropsToStub(): void { $subject = AnyArrayRepository::with(['prop1' => 'foo']); From e7b2b939e74c0af0ccadb5204a72628860dfe42d Mon Sep 17 00:00:00 2001 From: acoulton Date: Tue, 27 Oct 2026 11:36:31 +0000 Subject: [PATCH 12/16] fix: Tighten allowed array shape for ExternalCallSiteFinder It should only be called with a valid trace. --- src/Logging/ExternalCallSiteFinder.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Logging/ExternalCallSiteFinder.php b/src/Logging/ExternalCallSiteFinder.php index bc1d2bc..1320331 100644 --- a/src/Logging/ExternalCallSiteFinder.php +++ b/src/Logging/ExternalCallSiteFinder.php @@ -49,7 +49,7 @@ class ExternalCallSiteFinder * } */ /** - * @param list> $trace + * @param list $trace * @param list $ignore_classes * * @return array @@ -95,15 +95,15 @@ public function findExternalCall(array $trace, array $ignore_classes): array $func = '{closure}'; } elseif (isset($next_call['class'])) { // This was a class method - either -> for instance scope, or :: for static - $func = $next_call['class'].$next_call['type'].$next_call['function']; + $func = $next_call['class'].($next_call['type'] ?? '{unknown type}').$next_call['function']; } else { // This was a pure (named) function $func = $next_call['function']; } return [ - 'file' => $called_from['file'], - 'line' => $called_from['line'], + 'file' => $called_from['file'] ?? '{unknown file}', + 'line' => $called_from['line'] ?? '{unknown file}', 'function' => $func, ]; } From 33a3b7de566049197faf0b0b67d1c873635e8e18 Mon Sep 17 00:00:00 2001 From: acoulton Date: Tue, 27 Oct 2026 11:44:03 +0000 Subject: [PATCH 13/16] fix: Define a generic shape for the UniqueMap class So that callers can enforce they are only putting in / out the expected types of data. --- src/ArrayHelpers/UniqueMap.php | 25 ++++++++++++++++--- .../CryptoBox/CryptoBoxKeypairSet.php | 7 +++++- test/unit/ArrayHelpers/UniqueMapTest.php | 3 +++ 3 files changed, 30 insertions(+), 5 deletions(-) diff --git a/src/ArrayHelpers/UniqueMap.php b/src/ArrayHelpers/UniqueMap.php index 82de44b..24d8a14 100644 --- a/src/ArrayHelpers/UniqueMap.php +++ b/src/ArrayHelpers/UniqueMap.php @@ -23,23 +23,33 @@ * Note that you can still explicitly access it like `$foo = $map['undefined'] ?? 'default'` if * you want to access a key that may or may not exist (just like a standard array). * - * @implements ArrayAccess - * @implements IteratorAggregate + * @template TValueType + * + * @implements ArrayAccess + * @implements IteratorAggregate */ class UniqueMap implements ArrayAccess, IteratorAggregate, Countable { /** - * @param array $items initial items to put in the map + * @param array $items initial items to put in the map */ public function __construct(private array $items = []) { } + /** + * @param string $offset + */ public function offsetExists(mixed $offset): bool { return array_key_exists($offset, $this->items); } + /** + * @param string $offset + * + * @return TValueType + */ public function offsetGet(mixed $offset): mixed { if (!is_string($offset)) { @@ -53,6 +63,10 @@ public function offsetGet(mixed $offset): mixed return $this->items[$offset]; } + /** + * @param string $offset + * @param TValueType $value + */ public function offsetSet(mixed $offset, mixed $value): void { if (!is_string($offset)) { @@ -66,12 +80,15 @@ public function offsetSet(mixed $offset, mixed $value): void $this->items[$offset] = $value; } + /** + * @param string $offset + */ public function offsetUnset(mixed $offset): void { unset($this->items[$offset]); } - /** @return ArrayIterator */ + /** @return ArrayIterator */ public function getIterator(): Traversable { return new ArrayIterator($this->items); diff --git a/src/Encryption/CryptoBox/CryptoBoxKeypairSet.php b/src/Encryption/CryptoBox/CryptoBoxKeypairSet.php index d1d8ea5..d9729e1 100644 --- a/src/Encryption/CryptoBox/CryptoBoxKeypairSet.php +++ b/src/Encryption/CryptoBox/CryptoBoxKeypairSet.php @@ -18,6 +18,9 @@ */ final class CryptoBoxKeypairSet { + /** + * @var UniqueMap + */ private UniqueMap $keys; /** @@ -43,7 +46,9 @@ public static function fromStrings( public function __construct( CryptoBoxKeypair ...$keys, ) { - $this->keys = new UniqueMap([]); + $map = new UniqueMap(); + /** @var UniqueMap $map */ + $this->keys = $map; foreach ($keys as $key) { $this->keys[$key->keypair_id] = $key; } diff --git a/test/unit/ArrayHelpers/UniqueMapTest.php b/test/unit/ArrayHelpers/UniqueMapTest.php index 2d5ecce..3b2fed1 100644 --- a/test/unit/ArrayHelpers/UniqueMapTest.php +++ b/test/unit/ArrayHelpers/UniqueMapTest.php @@ -39,8 +39,10 @@ public function testItAcceptsNewItems(): void { $new1 = new class { }; $subject = new UniqueMap(['any' => 'item']); + /* @phpstan-ignore offsetAssign.valueType (don't need to enforce collection type in this test) */ $subject['new1'] = $new1; $subject['new2'] = 'some-string'; + /* @phpstan-ignore offsetAssign.valueType (don't need to enforce collection type in this test) */ $subject['new3'] = null; $this->assertSame($new1, $subject['new1']); @@ -99,6 +101,7 @@ public function testItIsIterable(): void $subject = new UniqueMap(['any' => 'item']); $subject['new'] = 'new1'; $subject['other'] = 'new2'; + /* @phpstan-ignore offsetAssign.valueType (don't need to enforce collection type in this test) */ $subject['nully'] = null; $this->assertSame( From 0954629fe7b9c8a21a234f819fd7cf680bc13a68 Mon Sep 17 00:00:00 2001 From: acoulton Date: Tue, 27 Oct 2026 11:45:21 +0000 Subject: [PATCH 14/16] fix: Validate argument types in BasicPDOStatementStub when FETCH_COLUMN Avoid runtime failures by checking the types in the test stub. --- test/unit/Mutex/BasicPDOStatementStub.php | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/test/unit/Mutex/BasicPDOStatementStub.php b/test/unit/Mutex/BasicPDOStatementStub.php index 8dd681d..e1a8d37 100644 --- a/test/unit/Mutex/BasicPDOStatementStub.php +++ b/test/unit/Mutex/BasicPDOStatementStub.php @@ -26,7 +26,21 @@ public function fetchAll(?int $mode = null, mixed ...$fetch_argument): array return $this->result; } if ($mode === PDO::FETCH_COLUMN) { - return array_map(fn (array $row) => $row[$fetch_argument[0]], $this->result); + $column = $fetch_argument[0] ?? 0; + if (!is_int($column) && !is_string($column)) { + throw new UnexpectedValueException('Column index must be int or string'); + } + + return array_map( + static function (mixed $row) use ($column): mixed { + if (!is_array($row)) { + throw new UnexpectedValueException('Expected array row'); + } + + return $row[$column] ?? null; + }, + $this->result + ); } throw new UnexpectedValueException('Not mocked '.$mode); } From d31c88a3cbeeb4dbfb6dffe05dceeec8c7cbcdd4 Mon Sep 17 00:00:00 2001 From: acoulton Date: Tue, 27 Oct 2026 11:58:45 +0000 Subject: [PATCH 15/16] fix: DeploymentConfig->read should fail if file unreadable or invalid If we fail to read the file, or if we read it but the content after decryption is not a string, then throw an exception. --- src/DeploymentConfig/DeploymentConfig.php | 11 +++++- .../MissingConfigException.php | 10 ++++++ .../DeploymentConfig/DeploymentConfigTest.php | 34 ++++++++++++++++++- 3 files changed, 53 insertions(+), 2 deletions(-) diff --git a/src/DeploymentConfig/DeploymentConfig.php b/src/DeploymentConfig/DeploymentConfig.php index 8934228..7d037be 100644 --- a/src/DeploymentConfig/DeploymentConfig.php +++ b/src/DeploymentConfig/DeploymentConfig.php @@ -76,7 +76,16 @@ public function read(string $path): ?string $cfg_path = $this->config_dir.'/'.$path; if (file_exists($cfg_path)) { - return $this->value_decrypter->decrypt(file_get_contents($cfg_path)); + $content = file_get_contents($cfg_path); + if ($content === false) { + throw MissingConfigException::failedFileRead($path, $cfg_path); + } + $decrypted = $this->value_decrypter->decrypt($content); + if (!is_string($decrypted)) { + throw MissingConfigException::invalidType($path, $cfg_path, get_debug_type($decrypted)); + } + + return $decrypted; } throw MissingConfigException::missingFile($path, $cfg_path, $this->environment); } diff --git a/src/DeploymentConfig/MissingConfigException.php b/src/DeploymentConfig/MissingConfigException.php index ac8fbb0..bad394d 100644 --- a/src/DeploymentConfig/MissingConfigException.php +++ b/src/DeploymentConfig/MissingConfigException.php @@ -13,6 +13,16 @@ public static function missingFile(string $path, string $real_path, string $env) return new self("Config `$path` is not present in `$real_path` and is required for `$env` environment"); } + public static function failedFileRead(string $path, string $real_path): static + { + return new self("Failed to read config `$path` from `$real_path`"); + } + + public static function invalidType(string $path, string $real_path, string $got_type): static + { + return new self("Config `$path` in `$real_path` should return a string, got `$got_type`"); + } + public static function missingMapValue(string $env): static { return new self("No config map entry for `$env`, nor one for `*`"); diff --git a/test/unit/DeploymentConfig/DeploymentConfigTest.php b/test/unit/DeploymentConfig/DeploymentConfigTest.php index 804d617..23dd0e3 100644 --- a/test/unit/DeploymentConfig/DeploymentConfigTest.php +++ b/test/unit/DeploymentConfig/DeploymentConfigTest.php @@ -11,6 +11,7 @@ use Ingenerator\PHPUtils\DeploymentConfig\MissingConfigException; use Ingenerator\PHPUtils\Object\ObjectPropertyPopulator; use Ingenerator\PHPUtils\Superglobals\ServerGlobal; +use InvalidArgumentException; use Iterator; use org\bovigo\vfs\vfsStream; use PHPUnit\Framework\Attributes\DataProvider; @@ -222,12 +223,43 @@ public function testItsReadSupportsRuntimeDecryption(): void $this->assertSame('Iwasencrypted', $subject->read('secrets/integrations/via/password')); } + public function testItsReadThrowsIfDecryptedValueNotString(): void + { + $this->decrypter = new class extends ConfigValueDecrypter { + public function __construct() + { + } + + public function decrypt(mixed $value): mixed + { + if (!is_string($value)) { + throw new InvalidArgumentException('Expected string'); + } + + return json_decode($value); + } + }; + + $path = $this->givenConfigDirWithFile( + 'secrets/integrations/via/password', + '15', + ); + $subject = $this->newSubjectWithEnvAndConfigDir( + DeploymentConfig::DEV, + $path, + ); + + $this->expectException(MissingConfigException::class); + $this->expectExceptionMessage('should return a string, got `int`'); + $subject->read('secrets/integrations/via/password'); + } + public function testItsReadThrowsIfFileNotPresentOutsideStandalone(): void { $path = $this->givenEmptyConfigDir(); $subject = $this->newSubjectWithEnvAndConfigDir( DeploymentConfig::DEV, - $path + $path, ); $this->expectException(MissingConfigException::class); $subject->read('secrets/integrations/via/password'); From 9464302c02881c88b146f3da5d7d16d710b4d5f8 Mon Sep 17 00:00:00 2001 From: acoulton Date: Tue, 27 Oct 2026 12:33:14 +0000 Subject: [PATCH 16/16] fix: Harden log entry shape assumptions for StackdriverApplicationLogger Previously both the code and the tests made some assumptions about nested array structure within log entries and context providers. In some cases these wouldn't always be guaranteed to hold - tighten them. --- src/Logging/StackdriverApplicationLogger.php | 14 ++++- .../StackdriverApplicationLoggerTest.php | 57 ++++++++++++++----- 2 files changed, 54 insertions(+), 17 deletions(-) diff --git a/src/Logging/StackdriverApplicationLogger.php b/src/Logging/StackdriverApplicationLogger.php index 0a1f7b4..3cc5774 100644 --- a/src/Logging/StackdriverApplicationLogger.php +++ b/src/Logging/StackdriverApplicationLogger.php @@ -391,11 +391,19 @@ public function logRequest( ): void { $http_code = http_response_code() ?: '{na}'; $meta = $this->getMetadata(); + $meta_context = $meta['context'] ?? []; + if (!is_array($meta_context)) { + $meta_context = []; + } + $http_request_meta = $meta_context['httpRequest'] ?? []; + if (!is_array($http_request_meta)) { + $http_request_meta = []; + } $log_entry = AssociativeArrayUtils::deepMerge( [ 'severity' => strtoupper($this->getLogPriorityForHttpCode((string) $http_code)), self::PROP_INGEN_TYPE => 'rqst', - 'httpRequest' => $meta['context']['httpRequest'] ?? [], + 'httpRequest' => $http_request_meta, 'context' => [ 'mem_mb' => sprintf('%.2f', memory_get_peak_usage(true) / 1_000_000), ], @@ -415,7 +423,9 @@ public function logRequest( ] ); // No need to duplicate the httpRequest in context, we have already given it as a top-level property - unset($log_entry['context']['httpRequest']); + if (is_array($log_entry['context'])) { + unset($log_entry['context']['httpRequest']); + } $this->writeLog($log_entry); } diff --git a/test/unit/Logging/StackdriverApplicationLoggerTest.php b/test/unit/Logging/StackdriverApplicationLoggerTest.php index 0f9c1df..7b54989 100644 --- a/test/unit/Logging/StackdriverApplicationLoggerTest.php +++ b/test/unit/Logging/StackdriverApplicationLoggerTest.php @@ -38,6 +38,17 @@ use function preg_replace; use function str_replace; +/** + * @phpstan-type TJsonLogEntry array{ + * severity: int, + * message: string, + * context: array, + * "@type": string, + * "@ingenType": string, + * "logging.googleapis.com/sourceLocation": array, + * ... + * } + */ final class StackdriverApplicationLoggerTest extends TestCase { private vfsStreamDirectory $vfs; @@ -160,7 +171,7 @@ public function testItLogsWithMetadataProvidedInConstructor(): void $entry = $this->assertLoggedOneLine(); $this->assertSame( ['app' => 'mine', 'ver' => 'this'], - $entry['serviceContext'] + $entry['serviceContext'] ?? null ); } @@ -174,7 +185,7 @@ public function testItRecursivelyMergesMultipleMetadataSetsFromConstructor(): vo $entry = $this->assertLoggedOneLine(); $this->assertSame( ['app' => 'mine', 'ver' => 'other', 'microsite' => 'whatever'], - $entry['serviceContext'] + $entry['serviceContext'] ?? null ); } @@ -206,7 +217,7 @@ function () use (&$call_site, &$call_count): array { foreach ($lines as $idx => $line) { $this->assertSame( ['req' => 'ab92823232', 'call_site' => 'lazy'], - $line['lambda'], + $line['lambda'] ?? null, 'Expect correct meta line '.$idx ); } @@ -282,7 +293,7 @@ public function getMetadata(): array foreach ($lines as $line) { $this->assertSame( ['first_ok', 'third_ok', 'fifth_ok', 'seventh_ok'], - $line['sources'], + $line['sources'] ?? null, 'Should log best-effort metadata for all entries' ); $actual[] = $line['severity'].': '.$line['message']; @@ -360,7 +371,7 @@ public function testItIncludesArbitraryCustomContextUnderNamespacedKey(): void $entry = $this->assertLoggedOneLine(); $this->assertSame( ['context' => ['user' => 'her', 'page' => 'ourpage']], - $entry['custom_context'] + $entry['custom_context'] ?? null ); $this->assertSame( ['user' => 'me', 'sess' => 'sass'], @@ -377,7 +388,7 @@ public function testItPublishesExceptionStringInContextWithoutIssues(): void $entry = $this->assertLoggedOneLine(); $this->assertSame( 'Well now, this is a string', - $entry['exception'] + $entry['exception'] ?? null ); } @@ -440,7 +451,7 @@ public function testItRecursivelyFormatsExceptionChainAsStructsWithTraceExcludin { $this->newSubject()->info('Broken', ['exception' => $e]); $entry = $this->assertLoggedOneLine(); - $this->assertSame($expect, $entry['exception']); + $this->assertSame($expect, $entry['exception'] ?? null); } public function testItReportsExceptionAsStackdriverErrorByDefaultWithStackTraceInStackdriverFormat(): void @@ -481,7 +492,7 @@ public function testItReportsExceptionAsStackdriverErrorByDefaultWithStackTraceI "Stack trace:\n".self::makeExpectedSanitisedTrace($e), (string) $e ); - $this->assertSame($expect_text, $entry['stack_trace']); + $this->assertSame($expect_text, $entry['stack_trace'] ?? null); } public function testItDoesNotReportExceptionAsStackdriverErrorIfFlagOverriden(): void @@ -494,7 +505,9 @@ public function testItDoesNotReportExceptionAsStackdriverErrorIfFlagOverriden(): $entry = $this->assertLoggedOneLine(); $this->assertArrayNotHasKey('@type', $entry); $this->assertArrayNotHasKey('stack_trace', $entry); - $this->assertNull($entry['context']['reportLocation'] ?? null, 'Should not have context.reportLocation'); + $context = $entry['context'] ?? []; + $this->assertIsArray($context); + $this->assertArrayNotHasKey('reportLocation', $context, 'Should not have context.reportLocation'); } public function testItCanOptionallyReportStackdriverErrorWithoutException(): void @@ -562,7 +575,7 @@ public function testItsRequestLoggerHoistsHttpMetadataToTopLevel(): void $entry = $this->assertLoggedOneLine(); $this->assertSame( $original_http_meta, - array_intersect_key($entry['httpRequest'], $original_http_meta), + array_intersect_key($entry['httpRequest'] ?? null, $original_http_meta), 'Should include metadata in top-level httpRequest struct' ); $this->assertArrayNotHasKey('httpRequest', $entry['context'], 'Should not duplicate httpRequest meta in context'); @@ -596,6 +609,7 @@ public function testItsRequestLoggerLogsHttpResponseCode(): void $logger = $this->newSubject(); $logger->logRequest(ServerGlobal::fake([])); $entry = $this->assertLoggedOneLine(); + $this->assertIsArray($entry['httpRequest'] ?? null); $this->assertSame(402, $entry['httpRequest']['status']); } @@ -612,6 +626,7 @@ public function testItsRequestLoggerLogsUserAgentFromGlobalArray(array $server, $logger = $this->newSubject(); $logger->logRequest(ServerGlobal::fake($server)); $entry = $this->assertLoggedOneLine(); + $this->assertIsArray($entry['httpRequest'] ?? null); $this->assertSame($expect, $entry['httpRequest']['userAgent']); } @@ -622,6 +637,7 @@ public function testItsRequestLoggerTruncatesLongUserAgents(): void $logger = $this->newSubject(); $logger->logRequest(ServerGlobal::fake(['HTTP_USER_AGENT' => $ua_val])); $entry = $this->assertLoggedOneLine(); + $this->assertIsArray($entry['httpRequest'] ?? null); $this->assertSame($expect, $entry['httpRequest']['userAgent']); } @@ -632,6 +648,8 @@ public function testItsRequestLoggerLogsLatencySinceStartTimeIfProvided(): void $logger->logRequest(ServerGlobal::fake([]), $start); $end = microtime(true); $entry = $this->assertLoggedOneLine(); + $this->assertIsArray($entry['httpRequest'] ?? null); + $this->assertIsString($entry['httpRequest']['latency'] ?? null); $this->assertMatchesRegularExpression('/^(0\.[0-9]+)s$/', $entry['httpRequest']['latency']); $seconds = (float) str_replace('s', '', $entry['httpRequest']['latency']); $this->assertEqualsWithDelta($end - $start, $seconds, 0.1); @@ -642,6 +660,7 @@ public function testItsRequestLoggerLogsNullLatencyIfNoStartTime(): void $logger = $this->newSubject(); $logger->logRequest(ServerGlobal::fake([])); $entry = $this->assertLoggedOneLine(); + $this->assertIsArray($entry['httpRequest'] ?? null); $this->assertNull($entry['httpRequest']['latency']); } @@ -668,7 +687,7 @@ public function testItsRequestLoggerLogsPeakMemoryUsageInMb(): void ); } - /** @return list> */ + /** @return list */ protected function assertLoggedJSONLines(): array { if (!is_file($this->log_stream)) { @@ -683,12 +702,19 @@ protected function assertLoggedJSONLines(): array $this->assertSame('', array_pop($lines), 'Expect trailing newline after last message'); return array_map( - JSON::decodeArray(...), + function (string $l): array { + $log = JSON::decodeArray($l); + + // We write and parse this ourselves, assume that it follows the expected structure and matches our + // virtual type. + /** @var TJsonLogEntry $log */ + return $log; + }, $lines ); } - /** @return array */ + /** @return TJsonLogEntry */ protected function assertLoggedOneLine(): array { $entries = $this->assertLoggedJSONLines(); @@ -727,19 +753,20 @@ function ($trace_line): string { } /** - * @param array $entry + * @param TJsonLogEntry $entry */ protected function assertClonesSourceLocationToContextReportLocation(array $entry): void { // Oh look, Google use different keys for the same values in different places. Thanks @google $source_location = $entry[StackdriverApplicationLogger::PROP_SOURCE_LOCATION]; + $this->assertIsArray($source_location); $this->assertSame( [ 'filePath' => $source_location['file'], 'lineNumber' => $source_location['line'], 'functionName' => $source_location['function'], ], - $entry['context']['reportLocation'], + $entry['context']['reportLocation'] ?? null, 'Should copy sourceLocation to context.reportLocation' ); }