From 61cf833e1e163279d2a98b052082e54b596e3877 Mon Sep 17 00:00:00 2001 From: acoulton Date: Tue, 27 Oct 2026 12:34:13 +0000 Subject: [PATCH 01/11] ci: Bump phpstan to level 10 --- phpstan.dist.neon | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/phpstan.dist.neon b/phpstan.dist.neon index 848775d..a38ddc8 100644 --- a/phpstan.dist.neon +++ b/phpstan.dist.neon @@ -1,6 +1,6 @@ parameters: treatPhpDocTypesAsCertain: false - level: 9 + level: 10 paths: - src - test From 365908cee8b9d890d6e477131d3add4d4ae00fec Mon Sep 17 00:00:00 2001 From: acoulton Date: Tue, 27 Oct 2026 12:36:51 +0000 Subject: [PATCH 02/11] fix: Don't allow variance of the UTF8_BOM CSV const The CSVWriter isn't currently final, so theoretically a child could modify the BOM constant to a non-string. --- src/CSV/CSVWriter.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/CSV/CSVWriter.php b/src/CSV/CSVWriter.php index c754bad..c98995d 100644 --- a/src/CSV/CSVWriter.php +++ b/src/CSV/CSVWriter.php @@ -23,7 +23,7 @@ class CSVWriter { - public const UTF8_BOM = "\xEF\xBB\xBF"; + final public const UTF8_BOM = "\xEF\xBB\xBF"; /** * @var resource|null @@ -78,7 +78,7 @@ public function write(array $row): void if ($this->expect_schema === null) { if ($this->options['write_utf8_bom']) { - fwrite($this->resource, static::UTF8_BOM); + fwrite($this->resource, self::UTF8_BOM); } $this->expect_schema = $row_schema; $this->writeHeaders($this->expect_schema); From bb69bd0e5abb8059c7a1f61371156233c748482c Mon Sep 17 00:00:00 2001 From: acoulton Date: Tue, 27 Oct 2026 12:45:54 +0000 Subject: [PATCH 03/11] fix: Imprecise types in unit tests --- test/unit/ArrayHelpers/AssociativeArrayUtilsTest.php | 2 +- test/unit/Cookie/CookieWrapperTest.php | 2 +- test/unit/DateTime/Clock/RealtimeClockTest.php | 3 +++ test/unit/Logging/ExternalCallSiteFinderTest.php | 2 ++ test/unit/Logging/StackdriverApplicationLoggerTest.php | 3 ++- test/unit/Object/ObjectPropertyPopulatorTest.php | 2 +- test/unit/Session/MysqlSessionTest.php | 2 +- test/unit/Superglobals/ServerGlobalTest.php | 2 +- 8 files changed, 12 insertions(+), 6 deletions(-) diff --git a/test/unit/ArrayHelpers/AssociativeArrayUtilsTest.php b/test/unit/ArrayHelpers/AssociativeArrayUtilsTest.php index 051b7ee..85c4c0c 100644 --- a/test/unit/ArrayHelpers/AssociativeArrayUtilsTest.php +++ b/test/unit/ArrayHelpers/AssociativeArrayUtilsTest.php @@ -59,7 +59,7 @@ public static function provider_paths_to_nested(): Iterator } /** - * @param array $input + * @param array $input * @param array $expect */ #[DataProvider('provider_paths_to_nested')] diff --git a/test/unit/Cookie/CookieWrapperTest.php b/test/unit/Cookie/CookieWrapperTest.php index 80c2026..0b2ae03 100644 --- a/test/unit/Cookie/CookieWrapperTest.php +++ b/test/unit/Cookie/CookieWrapperTest.php @@ -13,7 +13,7 @@ final class CookieWrapperTest extends TestCase { - /** @var array */ + /** @var array */ private array $_old_cookie_var; private bool $ssl_available = true; diff --git a/test/unit/DateTime/Clock/RealtimeClockTest.php b/test/unit/DateTime/Clock/RealtimeClockTest.php index 40e6ab4..2e9a698 100644 --- a/test/unit/DateTime/Clock/RealtimeClockTest.php +++ b/test/unit/DateTime/Clock/RealtimeClockTest.php @@ -118,6 +118,9 @@ public static function provider_relative_times(): Iterator ]; } + /** + * @param Closure(RealtimeClock): DateTimeImmutable $test_method + */ #[DataProvider('provider_relative_times')] public function testItReturnsRelativeTimes(Closure $test_method, string $expect_result, bool $expect_zero_time): void { diff --git a/test/unit/Logging/ExternalCallSiteFinderTest.php b/test/unit/Logging/ExternalCallSiteFinderTest.php index c9f1cd7..22557e7 100644 --- a/test/unit/Logging/ExternalCallSiteFinderTest.php +++ b/test/unit/Logging/ExternalCallSiteFinderTest.php @@ -220,6 +220,8 @@ public function testItCanHandleAllPossibleCallSites(string $code): void unlink($temp); } + $this->assertIsArray($result); + $this->assertSame(['expected', 'actual'], array_keys($result)); $this->assertSame($result['expected'], $result['actual']); } diff --git a/test/unit/Logging/StackdriverApplicationLoggerTest.php b/test/unit/Logging/StackdriverApplicationLoggerTest.php index 7b54989..d2bb18c 100644 --- a/test/unit/Logging/StackdriverApplicationLoggerTest.php +++ b/test/unit/Logging/StackdriverApplicationLoggerTest.php @@ -573,9 +573,10 @@ public function testItsRequestLoggerHoistsHttpMetadataToTopLevel(): void $logger = $this->newSubject(); $logger->logRequest(ServerGlobal::fake([])); $entry = $this->assertLoggedOneLine(); + $this->assertIsArray($entry['httpRequest'] ?? null); $this->assertSame( $original_http_meta, - array_intersect_key($entry['httpRequest'] ?? null, $original_http_meta), + array_intersect_key($entry['httpRequest'], $original_http_meta), 'Should include metadata in top-level httpRequest struct' ); $this->assertArrayNotHasKey('httpRequest', $entry['context'], 'Should not duplicate httpRequest meta in context'); diff --git a/test/unit/Object/ObjectPropertyPopulatorTest.php b/test/unit/Object/ObjectPropertyPopulatorTest.php index 63931b9..4f3526e 100644 --- a/test/unit/Object/ObjectPropertyPopulatorTest.php +++ b/test/unit/Object/ObjectPropertyPopulatorTest.php @@ -59,7 +59,7 @@ class TestPopulatingClass protected mixed $something_protected; protected string $already_init = 'Foo'; - /** @return array */ + /** @return array */ public function toArray(): array { return get_object_vars($this); diff --git a/test/unit/Session/MysqlSessionTest.php b/test/unit/Session/MysqlSessionTest.php index 792b69a..452d456 100644 --- a/test/unit/Session/MysqlSessionTest.php +++ b/test/unit/Session/MysqlSessionTest.php @@ -120,7 +120,7 @@ public function testSidThatItCreatesIsValid(array $config, string $expected_patt // it would obviously be better if this ran as an integration test against an actual mysql instance - however // really here I only want to test that the validation is done against the database e.g. not short-circuited by // the pattern matching. - $pdo = $this->mockPDOToPrepareQueries(function ($query): MockObject { + $pdo = $this->mockPDOToPrepareQueries(function (string $query): MockObject { $result = $this->createMock(PDOStatement::class); if (str_starts_with($query, 'INSERT INTO `sessions`')) { diff --git a/test/unit/Superglobals/ServerGlobalTest.php b/test/unit/Superglobals/ServerGlobalTest.php index 58d4d26..455bb8b 100644 --- a/test/unit/Superglobals/ServerGlobalTest.php +++ b/test/unit/Superglobals/ServerGlobalTest.php @@ -10,7 +10,7 @@ final class ServerGlobalTest extends TestCase { - /** @var array */ + /** @var array */ private array $old_server; protected function setUp(): void From fe6008323539a24059ee1f2c99ad36b9ca937ce7 Mon Sep 17 00:00:00 2001 From: acoulton Date: Tue, 27 Oct 2026 12:52:22 +0000 Subject: [PATCH 04/11] fix: Type safety when loading sessions from db Ensure that the returned data structure has the expected format and the data is valid. --- src/Session/MysqlSession.php | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/src/Session/MysqlSession.php b/src/Session/MysqlSession.php index 0517c12..c87f971 100644 --- a/src/Session/MysqlSession.php +++ b/src/Session/MysqlSession.php @@ -35,7 +35,7 @@ class MysqlSession implements SessionHandlerInterface, SessionUpdateTimestampHan protected ?string $session_lock = null; /** - * @var string[] + * @var array */ protected array $data_cache; @@ -186,11 +186,19 @@ public function validateId($session_id): bool // it is recommended to use fetchAll so that PDO can close the DB cursor, even tho we only expect one row $rows = $query->fetchAll(PDO::FETCH_ASSOC); - if ($session_data = ($rows[0]['session_data'] ?? null)) { + if ($rows !== []) { + if (!is_array($rows[0]) || !isset($rows[0]['session_data'])) { + throw new RuntimeException('Unexpected data type returned from database'); + } + + if (!is_string($rows[0]['session_data'])) { + throw new RuntimeException('Unexpected data type returned from database'); + } + // OK, they have a session, not expired and the hash is correct // Cache the data for the read call that will immediately follow // And keep the lock as we need to hold it till the end of their request - $this->data_cache[$session_id] = $session_data; + $this->data_cache[$session_id] = $rows[0]['session_data']; return true; } From a28995478da6e9a82c085b83407a5dab1e6c23c8 Mon Sep 17 00:00:00 2001 From: acoulton Date: Tue, 27 Oct 2026 12:59:39 +0000 Subject: [PATCH 05/11] fix: Type-safety when serialising saved entities in tests AbstractArrayRepository should not make so many assumptions about the incoming data. --- src/Repository/AbstractArrayRepository.php | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/src/Repository/AbstractArrayRepository.php b/src/Repository/AbstractArrayRepository.php index 2364181..c3186e5 100644 --- a/src/Repository/AbstractArrayRepository.php +++ b/src/Repository/AbstractArrayRepository.php @@ -175,24 +175,24 @@ protected function entityToArray(object $entity, ?WeakMap $seen_objects = null): $seen_objects[$entity] = true; $all_props = Closure::bind( - fn ($e): array => get_object_vars($e), + fn (object $e): array => get_object_vars($e), null, $entity, ); - $obj_identity = (fn ($a): string => $a::class.'#'.spl_object_id($a)); + $obj_identity = (fn (object $a): string => $a::class.'#'.spl_object_id($a)); $result = []; foreach ($all_props($entity) as $key => $var) { if (!is_object($var)) { $result[$key] = $var; } elseif ($var instanceof Collection) { - $result[$key] = []; - foreach ($var as $collection_item) { - $result[$key][] = [ - $obj_identity($var) => $this->entityToArray($collection_item, $seen_objects), - ]; - } + $result[$key] = array_map( + fn (mixed $collection_item): array => [ + $obj_identity($var) => is_object($collection_item) ? $this->entityToArray($collection_item, $seen_objects) : '**NOT OBJECT**', + ], + [...$var] + ); } elseif ($var instanceof DateTimeInterface) { - $result[$key][$var::class] = $var->format(DateTime::ISO8601); + $result[$key] = [$var::class => $var->format(DateTime::ISO8601)]; } else { $result[$key] = [ $obj_identity($var) => $this->entityToArray($var, $seen_objects), From 81a62b8a0e1d6e52f1c1107864831dcefe70eec2 Mon Sep 17 00:00:00 2001 From: acoulton Date: Tue, 27 Oct 2026 13:16:01 +0000 Subject: [PATCH 06/11] fix: Type safety in ObjectPropertyRipper --- src/Object/ObjectPropertyRipper.php | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/Object/ObjectPropertyRipper.php b/src/Object/ObjectPropertyRipper.php index d170709..e123688 100644 --- a/src/Object/ObjectPropertyRipper.php +++ b/src/Object/ObjectPropertyRipper.php @@ -38,7 +38,7 @@ public static function rip(object $object, array $properties): array $class = $object::class; $ripper = static::getRipper($class); - return $ripper($object, $properties); + return $ripper($object, array_values($properties)); } /** @@ -59,6 +59,10 @@ public static function ripAll(object $object): array fn (): array => get_object_vars($object), $object, ))(); + // Currently phpstan doesn't support typing a method to take a callable with arbitrary arguments so + // it's not possible to tell it that the ::bindScopedClosure return will be the return of the closure. + // See https://github.com/phpstan/phpstan/issues/8214 + /** @var array $props */ // Safety check - the method above is efficient but can't return private props from parent classes // And actually, turning complex classes like that into arrays is probelematic anyway because there's @@ -87,13 +91,16 @@ public static function ripOne(object $object, string $property): mixed * properties. * * @param class-string $class + * + * @return Closure(object, list): array */ protected static function getRipper(string $class): Closure { static::$rippers[$class] ??= self::bindScopedClosure( - function ($object, $properties): array { + function (object $object, array $properties): array { $values = []; foreach ($properties as $property) { + assert(is_string($property), 'Should have been called with string property names'); $values[$property] = $object->$property; } From 8d4db201f889d41f4c940c55b09549ff8a4e8e56 Mon Sep 17 00:00:00 2001 From: acoulton Date: Tue, 27 Oct 2026 13:19:09 +0000 Subject: [PATCH 07/11] fix: Type safety in DbBackedMutexWrapper Only count the lock as having been successful if we get an explicit `1` or `'1'` result. Previously we assumed it would always be one of these, but theoretically in an error condition we could get a value that can't properly cast to int which would have caused an error. --- src/Mutex/DbBackedMutexWrapper.php | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/Mutex/DbBackedMutexWrapper.php b/src/Mutex/DbBackedMutexWrapper.php index f248657..762dc12 100644 --- a/src/Mutex/DbBackedMutexWrapper.php +++ b/src/Mutex/DbBackedMutexWrapper.php @@ -30,10 +30,13 @@ protected function getLock(string $name, int $timeout_seconds): void $query = $this->runQuery("SELECT GET_LOCK($name_param, $timeout_seconds)"); $result = $query->fetchAll(PDO::FETCH_COLUMN, 0); - // Need to explicitly cast the result to an int for comparison as PDO value types vary between 8.0 and 8.1+ - // And we should keep this cast even when we drop 8.0, because the PDO int/string mode is actually - // configurable with a PDO attribute so could vary at runtime too. - if (1 !== (int) $result[0]) { + // Need to explicitly check as int and as string because the PDO int/string mode varies depending on the + // runtime configurable PDO attribute. + $got_lock = match ($result[0]) { + 1, '1' => true, + default => false, + }; + if (!$got_lock) { throw new MutexTimedOutException($name, $timeout_seconds, $result); } } From d33e391282104b5de05b66e8ef59fb1ca158bcb9 Mon Sep 17 00:00:00 2001 From: acoulton Date: Tue, 27 Oct 2026 13:28:10 +0000 Subject: [PATCH 08/11] test: Tag up array types after AssociativeArrayUtils::deepMerge AssociativeArrayUtils::deepMerge will in practice return: * array if all inputs were array * array if *any* input had numeric keys There is no easy way to report that to PHPStan (conditional return types don't cater for variadics) so we need to just tag the resultant variable. --- src/Logging/StackdriverApplicationLogger.php | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/Logging/StackdriverApplicationLogger.php b/src/Logging/StackdriverApplicationLogger.php index 3cc5774..82ae50c 100644 --- a/src/Logging/StackdriverApplicationLogger.php +++ b/src/Logging/StackdriverApplicationLogger.php @@ -177,6 +177,9 @@ public function log($level, string|Stringable $message, array $context = []): vo $this->getMetadata(), $context_overrides ); + // In context, we know that the ::deepMerge above returns an array since that is the type of all + // the inputs. + /** @var array $log_entry */ // Find source location here rather than in the initial array merge to avoid having to make this backtrace // call if it's already been provided / overridden by the caller. @@ -223,6 +226,9 @@ protected function getMetadata(): array $source = $source(); } $metadata = AssociativeArrayUtils::deepMerge($metadata, $source); + // In context, we know that the ::deepMerge above returns an array since that is the type of all + // the inputs. + /** @var array $metadata */ } catch (Throwable $e) { // @todo: include name/type of metadata source here (need a string helper to get the type name?) $meta_errors[] = ['idx' => $index, 'throwable' => $e]; @@ -427,6 +433,9 @@ public function logRequest( unset($log_entry['context']['httpRequest']); } + // In context, we know that the ::deepMerge above returns an array since that is the type of all + // the inputs. + /** @var array $log_entry */ $this->writeLog($log_entry); } From 686c5fa42504dc5206c258bc2bb7f3e6ededf65e Mon Sep 17 00:00:00 2001 From: acoulton Date: Tue, 27 Oct 2026 13:29:57 +0000 Subject: [PATCH 09/11] fix: Finalise `DeviceIdentifier` class There were a couple of phpstan errors coming up related to the class having potentially conflicting types in a child. In practice this never needs to be extended so we can safely just finalise it which solves all those issues. --- src/Logging/DeviceIdentifier.php | 34 ++++++++++++++-------- test/unit/Logging/DeviceIdentifierTest.php | 20 +++---------- 2 files changed, 26 insertions(+), 28 deletions(-) diff --git a/src/Logging/DeviceIdentifier.php b/src/Logging/DeviceIdentifier.php index 014a114..38859c2 100644 --- a/src/Logging/DeviceIdentifier.php +++ b/src/Logging/DeviceIdentifier.php @@ -1,5 +1,7 @@ $id])); + self::$instance = new DeviceIdentifier(new ArrayCookieWrapperStub(['did' => $id])); } /** @@ -49,12 +59,12 @@ public static function initAndEnsureCookieSet(bool $ssl_available, bool $is_cli // Note that as it's not really appropriate to inject the `is_cli` arg to `::get()`, and we can't stub // PHP_SAPI for testing, that method will still return `-unset-` if it is called before // ::initAndEnsureCookieSet() - static::forceGlobalTestValue(static::CLI_ID); + self::forceGlobalTestValue(self::CLI_ID); } else { - static::$instance = new DeviceIdentifier(new CookieWrapper($ssl_available)); + self::$instance = new DeviceIdentifier(new CookieWrapper($ssl_available)); } - assert(static::$instance instanceof DeviceIdentifier, 'Should have been assigned by above or by ::forceGlobalTestValue'); - static::$instance->init(); + assert(self::$instance instanceof DeviceIdentifier, 'Should have been assigned by above or by ::forceGlobalTestValue'); + self::$instance->init(); } /** @@ -66,7 +76,7 @@ public static function initAndEnsureCookieSet(bool $ssl_available, bool $is_cli */ public static function get(): string { - $i = static::$instance ?: new DeviceIdentifier(new CookieWrapper()); + $i = self::$instance ?? new DeviceIdentifier(new CookieWrapper()); return $i->getValue(); } @@ -75,9 +85,9 @@ public static function get(): string public const COOKIE_LIFETIME = 'P5Y'; public const VALID_REGEX = '/^[a-zA-Z0-9\-_=]{22}$/'; - protected ?string $id = null; + private ?string $id = null; - protected function __construct(protected CookieWrapper $cookies) + private function __construct(private readonly CookieWrapper $cookies) { } @@ -117,10 +127,10 @@ public function init(): void } } - protected function assignNewIdAndSetCookies(): void + private function assignNewIdAndSetCookies(): void { $this->id = Base64Url::encode(random_bytes(16)); - $expire = (new DateTimeImmutable())->add(new DateInterval(static::COOKIE_LIFETIME)); + $expire = (new DateTimeImmutable())->add(new DateInterval(self::COOKIE_LIFETIME)); // The cookies are set with httponly=false to allow access from JS (though generally it is // preferred to render it server-side and inject into javascript through data attributes / diff --git a/test/unit/Logging/DeviceIdentifierTest.php b/test/unit/Logging/DeviceIdentifierTest.php index ebf80fd..aa5ca33 100644 --- a/test/unit/Logging/DeviceIdentifierTest.php +++ b/test/unit/Logging/DeviceIdentifierTest.php @@ -145,11 +145,7 @@ public function testItsGetterReturnsInitialisedValueIfInitialised(): void public function testItsStaticInitCreatesInstanceAndInitialises(): void { - ScopeChangingCaller::call( - DeviceIdentifier::class, - /** @phpstan-ignore staticProperty.protected (intentional modification of state to reset singleton) */ - function (): void { DeviceIdentifier::$instance = null; } - ); + DeviceIdentifier::resetInstance(); $old_cookie = $_COOKIE; try { @@ -172,11 +168,7 @@ function (): void { DeviceIdentifier::$instance = null; } public function testItsStaticInitCreatesInstanceAndInitialisesWithFixedIdInCli(): void { - ScopeChangingCaller::call( - DeviceIdentifier::class, - /** @phpstan-ignore staticProperty.protected (intentional modification of state to reset singleton) */ - function (): void { DeviceIdentifier::$instance = null; } - ); + DeviceIdentifier::resetInstance(); DeviceIdentifier::initAndEnsureCookieSet(true); // Fall back to default arg $this->assertSame(DeviceIdentifier::CLI_ID, DeviceIdentifier::get()); @@ -185,11 +177,7 @@ function (): void { DeviceIdentifier::$instance = null; } public function testItsStaticGetCanReadFromCookiesEvenIfNotInitialised(): void { - ScopeChangingCaller::call( - DeviceIdentifier::class, - /** @phpstan-ignore staticProperty.protected (intentional modification of state to reset singleton) */ - function (): void { DeviceIdentifier::$instance = null; } - ); + DeviceIdentifier::resetInstance(); $old_cookie = $_COOKIE; try { @@ -221,7 +209,7 @@ protected function newSubject(): DeviceIdentifier { return ScopeChangingCaller::call( DeviceIdentifier::class, - /** @phpstan-ignore new.protectedConstructor (intentional modification of state to reset singleton) */ + /** @phpstan-ignore new.privateConstructor (intentional modification of state to reset singleton) */ fn (CookieWrapper $cookies): DeviceIdentifier => new DeviceIdentifier($cookies), $this->cookies ); From a605367686665a4ea8cc4ddb83e17abbdc35fcd5 Mon Sep 17 00:00:00 2001 From: acoulton Date: Tue, 27 Oct 2026 13:36:54 +0000 Subject: [PATCH 10/11] fix: Enforce type-safety of static DeploymentConfig instance --- src/DeploymentConfig/DeploymentConfig.php | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/src/DeploymentConfig/DeploymentConfig.php b/src/DeploymentConfig/DeploymentConfig.php index 7d037be..eb381ef 100644 --- a/src/DeploymentConfig/DeploymentConfig.php +++ b/src/DeploymentConfig/DeploymentConfig.php @@ -24,17 +24,13 @@ final class DeploymentConfig private readonly ConfigValueDecrypter $value_decrypter; - /** - * @return static - */ - public static function instance() + private static DeploymentConfig $instance; + + public static function instance(): self { - static $instance; - if (!$instance) { - $instance = new self(); - } + self::$instance ??= new self(); - return $instance; + return self::$instance; } private function __construct( From 9b36fc752c3a8c5402af329a4963099242636fcf Mon Sep 17 00:00:00 2001 From: acoulton Date: Tue, 27 Oct 2026 13:39:56 +0000 Subject: [PATCH 11/11] fix: Enforce type-safety of parts in DateIntervalUtils::toHuman --- src/DateTime/DateIntervalUtils.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/DateTime/DateIntervalUtils.php b/src/DateTime/DateIntervalUtils.php index b428712..e458988 100644 --- a/src/DateTime/DateIntervalUtils.php +++ b/src/DateTime/DateIntervalUtils.php @@ -41,8 +41,8 @@ public static function toHuman(DateInterval $interval): string $parts = []; foreach ($supported_components as $key => $human_value) { - $qty = $components[$key] ?? null; - $parts[] = $qty.' '.$human_value.($qty > 1 ? 's' : ''); + $qty = $interval->$key ?? null; + $parts[] = sprintf('%s %s%s', $qty, $human_value, $qty > 1 ? 's' : ''); } $last_part = array_pop($parts);