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 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); 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); 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( 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/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); } 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); } } 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; } 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), 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; } 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/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 ); 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