From 43a8c20dfd7bc431eaccccef6cdad1b557054266 Mon Sep 17 00:00:00 2001 From: acoulton Date: Mon, 26 Oct 2026 17:03:33 +0000 Subject: [PATCH 01/10] ci: Enable phpstan level 8 --- phpstan.dist.neon | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/phpstan.dist.neon b/phpstan.dist.neon index 720c16f..6509806 100644 --- a/phpstan.dist.neon +++ b/phpstan.dist.neon @@ -1,6 +1,6 @@ parameters: treatPhpDocTypesAsCertain: false - level: 7 + level: 8 paths: - src - test From 9fac96dfe047730aa6b741d8ecd7327c0fceebe0 Mon Sep 17 00:00:00 2001 From: acoulton Date: Mon, 26 Oct 2026 17:24:41 +0000 Subject: [PATCH 02/10] fix: Level 8 type-safety in tests --- test/unit/Logging/StackdriverApplicationLoggerTest.php | 2 +- test/unit/Mutex/BasicPDOStub.php | 7 ++++++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/test/unit/Logging/StackdriverApplicationLoggerTest.php b/test/unit/Logging/StackdriverApplicationLoggerTest.php index d09f022..bd460c3 100644 --- a/test/unit/Logging/StackdriverApplicationLoggerTest.php +++ b/test/unit/Logging/StackdriverApplicationLoggerTest.php @@ -130,7 +130,7 @@ public function testItAppendsLogsToExistingContentIfFileSpecified(): void $entries = $this->assertLoggedJSONLines(); $this->assertSame(['previous' => 'content'], array_shift($entries)); - $this->assertSame('Another message appended', array_shift($entries)['message']); + $this->assertSame('Another message appended', array_shift($entries)['message'] ?? null); } /** diff --git a/test/unit/Mutex/BasicPDOStub.php b/test/unit/Mutex/BasicPDOStub.php index a5bbd65..84abbb0 100644 --- a/test/unit/Mutex/BasicPDOStub.php +++ b/test/unit/Mutex/BasicPDOStub.php @@ -9,12 +9,16 @@ class BasicPDOStub extends PDO { /** @var list}> */ - protected $query_stack = []; + protected array $query_stack = []; /** @param list}> $stack */ public static function withQueryStack(array $stack): self { $i = new self(); + foreach ($stack as $q) { + Assert::assertIsString($q['sql'] ?? null, 'Each query stack entry must have `sql` string'); + Assert::assertIsArray($q['result'] ?? null, 'Each query stack entry must have result array'); + } $i->query_stack = $stack; return $i; @@ -36,6 +40,7 @@ public function query( ): PDOStatement|false { Assert::assertNotEmpty($this->query_stack, 'No expectation defined for query '.$statement); $next_query = array_shift($this->query_stack); + assert($next_query !== null, 'Should not get empty from array_shift on non-empty array'); Assert::assertSame($next_query['sql'], $statement); return new BasicPDOStatementStub($next_query['result']); From e4473b27f29d05cec49daf156faa3685c8c06ad3 Mon Sep 17 00:00:00 2001 From: acoulton Date: Mon, 26 Oct 2026 17:24:55 +0000 Subject: [PATCH 03/10] fix: Cookies cannot be set with null values --- src/Cookie/ArrayCookieWrapperStub.php | 4 ++-- src/Cookie/CookieWrapper.php | 4 ++-- src/Cookie/HeadersSentException.php | 9 ++++++--- test/unit/Cookie/CookieWrapperTest.php | 2 +- 4 files changed, 11 insertions(+), 8 deletions(-) diff --git a/src/Cookie/ArrayCookieWrapperStub.php b/src/Cookie/ArrayCookieWrapperStub.php index 6239061..05b818e 100644 --- a/src/Cookie/ArrayCookieWrapperStub.php +++ b/src/Cookie/ArrayCookieWrapperStub.php @@ -14,14 +14,14 @@ public function __construct(array $cookies = []) $this->cookies = $cookies; } - public function set(string $name, ?string $value = null, array $options = []): void + public function set(string $name, string $value = '', array $options = []): void { parent::set($name, $value, $options); $this->set_cookie_calls[$name][] = ['value' => $value, 'opts' => $options]; } /** @param array $options */ - protected function set_cookie(string $name, ?string $value, array $options): void + protected function set_cookie(string $name, string $value, array $options): void { // No-op } diff --git a/src/Cookie/CookieWrapper.php b/src/Cookie/CookieWrapper.php index 57b0d8f..9081c9b 100644 --- a/src/Cookie/CookieWrapper.php +++ b/src/Cookie/CookieWrapper.php @@ -37,7 +37,7 @@ public function __construct(protected bool $has_ssl_available = true) /** * @param array $options */ - public function set(string $name, ?string $value = null, array $options = []): void + public function set(string $name, string $value = '', array $options = []): void { if ($this->headers_sent($file, $line)) { throw new HeadersSentException($name, $file, $line); @@ -97,7 +97,7 @@ public function delete(string $name): void } /** @param array $options */ - protected function set_cookie(string $name, ?string $value, array $options): void + protected function set_cookie(string $name, string $value, array $options): void { setcookie($name, $value, $options); } diff --git a/src/Cookie/HeadersSentException.php b/src/Cookie/HeadersSentException.php index 7330947..d3e41f4 100644 --- a/src/Cookie/HeadersSentException.php +++ b/src/Cookie/HeadersSentException.php @@ -11,10 +11,13 @@ */ class HeadersSentException extends LogicException { - public function __construct(string $cookie_name, string $output_file, ?int $output_line) + public function __construct(string $cookie_name, ?string $output_file, ?int $output_line) { - parent::__construct( - "Cannot assign cookie $cookie_name - headers have been sent by output at $output_file:$output_line" + parent::__construct(sprintf( + "Cannot assign cookie $cookie_name - headers have been sent by output at %s:%s", + $output_file ?? '{unknown file}', + $output_line ?? '{unknown line}' + ) ); } } diff --git a/test/unit/Cookie/CookieWrapperTest.php b/test/unit/Cookie/CookieWrapperTest.php index ce9a67b..0068a20 100644 --- a/test/unit/Cookie/CookieWrapperTest.php +++ b/test/unit/Cookie/CookieWrapperTest.php @@ -229,7 +229,7 @@ class TestableCookieWrapper extends CookieWrapper /** @param array $options */ protected function set_cookie( string $name, - ?string $value, + string $value, array $options, ): void { $this->setcookie_calls[] = [ From c618e8d8b92b2fd8eb1fff068fb72af3c244a445 Mon Sep 17 00:00:00 2001 From: acoulton Date: Mon, 26 Oct 2026 17:25:10 +0000 Subject: [PATCH 04/10] fix: Always check the CSV resource is open before writing --- src/CSV/CSVWriter.php | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/CSV/CSVWriter.php b/src/CSV/CSVWriter.php index 471c4a9..c347c15 100644 --- a/src/CSV/CSVWriter.php +++ b/src/CSV/CSVWriter.php @@ -86,9 +86,15 @@ public function write(array $row): void throw MismatchedSchemaException::forSchema($this->expect_schema, $row_schema); } + if (!$this->isResourceOpen()) { + throw new LogicException('Cannot write to a closed file'); + } fputcsv($this->resource, $row, eol: $this->options['eol']); } + /** + * @phpstan-assert-if-true resource $this->resource + */ protected function isResourceOpen(): bool { return $this->resource && (get_resource_type($this->resource) === 'stream'); @@ -113,6 +119,9 @@ public function close(): void private function writeHeaders(array $keys): void { if ($this->options['quote_headers']) { + if (!$this->isResourceOpen()) { + throw new LogicException('Cannot write to a closed file'); + } fputcsv($this->resource, $keys, eol: $this->options['eol']); } else { array_walk( @@ -122,6 +131,9 @@ private function writeHeaders(array $keys): void "Column header `$str` cannot contain comma if headers are not quoted" ) ); + if (!$this->isResourceOpen()) { + throw new LogicException('Cannot write to a closed file'); + } fwrite($this->resource, implode(',', $keys).$this->options['eol']); } } From f921d09f923a8d68ee25b635de850916d722beae Mon Sep 17 00:00:00 2001 From: acoulton Date: Mon, 26 Oct 2026 17:25:49 +0000 Subject: [PATCH 05/10] fix: All DateString format methods should support a `null` empty value Previously some did and some did not, causing confusion about whether the methods should be :string or :?string. --- src/DateTime/DateString.php | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/DateTime/DateString.php b/src/DateTime/DateString.php index a9514b0..b494f38 100644 --- a/src/DateTime/DateString.php +++ b/src/DateTime/DateString.php @@ -1,5 +1,7 @@ * @@ -15,7 +17,7 @@ */ class DateString { - public static function format(?DateTimeImmutable $date, string $format, string $empty_value = ''): string + public static function format(?DateTimeImmutable $date, string $format, ?string $empty_value = ''): ?string { if (!$date instanceof DateTimeImmutable) { return $empty_value; @@ -35,7 +37,7 @@ public static function isoMS(?DateTimeImmutable $date, ?string $empty_value = '' /** * Formats as Y-m-d H:i:s. */ - public static function ymd(?DateTimeImmutable $date, string $empty_value = ''): string + public static function ymd(?DateTimeImmutable $date, ?string $empty_value = ''): ?string { return static::format($date, 'Y-m-d', $empty_value); } @@ -43,7 +45,7 @@ public static function ymd(?DateTimeImmutable $date, string $empty_value = ''): /** * Formats as Y-m-d H:i:s. */ - public static function ymdhis(?DateTimeImmutable $date, string $empty_value = ''): string + public static function ymdhis(?DateTimeImmutable $date, ?string $empty_value = ''): ?string { return static::format($date, 'Y-m-d H:i:s', $empty_value); } From 1bb9c56cc96beaf680428d7ed9a8fe6b9ae61b8d Mon Sep 17 00:00:00 2001 From: acoulton Date: Mon, 26 Oct 2026 17:26:31 +0000 Subject: [PATCH 06/10] fix: Ensure CryptoBoxKeypair always has a keypair when used Theoretically the keypair could have been nulled at runtime e.g. if `__destruct` was called manually from userland code. --- src/Encryption/CryptoBox/CryptoBoxKeypair.php | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/src/Encryption/CryptoBox/CryptoBoxKeypair.php b/src/Encryption/CryptoBox/CryptoBoxKeypair.php index 83a83a3..92508f9 100644 --- a/src/Encryption/CryptoBox/CryptoBoxKeypair.php +++ b/src/Encryption/CryptoBox/CryptoBoxKeypair.php @@ -89,7 +89,7 @@ private function __construct( ) { // Creating the public key now is the easiest way to validate that the incoming keypair string is actually valid try { - $this->public_key = new CryptoBoxPublicKey(sodium_crypto_box_publickey($this->keypair), $this->keypair_id); + $this->public_key = new CryptoBoxPublicKey(sodium_crypto_box_publickey($this->requireKeypair()), $this->keypair_id); } catch (SodiumException $e) { throw new InvalidArgumentException('Invalid keypair: '.$e->getMessage(), $e->getCode(), $e); } @@ -120,7 +120,7 @@ public function decrypt(CryptoBoxString $encrypted): string } try { - $result = sodium_crypto_box_seal_open($encrypted->ciphertext, $this->keypair); + $result = sodium_crypto_box_seal_open($encrypted->ciphertext, $this->requireKeypair()); if ($result === false) { throw new DecryptionFailedException('Failed to decrypt - invalid key or ciphertext?'); } @@ -140,6 +140,18 @@ public function decrypt(CryptoBoxString $encrypted): string public function exportToString(): string { // Use constant-time base64 decoding to avoid timing attacks - return $this->keypair_id.'.'.sodium_bin2base64($this->keypair, SODIUM_BASE64_VARIANT_URLSAFE_NO_PADDING); + return $this->keypair_id.'.'.sodium_bin2base64($this->requireKeypair(), SODIUM_BASE64_VARIANT_URLSAFE_NO_PADDING); + } + + private function requireKeypair(): string + { + if ($this->keypair === null) { + // This shouldn't be possible if created through our constructors which all take a `string` not a `?string`. + // However the property itself has to be nullable to allow us to null it on __destruct, meaning phpstan + // (and we) cannot *guarantee* that it will never be null when we attempt to use it. + throw new InvalidArgumentException('Unexpected state: keypair is null'); + } + + return $this->keypair; } } From f63693e8060fb2cf9d2a42af0776373486e113ce Mon Sep 17 00:00:00 2001 From: acoulton Date: Mon, 26 Oct 2026 17:26:46 +0000 Subject: [PATCH 07/10] fix: UniqueMap should only accept string keys --- src/ArrayHelpers/UniqueMap.php | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/ArrayHelpers/UniqueMap.php b/src/ArrayHelpers/UniqueMap.php index 12f8fda..82de44b 100644 --- a/src/ArrayHelpers/UniqueMap.php +++ b/src/ArrayHelpers/UniqueMap.php @@ -7,6 +7,7 @@ use ArrayAccess; use ArrayIterator; use Countable; +use InvalidArgumentException; use IteratorAggregate; use OutOfBoundsException; use Traversable; @@ -41,6 +42,10 @@ public function offsetExists(mixed $offset): bool public function offsetGet(mixed $offset): mixed { + if (!is_string($offset)) { + throw new InvalidArgumentException('Map keys must be strings'); + } + if (!array_key_exists($offset, $this->items)) { throw new OutOfBoundsException('No item with key '.$offset); } @@ -50,6 +55,10 @@ public function offsetGet(mixed $offset): mixed public function offsetSet(mixed $offset, mixed $value): void { + if (!is_string($offset)) { + throw new InvalidArgumentException('Map keys must be strings'); + } + if (array_key_exists($offset, $this->items)) { throw new DuplicateMapItemException('Map already contains an item with key '.$offset); } From 62ed3bdb8729764fe5e3b4e69e2013573f1b8d0e Mon Sep 17 00:00:00 2001 From: acoulton Date: Mon, 26 Oct 2026 17:26:59 +0000 Subject: [PATCH 08/10] fix: Handle regex failure when sanitising string --- src/StringEncoding/StringSanitiser.php | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/StringEncoding/StringSanitiser.php b/src/StringEncoding/StringSanitiser.php index 013671d..cafaaf0 100644 --- a/src/StringEncoding/StringSanitiser.php +++ b/src/StringEncoding/StringSanitiser.php @@ -2,6 +2,8 @@ namespace Ingenerator\PHPUtils\StringEncoding; +use RuntimeException; + class StringSanitiser { /** @@ -23,6 +25,9 @@ public static function ensurePrintableUtf8(string $input, ?int $max_length = nul '�', mb_convert_encoding($input, 'UTF-8', 'UTF-8') ); + if ($cleaned === null) { + throw new RuntimeException('Failed to replace invalid UTF8 in string'); + } if ($max_length !== null) { return mb_substr($cleaned, 0, $max_length); From 969a3dae64051cbeb6337345a0b599fc43a8770a Mon Sep 17 00:00:00 2001 From: acoulton Date: Mon, 26 Oct 2026 17:27:10 +0000 Subject: [PATCH 09/10] fix: Handle failure to parse XML when parsing sitemap --- src/Sitemap/SitemapParser.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/Sitemap/SitemapParser.php b/src/Sitemap/SitemapParser.php index 5e9810f..380c113 100644 --- a/src/Sitemap/SitemapParser.php +++ b/src/Sitemap/SitemapParser.php @@ -7,6 +7,7 @@ use DOMDocument; use InvalidArgumentException; use LibXMLError; +use SimpleXMLElement; use function array_map; use function implode; @@ -29,6 +30,9 @@ public static function parse(string $sitemap): array $doc = self::validateSitemapXML($sitemap); $xml = simplexml_import_dom($doc); + if (!$xml instanceof SimpleXMLElement) { + throw new InvalidArgumentException('Failed to parse sitemap XML'); + } $urls = []; foreach ($xml->url as $x_url) { $url = (string) $x_url->loc; From fad50e7a9d3c04084759130007bf0c8b5a699a1d Mon Sep 17 00:00:00 2001 From: acoulton Date: Mon, 26 Oct 2026 17:27:46 +0000 Subject: [PATCH 10/10] ci: Mark expected behaviour of DeviceIdentifier creating a singleton PHPStan couldn't follow this logic since we call an extra factory method . --- src/Logging/DeviceIdentifier.php | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Logging/DeviceIdentifier.php b/src/Logging/DeviceIdentifier.php index 0951821..014a114 100644 --- a/src/Logging/DeviceIdentifier.php +++ b/src/Logging/DeviceIdentifier.php @@ -53,6 +53,7 @@ public static function initAndEnsureCookieSet(bool $ssl_available, bool $is_cli } else { static::$instance = new DeviceIdentifier(new CookieWrapper($ssl_available)); } + assert(static::$instance instanceof DeviceIdentifier, 'Should have been assigned by above or by ::forceGlobalTestValue'); static::$instance->init(); }