diff --git a/phpstan.dist.neon b/phpstan.dist.neon index 56beacb..fdf92f2 100644 --- a/phpstan.dist.neon +++ b/phpstan.dist.neon @@ -1,6 +1,6 @@ parameters: treatPhpDocTypesAsCertain: false - level: 5 + level: 6 paths: - src - test diff --git a/rector.php b/rector.php index 02481e5..1ee4710 100644 --- a/rector.php +++ b/rector.php @@ -3,6 +3,7 @@ declare(strict_types=1); use Rector\Config\RectorConfig; +use Rector\Php81\Rector\Property\ReadOnlyPropertyRector; use Rector\Php82\Rector\Class_\ReadOnlyClassRector; return RectorConfig::configure() @@ -22,6 +23,10 @@ ->withSkip([ // Don't make whole classes read-only in libraries, it makes BC awkward ReadOnlyClassRector::class, + // Don't force test properties to readonly + ReadOnlyPropertyRector::class => [ + __DIR__.'/test/unit/Object/ObjectPropertyPopulatorTest.php', + ], ]) ->withImportNames( removeUnusedImports: true, diff --git a/src/ArrayHelpers/AssociativeArrayUtils.php b/src/ArrayHelpers/AssociativeArrayUtils.php index 47e0693..f289530 100644 --- a/src/ArrayHelpers/AssociativeArrayUtils.php +++ b/src/ArrayHelpers/AssociativeArrayUtils.php @@ -37,8 +37,10 @@ class AssociativeArrayUtils * * Updated PHP7 implementation of Kohana's \Arr::merge, with the same behaviour * - * @param array $merge_base initial array - * @param array $merge_patches,... array to merge + * @param array $merge_base initial array + * @param array ...$merge_patches array to merge + * + * @return array */ public static function deepMerge(array $merge_base, array ...$merge_patches): array { @@ -74,7 +76,7 @@ public static function deepMerge(array $merge_base, array ...$merge_patches): ar * * Imported from the Kohana framework. * - * @param array $array array to check + * @param array $array array to check * * @author Kohana Team */ @@ -91,6 +93,11 @@ public static function isAssociative(array $array): bool /** * Turns 'this.thing.here => bar' into ['this']['thing']['here'] = bar. */ + /** + * @param array $input + * + * @return array + */ public static function pathsToNested(array $input): array { $result = []; @@ -104,8 +111,8 @@ public static function pathsToNested(array $input): array /** * Set a value on an array by path. * - * @param array $array Array to update - * @param string|array $path Path + * @param array $array Array to update + * @param string|list $path Path * @param mixed $value Value to set * @param string $delimiter Path delimiter * @@ -148,6 +155,12 @@ public static function setPath(array &$array, string|array $path, mixed $value, * assert($array === ['mix' => 'of', 'useful' => 'separately']); * assert($result === ['things' => 'that', 'might' => 'be']); // Note `undefined` not present in source or result */ + /** + * @param array $source + * @param list $pop_keys + * + * @return array + */ public static function popKeys(array &$source, array $pop_keys): array { $result = []; diff --git a/src/ArrayHelpers/UniqueMap.php b/src/ArrayHelpers/UniqueMap.php index 8672794..12f8fda 100644 --- a/src/ArrayHelpers/UniqueMap.php +++ b/src/ArrayHelpers/UniqueMap.php @@ -21,6 +21,9 @@ * * 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 */ class UniqueMap implements ArrayAccess, IteratorAggregate, Countable { @@ -59,6 +62,7 @@ public function offsetUnset(mixed $offset): void unset($this->items[$offset]); } + /** @return ArrayIterator */ public function getIterator(): Traversable { return new ArrayIterator($this->items); diff --git a/src/CSV/CSVWriter.php b/src/CSV/CSVWriter.php index bef44c6..3fe9b08 100644 --- a/src/CSV/CSVWriter.php +++ b/src/CSV/CSVWriter.php @@ -32,8 +32,10 @@ class CSVWriter protected bool $owns_resource; + /** @var list|null */ protected ?array $expect_schema = null; + /** @var array{write_utf8_bom: bool, quote_headers: bool, eol: string} */ protected array $options = [ 'write_utf8_bom' => false, 'quote_headers' => true, @@ -61,6 +63,7 @@ public function open(mixed $file, array $options = []): void $this->options = array_merge($this->options, $options); } + /** @param array $row */ public function write(array $row): void { if (!$this->isResourceOpen()) { diff --git a/src/CSV/MismatchedSchemaException.php b/src/CSV/MismatchedSchemaException.php index 069238e..769cec8 100644 --- a/src/CSV/MismatchedSchemaException.php +++ b/src/CSV/MismatchedSchemaException.php @@ -15,6 +15,9 @@ final class MismatchedSchemaException extends InvalidArgumentException { + /** @param list $expected + * @param list $actual + */ public static function forSchema(array $expected, array $actual): self { return new self( diff --git a/src/Cookie/ArrayCookieWrapperStub.php b/src/Cookie/ArrayCookieWrapperStub.php index 5045582..6239061 100644 --- a/src/Cookie/ArrayCookieWrapperStub.php +++ b/src/Cookie/ArrayCookieWrapperStub.php @@ -4,8 +4,10 @@ class ArrayCookieWrapperStub extends CookieWrapper { + /** @var array}>> */ protected $set_cookie_calls = []; + /** @param array $cookies */ public function __construct(array $cookies = []) { parent::__construct(has_ssl_available: false); @@ -18,16 +20,18 @@ public function set(string $name, ?string $value = null, array $options = []): v $this->set_cookie_calls[$name][] = ['value' => $value, 'opts' => $options]; } - protected function set_cookie($name, $value, $options): void + /** @param array $options */ + protected function set_cookie(string $name, ?string $value, array $options): void { // No-op } - protected function headers_sent(&$file, &$line): bool + protected function headers_sent(?string &$file = null, ?int &$line = null): bool { return false; } + /** @return array}>> */ public function inspectSetCookies(): array { return $this->set_cookie_calls; diff --git a/src/Cookie/CookieWrapper.php b/src/Cookie/CookieWrapper.php index 697bbd5..57b0d8f 100644 --- a/src/Cookie/CookieWrapper.php +++ b/src/Cookie/CookieWrapper.php @@ -96,12 +96,13 @@ public function delete(string $name): void unset($this->cookies[$name]); } - protected function set_cookie($name, $value, $options) + /** @param array $options */ + protected function set_cookie(string $name, ?string $value, array $options): void { setcookie($name, $value, $options); } - protected function headers_sent(&$file, &$line): bool + protected function headers_sent(?string &$file = null, ?int &$line = null): bool { return headers_sent($file, $line); } diff --git a/src/Cookie/HeadersSentException.php b/src/Cookie/HeadersSentException.php index 1755d46..7330947 100644 --- a/src/Cookie/HeadersSentException.php +++ b/src/Cookie/HeadersSentException.php @@ -11,7 +11,7 @@ */ class HeadersSentException extends LogicException { - public function __construct(string $cookie_name, string $output_file, string $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" diff --git a/src/DateTime/Clock/RealtimeClock.php b/src/DateTime/Clock/RealtimeClock.php index ea60918..0ce36c9 100644 --- a/src/DateTime/Clock/RealtimeClock.php +++ b/src/DateTime/Clock/RealtimeClock.php @@ -31,7 +31,7 @@ public function getMicrotime(): float return microtime(true); } - public function usleep($microseconds): void + public function usleep(int $microseconds): void { usleep($microseconds); } diff --git a/src/DateTime/Clock/StoppedMockClock.php b/src/DateTime/Clock/StoppedMockClock.php index 4485c80..d6f6b8c 100644 --- a/src/DateTime/Clock/StoppedMockClock.php +++ b/src/DateTime/Clock/StoppedMockClock.php @@ -17,9 +17,7 @@ final class StoppedMockClock extends RealtimeClock { private float $current_microtime; - /** - * @var int[] - */ + /** @var list */ private array $sleeps = []; /** @@ -78,18 +76,19 @@ public function tickMicroseconds(float $microseconds): void $this->current_microtime += ($microseconds / 1000000); } - public function usleep($microseconds): void + public function usleep(int $microseconds): void { $this->tickMicroseconds($microseconds); $this->sleeps[] = $microseconds; } - public function assertSlept(array $expected, $msg = ''): void + /** @param list $expected */ + public function assertSlept(array $expected, string $msg = ''): void { Assert::assertSame($expected, $this->sleeps, $msg); } - public function assertNeverSlept($msg = ''): void + public function assertNeverSlept(string $msg = ''): void { Assert::assertSame([], $this->sleeps, $msg); } diff --git a/src/DeploymentConfig/ConfigMapDeclarationParser.php b/src/DeploymentConfig/ConfigMapDeclarationParser.php index d71c1d5..c8a639c 100644 --- a/src/DeploymentConfig/ConfigMapDeclarationParser.php +++ b/src/DeploymentConfig/ConfigMapDeclarationParser.php @@ -22,6 +22,11 @@ class ConfigMapDeclarationParser * * This can then be used as a simple lookup table in the deployment config class */ + /** + * @param array $declarations + * + * @return array + */ public function parse(array $declarations): array { $result = []; @@ -38,7 +43,10 @@ public function parse(array $declarations): array return $result; } - protected function validateDeclaration($declaration): array + /** + * @return array{list, mixed} + */ + protected function validateDeclaration(mixed $declaration): array { if (!is_array($declaration)) { throw InvalidConfigException::invalidMapDeclaration('not an array'); diff --git a/src/DeploymentConfig/ConfigValueDecrypter.php b/src/DeploymentConfig/ConfigValueDecrypter.php index 1615505..c434e22 100644 --- a/src/DeploymentConfig/ConfigValueDecrypter.php +++ b/src/DeploymentConfig/ConfigValueDecrypter.php @@ -15,7 +15,7 @@ public function __construct(protected string $keypair_dir) { } - public function decrypt($value) + public function decrypt(mixed $value): mixed { if (is_string($value) && preg_match('/^#SECRET-?(?P.*)#(?P.+)$/', $value, $matches)) { return $this->tryDecrypt($matches['ciphertext'], $this->getKeypair($matches['keypair'] ?: 'default')); diff --git a/src/DeploymentConfig/DeploymentConfig.php b/src/DeploymentConfig/DeploymentConfig.php index 9aaf07e..db796de 100644 --- a/src/DeploymentConfig/DeploymentConfig.php +++ b/src/DeploymentConfig/DeploymentConfig.php @@ -37,7 +37,7 @@ public static function instance() } /** - * @param array|null $env_vars - if missing will default to reading from $_SERVER + * @param array|null $env_vars - if missing will default to reading from $_SERVER */ private function __construct( ?array $env_vars = null, @@ -91,7 +91,7 @@ public function read(string $path): ?string /** * Use this when the value of a config / secret is type-sensitive (integer / boolean / supports null value). */ - public function readJSON(string $string) + public function readJSON(string $string): mixed { $value = $this->read($string); if ($value === null) { @@ -105,7 +105,8 @@ public function readJSON(string $string) } } - public function map(array ...$declarations) + /** @param array ...$declarations */ + public function map(array ...$declarations): mixed { $map = $this->map_parser->parse($declarations); if (array_key_exists($this->environment, $map)) { diff --git a/src/DeploymentConfig/InvalidConfigException.php b/src/DeploymentConfig/InvalidConfigException.php index 6c571ae..f1dfdab 100644 --- a/src/DeploymentConfig/InvalidConfigException.php +++ b/src/DeploymentConfig/InvalidConfigException.php @@ -25,7 +25,7 @@ public static function corruptKeypair(string $keypair_file, string $reason): Inv return new self('Corrupt config keypair file '.$keypair_file.' ('.$reason.')'); } - public static function duplicateEnvironmentMap($env): InvalidConfigException + public static function duplicateEnvironmentMap(string $env): InvalidConfigException { return new self('Duplicate environment mapping for '.$env); } diff --git a/src/DeploymentConfig/MissingConfigException.php b/src/DeploymentConfig/MissingConfigException.php index 36b0357..ac8fbb0 100644 --- a/src/DeploymentConfig/MissingConfigException.php +++ b/src/DeploymentConfig/MissingConfigException.php @@ -8,12 +8,12 @@ final class MissingConfigException extends RuntimeException { - public static function missingFile($path, $real_path, $env): static + public static function missingFile(string $path, string $real_path, string $env): static { return new self("Config `$path` is not present in `$real_path` and is required for `$env` environment"); } - public static function missingMapValue($env): static + public static function missingMapValue(string $env): static { return new self("No config map entry for `$env`, nor one for `*`"); } diff --git a/src/Logging/DefaultLogMetadata.php b/src/Logging/DefaultLogMetadata.php index c172439..73ceb70 100644 --- a/src/Logging/DefaultLogMetadata.php +++ b/src/Logging/DefaultLogMetadata.php @@ -91,7 +91,7 @@ public static function requestTrace(array $server = [], ?string $gcp_project = n * * If the file does not exist or cannot be read the version will be returned as '#ERROR#' * - * @return array|array[] + * @return array{serviceContext: array{service: string, version: mixed}} */ public static function serviceContext(string $service_name, ?string $version_file_path = null): array { diff --git a/src/Logging/DeviceIdentifier.php b/src/Logging/DeviceIdentifier.php index 8775d6a..0951821 100644 --- a/src/Logging/DeviceIdentifier.php +++ b/src/Logging/DeviceIdentifier.php @@ -116,7 +116,7 @@ public function init(): void } } - protected function assignNewIdAndSetCookies() + protected function assignNewIdAndSetCookies(): void { $this->id = Base64Url::encode(random_bytes(16)); $expire = (new DateTimeImmutable())->add(new DateInterval(static::COOKIE_LIFETIME)); diff --git a/src/Logging/ExternalCallSiteFinder.php b/src/Logging/ExternalCallSiteFinder.php index 1aafd65..bc1d2bc 100644 --- a/src/Logging/ExternalCallSiteFinder.php +++ b/src/Logging/ExternalCallSiteFinder.php @@ -48,6 +48,12 @@ class ExternalCallSiteFinder * } * } */ + /** + * @param list> $trace + * @param list $ignore_classes + * + * @return array + */ public function findExternalCall(array $trace, array $ignore_classes): array { $orig_trace = $trace; @@ -102,6 +108,7 @@ public function findExternalCall(array $trace, array $ignore_classes): array ]; } + /** @param list $ignore_classes */ protected function isIgnoredClass(string $class, array $ignore_classes): bool { foreach ($ignore_classes as $ignored_class) { diff --git a/src/Logging/LogMetadataProvider.php b/src/Logging/LogMetadataProvider.php index 5da2c43..ac94946 100644 --- a/src/Logging/LogMetadataProvider.php +++ b/src/Logging/LogMetadataProvider.php @@ -21,6 +21,8 @@ interface LogMetadataProvider * if appropriate return a warning value in your array. Only unexpected / system-level exceptions (failure to * connect to external service / invalid configuration even when fully bootstrapped / etc) should bubble to allow * these to be detected and fixed. + * + * @return array */ public function getMetadata(): array; } diff --git a/src/Logging/StackdriverApplicationLogger.php b/src/Logging/StackdriverApplicationLogger.php index 425abe1..e1fd779 100644 --- a/src/Logging/StackdriverApplicationLogger.php +++ b/src/Logging/StackdriverApplicationLogger.php @@ -32,6 +32,9 @@ * again with appropriate application-level metadata. * * Exceptions will be formatted and (by default) tagged to be reported to Stackdriver Errors - see `->log()` for details + * + * @phpstan-type TLogMetadataGroup array + * @phpstan-type TLogMetadataSource TLogMetadataGroup|callable(): TLogMetadataGroup|LogMetadataProvider */ class StackdriverApplicationLogger extends AbstractLogger { @@ -45,8 +48,14 @@ class StackdriverApplicationLogger extends AbstractLogger protected ExternalCallSiteFinder $call_site_finder; + /** + * @var array + */ protected array $metadata; + /** + * @var list + */ protected array $metadata_sources; /** @@ -100,11 +109,11 @@ class StackdriverApplicationLogger extends AbstractLogger * return StackdriverApplicationLogger::instance(); * * @param string $log_destination A PHP file / stream destination to append, commonly php://stdout - * @param array|callable|LogMetadataProvider ...$metadata_sources Sources of metadata to merge together + * @param TLogMetadataSource ...$metadata_sources Sources of metadata to merge together */ public function __construct( protected string $log_destination, - ...$metadata_sources, + array|callable|LogMetadataProvider ...$metadata_sources, ) { $this->metadata_sources = array_pad($metadata_sources, 2, []); $this->call_site_finder = new ExternalCallSiteFinder(); @@ -193,6 +202,8 @@ public function log($level, string|Stringable $message, array $context = []): vo /** * Lazily compiles all provided metadata. + * + * @return TLogMetadataGroup */ protected function getMetadata(): array { @@ -233,6 +244,17 @@ protected function getMetadata(): array return $this->metadata; } + /** + * @return array{ + * class: string, + * msg: string, + * code: int, + * file: string, + * line: int, + * trace: string, + * previous?: array + * } + */ protected function formatException(Throwable $e): array { $result = [ @@ -260,6 +282,8 @@ protected function formatException(Throwable $e): array * * This method renders a string trace that follows the format of the standard trace (so it can be * parsed by tools that are looking for that) but without including any function argument details. + * + * @param array $trace_stack */ protected function getExceptionTraceAsStringWithoutArgs(array $trace_stack): string { @@ -282,6 +306,8 @@ protected function getExceptionTraceAsStringWithoutArgs(array $trace_stack): str /** * @param array $log_entry + * + * @return array $server */ protected function addStackdriverErrorReportingData(array $log_entry): array { @@ -313,6 +339,9 @@ protected function addStackdriverErrorReportingData(array $log_entry): array return $log_entry; } + /** + * @param array $log_entry + */ protected function writeLog(array $log_entry): void { try { @@ -343,7 +372,7 @@ 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 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 diff --git a/src/Mutex/MockMutexWrapper.php b/src/Mutex/MockMutexWrapper.php index 65a56c3..c06f0a0 100644 --- a/src/Mutex/MockMutexWrapper.php +++ b/src/Mutex/MockMutexWrapper.php @@ -4,13 +4,19 @@ use LogicException; +/** + * @phpstan-type TLockHistoryEntry array{name: string, timeout: int} + */ class MockMutexWrapper implements MutexWrapper { - protected $always_timeout = false; + protected bool $always_timeout = false; - protected $current_lock_name; + protected ?string $current_lock_name = null; - protected $lock_history = []; + /** + * @var list + */ + protected array $lock_history = []; public function withLock(string $name, int $timeout_seconds, callable $exclusive_code) { @@ -59,6 +65,8 @@ public function getCurrentLockName(): string * This is useful where you can only observe the outside of your process, but does not provide a way * to verify that the application code actually ran *inside* the mutex rather than before / after it. * Where possible use an injected callback and the ->getCurrentLockName method. + * + * @return list */ public function getLockHistory(): array { diff --git a/src/Mutex/MutexTimedOutException.php b/src/Mutex/MutexTimedOutException.php index 6c1b8b9..37bd8d6 100644 --- a/src/Mutex/MutexTimedOutException.php +++ b/src/Mutex/MutexTimedOutException.php @@ -9,7 +9,7 @@ class MutexTimedOutException extends RuntimeException { - public function __construct(string $name, int $timeout, $result) + public function __construct(string $name, int $timeout, mixed $result) { parent::__construct( sprintf( diff --git a/src/Object/ConstantDirectory.php b/src/Object/ConstantDirectory.php index ae2058c..1498c7b 100644 --- a/src/Object/ConstantDirectory.php +++ b/src/Object/ConstantDirectory.php @@ -15,6 +15,9 @@ final class ConstantDirectory { + /** + * @var array + */ private array $constants; private function __construct(private readonly string $class_name) @@ -27,7 +30,7 @@ public static function forClass(string $class): static } /** - * @return array keyed by the constant id + * @return array keyed by the constant id */ public function filterConstants(string $prefix): array { @@ -43,7 +46,7 @@ public function filterConstants(string $prefix): array } /** - * @return array keyed by the constant id + * @return array keyed by the constant id */ public function listConstants(): array { @@ -55,7 +58,7 @@ public function listConstants(): array } /** - * @return array keyed by the constant id + * @return array keyed by the constant id */ private function loadConstants(): array { diff --git a/src/Object/InitialisableSingletonTrait.php b/src/Object/InitialisableSingletonTrait.php index e8639d2..1f07326 100644 --- a/src/Object/InitialisableSingletonTrait.php +++ b/src/Object/InitialisableSingletonTrait.php @@ -10,16 +10,17 @@ */ trait InitialisableSingletonTrait { + /** + * @var static + */ protected static $instance; /** * Return the singleton instance. * - * @return static - * * @throws SingletonNotInitialisedException if the class has not been initialised */ - public static function instance() + public static function instance(): static { if (!static::$instance) { throw new SingletonNotInitialisedException('Cannot access '.static::class.' - class not initialised'); diff --git a/src/Object/ObjectPropertyPopulator.php b/src/Object/ObjectPropertyPopulator.php index 4a0aa62..c9d72bd 100644 --- a/src/Object/ObjectPropertyPopulator.php +++ b/src/Object/ObjectPropertyPopulator.php @@ -26,10 +26,7 @@ private function __construct() { } - /** - * @param object $object - */ - public static function assign($object, string $property, $value): void + public static function assign(object $object, string $property, mixed $value): void { static::assignHash($object, [$property => $value]); } @@ -37,10 +34,9 @@ public static function assign($object, string $property, $value): void /** * Assign an array of properties on the object keyed by their name, throwing if any property is undefined. * - * @param object $object * @param array $properties */ - public static function assignHash($object, array $properties): void + public static function assignHash(object $object, array $properties): void { if ($undefined = self::listUndefinedProperties($object, array_keys($properties))) { throw new InvalidArgumentException( @@ -65,8 +61,10 @@ function ($object, array $properties): void { /** * @param string[] $property_names + * + * @return list */ - private static function listUndefinedProperties($object, array $property_names): array + private static function listUndefinedProperties(object $object, array $property_names): array { return array_values( array_filter( diff --git a/src/Object/ObjectPropertyRipper.php b/src/Object/ObjectPropertyRipper.php index b06dcf2..e7e5d6a 100644 --- a/src/Object/ObjectPropertyRipper.php +++ b/src/Object/ObjectPropertyRipper.php @@ -28,10 +28,11 @@ class ObjectPropertyRipper /** * Grab the values of all these (presumably private / protected) properties from inside object. * - * @param object $object * @param string[] $properties + * + * @return array */ - public static function rip($object, array $properties): array + public static function rip(object $object, array $properties): array { $ripper = static::getRipper($object::class); @@ -43,6 +44,8 @@ public static function rip($object, array $properties): array * * Note it does not support objects where a parent class has any private properties, as these cannot be reliably * exported. + * + * @return array */ public static function ripAll(object $object): array { @@ -71,10 +74,8 @@ public static function ripAll(object $object): array /** * Grab a single property value from the object. - * - * @param object $object */ - public static function ripOne($object, string $property) + public static function ripOne(object $object, string $property): mixed { return static::rip($object, [$property])[$property]; } diff --git a/src/Object/ScopeChangingCaller.php b/src/Object/ScopeChangingCaller.php index 8808ae1..9c7f020 100644 --- a/src/Object/ScopeChangingCaller.php +++ b/src/Object/ScopeChangingCaller.php @@ -23,8 +23,14 @@ class ScopeChangingCaller * ACachedThing::class, * function () { ACachedThing::$cache = NULL; } * ); + * + * @template TReturn of mixed + * @template TArgs + * + * @param callable(TArgs):TReturn $func + * @param TArgs $args,... */ - public static function call(string $class, callable $func, ...$args) + public static function call(string $class, callable $func, mixed ...$args): mixed { $func = Closure::bind($func, null, $class); diff --git a/src/Random/ConsistentStringScrambler.php b/src/Random/ConsistentStringScrambler.php index cc0ff79..6d1a6dc 100644 --- a/src/Random/ConsistentStringScrambler.php +++ b/src/Random/ConsistentStringScrambler.php @@ -40,7 +40,9 @@ public function shuffleWords(?string $input, string $random_seed): ?string /** * Seeded Fisher-Yates shuffle implemented as per https://stackoverflow.com/a/19658344. * - * @param string[] $items + * @param list $items + * + * @return list */ private function seededShuffle(array $items, int $seed): array { diff --git a/src/Repository/AbstractArrayRepository.php b/src/Repository/AbstractArrayRepository.php index e10ffea..480e485 100644 --- a/src/Repository/AbstractArrayRepository.php +++ b/src/Repository/AbstractArrayRepository.php @@ -33,14 +33,16 @@ * Base class for an array-based memory repository for use in unit tests. Provides helpers to allow * easy and quick creation of array-backed implementations of a project-specific repository interface. * - * @template T of object + * @template TEntityInstance of object + * + * @phpstan-type TEntityData array */ abstract class AbstractArrayRepository { protected string $save_log = ''; /** - * @param array $entities + * @param array $entities */ final protected function __construct(protected array $entities) { @@ -55,11 +57,11 @@ protected function onConstruct(): void /** * Create a repo with the provided entities. Pass entities, or arrays of properties to stub. * - * @param array|T $entity ,... + * @param TEntityData|TEntityInstance $entity ,... * * @return static */ - public static function with($entity) + public static function with(array|object $entity) { return static::withList(func_get_args()); } @@ -67,7 +69,7 @@ public static function with($entity) /** * Same as ::with, but takes an array rather than a list of method parameters. * - * @param list $entity_data + * @param list $entity_data * * @return static */ @@ -86,14 +88,14 @@ public static function withList(array $entity_data) } /** - * @return class-string + * @return class-string */ abstract protected static function getEntityBaseClass(): string; /** - * @param array $data + * @param TEntityData $data * - * @return T + * @return TEntityInstance */ protected static function stubEntity(array $data): object { @@ -126,7 +128,7 @@ protected function assertNothingSaved(): void /** * This, and only this, entity should have been saved. * - * @param T $entity + * @param TEntityInstance $entity */ protected function assertSavedOnly(object $entity): void { @@ -140,7 +142,7 @@ protected function assertSavedOnly(object $entity): void /** * Build a save-log record to allow the class to identify what's been saved for assertions. * - * @param T $entity + * @param TEntityInstance $entity */ protected function formatSaveLog(object $entity): string { @@ -156,6 +158,10 @@ protected function formatSaveLog(object $entity): string * Creates a simple array representation of a set of entities that can be formatted as JSON. * * Used to capture a snapshot of entity state at the time it's saved to allow later comparison + * + * @param WeakMap $seen_objects + * + * @return array */ protected function entityToArray(object $entity, ?WeakMap $seen_objects = null): array { @@ -203,7 +209,7 @@ protected function entityToArray(object $entity, ?WeakMap $seen_objects = null): * ); * } * - * @param callable(T):string $callable + * @param callable(TEntityInstance):string $callable * * @return array */ @@ -225,9 +231,9 @@ protected function countWith(callable $callable): array * return $this->loadWith(function (MyEntity $e) use ($id) { return $e->getId() === $id; }); * } * - * @param callable(T):bool $callable + * @param callable(TEntityInstance):bool $callable * - * @return T + * @return TEntityInstance */ protected function loadWith(callable $callable): object { @@ -241,9 +247,9 @@ protected function loadWith(callable $callable): object /** * Find a single entity matching the callback, or null (throws if non-unique). * - * @param callable(T):bool $callable + * @param callable(TEntityInstance):bool $callable * - * @return T|null + * @return TEntityInstance|null */ protected function findWith(callable $callable): ?object { @@ -260,9 +266,9 @@ protected function findWith(callable $callable): ?object /** * Find all entities that the callable matches (like array_filter). * - * @param callable(T):bool $callable + * @param callable(TEntityInstance):bool $callable * - * @return array + * @return array */ protected function listWith($callable): array { @@ -282,7 +288,7 @@ protected function listWith($callable): array * The state of all entity properties will be captured at time of save to allow verifying that * it hasn't been subsequently modified. * - * @param T $entity + * @param TEntityInstance $entity */ protected function saveEntity($entity): void { diff --git a/src/Session/MysqlSession.php b/src/Session/MysqlSession.php index 8d0eeb5..0c4c2a1 100644 --- a/src/Session/MysqlSession.php +++ b/src/Session/MysqlSession.php @@ -303,7 +303,7 @@ protected function calculateHash(): string /** * @throws ErrorException */ - protected function getLock($session_id): bool + protected function getLock(string $session_id): bool { $this->session_lock = 'session_'.$session_id; diff --git a/src/Sitemap/SitemapParser.php b/src/Sitemap/SitemapParser.php index 19c071d..5e9810f 100644 --- a/src/Sitemap/SitemapParser.php +++ b/src/Sitemap/SitemapParser.php @@ -16,8 +16,14 @@ use function simplexml_import_dom; use function sprintf; +/** + * @phpstan-type TSitemapEntry array{lastmod: string|null, changefreq: string|null, priority: string|null} + */ class SitemapParser { + /** + * @return array + */ public static function parse(string $sitemap): array { $doc = self::validateSitemapXML($sitemap); diff --git a/src/Sitemap/SitemapRenderer.php b/src/Sitemap/SitemapRenderer.php index c6f6ba4..e776113 100644 --- a/src/Sitemap/SitemapRenderer.php +++ b/src/Sitemap/SitemapRenderer.php @@ -13,6 +13,9 @@ class SitemapRenderer { + /** + * @var list + */ private array $urls = []; private bool $is_rendered = false; diff --git a/src/StringEncoding/JSON.php b/src/StringEncoding/JSON.php index ed3637f..e3a488d 100644 --- a/src/StringEncoding/JSON.php +++ b/src/StringEncoding/JSON.php @@ -23,6 +23,9 @@ public static function decode(?string $json): mixed } } + /** + * @return array + */ public static function decodeArray(string $json): array { $value = static::decode($json); @@ -37,7 +40,7 @@ public static function decodeArray(string $json): array * @param bool $escaped_slashes defaults true to match the PHP default */ public static function encode( - $value, + mixed $value, bool $pretty = true, bool $escaped_slashes = true, ): string { diff --git a/src/Validation/StrictDate.php b/src/Validation/StrictDate.php index e14657a..9d175ad 100644 --- a/src/Validation/StrictDate.php +++ b/src/Validation/StrictDate.php @@ -19,6 +19,8 @@ class StrictDate /** * Validate that value of one field is a date after the value of another. * + * @param ArrayAccess $validation + * * @deprecated validate input before creating DateTimeImmutable objects */ public static function date_after(ArrayAccess $validation, string $from_field, string $to_field): bool @@ -37,6 +39,8 @@ 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 + * * @deprecated validate input before creating DateTimeImmutable objects */ public static function date_on_or_after(ArrayAccess $validation, string $from_field, string $to_field): bool diff --git a/test/unit/ArrayHelpers/AssociativeArrayUtilsTest.php b/test/unit/ArrayHelpers/AssociativeArrayUtilsTest.php index af2160f..ac8e6e6 100644 --- a/test/unit/ArrayHelpers/AssociativeArrayUtilsTest.php +++ b/test/unit/ArrayHelpers/AssociativeArrayUtilsTest.php @@ -18,10 +18,11 @@ final class AssociativeArrayUtilsTest extends TestCase { + /** @param array $array */ #[TestWith([['one', 'two', 'three'], false])] #[TestWith([[1 => 'mixed indices', 5 => 'also mixed'], true])] #[TestWith([['one' => 'o clock', 'two' => 'o clock', 'three' => 'o clock'], true])] - public function testIsAssociative(array $array, $expected): void + public function testIsAssociative(array $array, bool $expected): void { $this->assertSame( $expected, @@ -56,6 +57,10 @@ public static function provider_paths_to_nested(): Iterator ]; } + /** + * @param array $input + * @param array $expect + */ #[DataProvider('provider_paths_to_nested')] public function testItConvertsPathedHashToNestedArrays(array $input, array $expect): void { @@ -94,6 +99,11 @@ public static function provider_pop_keys(): Iterator ]; } + /** + * @param array $source + * @param list $pop_keys + * @param array $expect + */ #[DataProvider('provider_pop_keys')] public function testItCanPopKeysFromASourceArray(array $source, array $pop_keys, array $expect): void { @@ -125,8 +135,12 @@ public static function provider_set_path(): Iterator yield [['kohana' => ['is' => 'awesome']], [], ['kohana', 'is'], 'awesome']; } + /** + * @param array $expected + * @param array $array + */ #[DataProvider('provider_set_path')] - public function testSetPath(array $expected, array $array, ...$args): void + public function testSetPath(array $expected, array $array, mixed ...$args): void { AssociativeArrayUtils::setPath($array, ...$args); @@ -261,8 +275,9 @@ public static function provider_merge(): Iterator ]; } + /** @param array $expected */ #[DataProvider('provider_merge')] - public function testDeepMerge(array $expected, ...$args): void + public function testDeepMerge(array $expected, mixed ...$args): void { $this->assertSame( $expected, diff --git a/test/unit/Assets/StaticAssetUrlProviderTest.php b/test/unit/Assets/StaticAssetUrlProviderTest.php index 74febb3..d567896 100644 --- a/test/unit/Assets/StaticAssetUrlProviderTest.php +++ b/test/unit/Assets/StaticAssetUrlProviderTest.php @@ -46,7 +46,7 @@ public function testInLocalModeGetUrlThrowsIfFileDoesNotExist(): void #[TestWith(['assets/my-file.css'])] #[TestWith(['/assets/my-file.css'])] - public function testInLocalModeGetUrlReturnsAbsoluteUrlWithMtimeSuffix($rel_path): void + public function testInLocalModeGetUrlReturnsAbsoluteUrlWithMtimeSuffix(string $rel_path): void { $dir = $this->vfs->getChild('docroot'); $this->assertInstanceOf(vfsStreamDirectory::class, $dir); @@ -78,7 +78,7 @@ public function testInRemoteModeGetUrlThrowsIfAssetBaseUrlFileDoesNotExist(): vo #[TestWith(['some content that is not php'])] #[TestWith([' $file_content], @@ -94,7 +94,7 @@ public function testInRemoteModeGetUrlThrowsIfAssetBaseUrlFileDoesNotReturnStrin #[TestWith(['assets/my-file.css'])] #[TestWith(['/assets/my-file.css'])] - public function testItRemoteModeGetUrlReturnsUrlPrefixedWithBaseUrl($rel_path): void + public function testItRemoteModeGetUrlReturnsUrlPrefixedWithBaseUrl(string $rel_path): void { vfsStream::create( ['asset-base-url.php' => ' $row + * @param array $options + */ #[DataProvider('providerQuotedHeaders')] public function testItOptionallyWritesColumnHeadersWithoutQuotes(array $row, array $options, string $expect): void { @@ -229,6 +233,7 @@ public static function providerLineEndings(): Iterator ]; } + /** @param array $options */ #[DataProvider('providerLineEndings')] public function testItsLineEndingsCanBeConfigured(array $options, string $expect): void { @@ -243,7 +248,7 @@ public function testItsLineEndingsCanBeConfigured(array $options, string $expect #[TestWith([true])] #[TestWith([false])] - public function testItOptionallyWritesByteOrderMarkAtStartOfFile($write_bom): void + public function testItOptionallyWritesByteOrderMarkAtStartOfFile(bool $write_bom): void { $file = fopen('php://memory', 'w'); $subj = $this->newSubject(); @@ -256,9 +261,10 @@ public function testItOptionallyWritesByteOrderMarkAtStartOfFile($write_bom): vo $this->assertSame(['first'], fgetcsv($file, escape: '\\')); } + /** @param array $second_row */ #[TestWith([['is' => 'jumbled', 'our' => 'up']])] #[TestWith([['our' => 'things', 'went' => 'bad']])] - public function testItThrowsIfSubsequentRowHeadersDoNotMatch($second_row): void + public function testItThrowsIfSubsequentRowHeadersDoNotMatch(array $second_row): void { $file = fopen('php://memory', 'w'); try { @@ -285,6 +291,10 @@ public function testItDoesNotCloseExternallyProvidedStream(): void } } + /** + * @param array> $expect + * @param resource $file + */ protected function assertCSVContent(array $expect, $file): void { rewind($file); diff --git a/test/unit/Cookie/ArrayCookieWrapperStubTest.php b/test/unit/Cookie/ArrayCookieWrapperStubTest.php index 8fdc076..128a8e4 100644 --- a/test/unit/Cookie/ArrayCookieWrapperStubTest.php +++ b/test/unit/Cookie/ArrayCookieWrapperStubTest.php @@ -15,9 +15,9 @@ final class ArrayCookieWrapperStubTest extends TestCase #[TestWith(['has', true, 'values'])] #[TestWith(['anything', false, null])] public function testItHasCookiesFromConstructorIgnoringSuperglobal( - $name, - $expect_has, - $expect_val, + string $name, + bool $expect_has, + ?string $expect_val, ): void { $old_cookie = $_COOKIE; try { @@ -59,6 +59,7 @@ public function testItCanSimulateSetCookieAndCaptureArgs(): void ); } + /** @param array $cookies */ protected function newSubject(array $cookies = []): ArrayCookieWrapperStub { return new ArrayCookieWrapperStub($cookies); diff --git a/test/unit/Cookie/CookieWrapperTest.php b/test/unit/Cookie/CookieWrapperTest.php index c1b8408..ce9a67b 100644 --- a/test/unit/Cookie/CookieWrapperTest.php +++ b/test/unit/Cookie/CookieWrapperTest.php @@ -12,14 +12,15 @@ final class CookieWrapperTest extends TestCase { + /** @var array */ private array $_old_cookie_var; - private $ssl_available = true; + private bool $ssl_available = true; #[TestWith(['my', true, 'cookie'])] #[TestWith(['has', true, 'values'])] #[TestWith(['anything', false, null])] - public function testItHasCookiesFromSuperglobal($name, $expect_has, $expect_val): void + public function testItHasCookiesFromSuperglobal(string $name, bool $expect_has, ?string $expect_val): void { $_COOKIE = ['my' => 'cookie', 'has' => 'values']; $subject = $this->newSubject(); @@ -135,10 +136,11 @@ public function testItCanSetExpiresFromDatetimeImmutable(): void ); } + /** @param array $opts */ #[TestWith([['secure' => true], false])] #[TestWith([['secure' => false], false])] #[TestWith([[], false])] - public function testItDowngradesSecureCookiesWhenNoSslAvailable($opts, $expect): void + public function testItDowngradesSecureCookiesWhenNoSslAvailable(array $opts, bool $expect): void { $this->ssl_available = false; $subject = $this->newSubject(); @@ -147,11 +149,12 @@ public function testItDowngradesSecureCookiesWhenNoSslAvailable($opts, $expect): $this->assertSame($expect, $subject->setcookie_calls[0]['options']['secure']); } + /** @param array $opts */ #[TestWith([true, [], null])] #[TestWith([true, ['samesite' => 'Lax'], 'Lax'])] #[TestWith([true, ['samesite' => 'None'], 'None'])] #[TestWith([false, ['samesite' => 'None'], null])] - public function testItAddsSamesiteAttributeOnlyIfSslAvailable($has_ssl, $opts, $expect): void + public function testItAddsSamesiteAttributeOnlyIfSslAvailable(bool $has_ssl, array $opts, ?string $expect): void { $this->ssl_available = $has_ssl; $subject = $this->newSubject(); @@ -217,13 +220,17 @@ protected function newSubject(): TestableCookieWrapper class TestableCookieWrapper extends CookieWrapper { + /** @var list}> */ public $setcookie_calls = []; + + /** @var false|array{file: string, line: int} */ public $headers_sent = false; + /** @param array $options */ protected function set_cookie( - $name, - $value, - $options, + string $name, + ?string $value, + array $options, ): void { $this->setcookie_calls[] = [ 'name' => $name, @@ -232,7 +239,7 @@ protected function set_cookie( ]; } - protected function headers_sent(&$file, &$line): bool + protected function headers_sent(?string &$file = null, ?int &$line = null): bool { if ($this->headers_sent === false) { return false; diff --git a/test/unit/Database/Doctrine2TransactionWrapperTest.php b/test/unit/Database/Doctrine2TransactionWrapperTest.php index eaa1957..0332050 100644 --- a/test/unit/Database/Doctrine2TransactionWrapperTest.php +++ b/test/unit/Database/Doctrine2TransactionWrapperTest.php @@ -65,7 +65,7 @@ private function newSubject(): Doctrine2TransactionWrapper */ class StubEntityManager { - public function transactional($func) + public function transactional(callable $func): mixed { return $func(); } diff --git a/test/unit/DateTime/Clock/StoppedMockClockTest.php b/test/unit/DateTime/Clock/StoppedMockClockTest.php index 5ca60ae..ea229e5 100644 --- a/test/unit/DateTime/Clock/StoppedMockClockTest.php +++ b/test/unit/DateTime/Clock/StoppedMockClockTest.php @@ -155,6 +155,7 @@ function (StoppedMockClock $clock): void { ]; } + /** @param list $expected */ #[DataProvider('provider_assert_slept_fails')] public function testAssertSleptFailsIfNotSleptForExpectedIntervals(Closure $callback, array $expected, string $msg): void { diff --git a/test/unit/DateTime/DateTimeImmutableFactoryTest.php b/test/unit/DateTime/DateTimeImmutableFactoryTest.php index db90d45..c498fa2 100644 --- a/test/unit/DateTime/DateTimeImmutableFactoryTest.php +++ b/test/unit/DateTime/DateTimeImmutableFactoryTest.php @@ -26,7 +26,7 @@ final class DateTimeImmutableFactoryTest extends TestCase { #[TestWith(['2017-07-09 10:01:02', '2017-07-09T10:01:02.000000+01:00'])] - public function testItFactoriesCorrectObjectFromValidYmdhisInDefaultTz($input, $expect): void + public function testItFactoriesCorrectObjectFromValidYmdhisInDefaultTz(string $input, string $expect): void { $old_default = date_default_timezone_get(); try { @@ -46,7 +46,7 @@ public function testItFactoriesCorrectObjectFromValidYmdhisInDefaultTz($input, $ #[TestWith(['2017-11-10 26:10:10'])] #[TestWith(['2017-14-10'])] #[TestWith(['10/11/2017'])] - public function testItThrowsFromInvalidYmdhisInput($input): void + public function testItThrowsFromInvalidYmdhisInput(string $input): void { $this->expectException(InvalidArgumentException::class); DateTimeImmutableFactory::fromYmdHis($input); @@ -70,7 +70,7 @@ public function testItFactoriesFromUnixTimestampInDefaultTz(): void #[TestWith([1274437650, '2010-05-21T11:27:30.000000+01:00'])] #[TestWith([1274437650, '2010-05-21T11:27:30.000000+01:00'])] #[TestWith([1274437650.0, '2010-05-21T11:27:30.000000+01:00'])] - public function testItFactoriesFromMicrotimeInDefaultTz($val, $expect): void + public function testItFactoriesFromMicrotimeInDefaultTz(int|float|string $val, string $expect): void { try { $old_default = date_default_timezone_get(); diff --git a/test/unit/DeploymentConfig/ConfigMapDeclarationParserTest.php b/test/unit/DeploymentConfig/ConfigMapDeclarationParserTest.php index e10c1bf..a352b98 100644 --- a/test/unit/DeploymentConfig/ConfigMapDeclarationParserTest.php +++ b/test/unit/DeploymentConfig/ConfigMapDeclarationParserTest.php @@ -85,6 +85,7 @@ public function testItThrowsIfAnEnvironmentMappedMoreThanOnce(): void ); } + /** @return array> */ public static function provider_invalid_declarations(): array { // Compose like this because by the time you nest the different levels of data provider cases and argument arrays @@ -114,7 +115,7 @@ public static function provider_invalid_declarations(): array } #[DataProvider('provider_invalid_declarations')] - public function testItThrowsIfAnyDeclarationsDoNotHaveExactlyTwoValues($declarations): void + public function testItThrowsIfAnyDeclarationsDoNotHaveExactlyTwoValues(mixed $declarations): void { $subject = $this->newSubject(); $this->expectException(InvalidConfigException::class); diff --git a/test/unit/DeploymentConfig/ConfigValueDecrypterTest.php b/test/unit/DeploymentConfig/ConfigValueDecrypterTest.php index 091cabb..7f8948e 100644 --- a/test/unit/DeploymentConfig/ConfigValueDecrypterTest.php +++ b/test/unit/DeploymentConfig/ConfigValueDecrypterTest.php @@ -8,6 +8,7 @@ use Ingenerator\PHPUtils\DeploymentConfig\InvalidConfigException; use Iterator; use org\bovigo\vfs\vfsStream; +use org\bovigo\vfs\vfsStreamDirectory; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use PHPUnit\Framework\TestCase; @@ -17,7 +18,7 @@ final class ConfigValueDecrypterTest extends TestCase { - private $vfs; + private vfsStreamDirectory $vfs; public function testItIsInitialisable(): void { @@ -29,7 +30,7 @@ public function testItIsInitialisable(): void #[TestWith([1.29])] #[TestWith(['anything'])] #[TestWith([['any' => 'thing', 'other' => ['things' => 'here']]])] - public function testItReturnsUnchangedValueIfNotEncrypted($value): void + public function testItReturnsUnchangedValueIfNotEncrypted(mixed $value): void { $this->assertSame($value, $this->newSubject()->decrypt($value)); } @@ -74,6 +75,7 @@ public static function provider_decrypt(): Iterator ]; } + /** @param array $keypairs */ #[DataProvider('provider_decrypt')] public function testItReturnsValueDecryptedWithSpecifiedOrDefaultKey(string $value, string $expect, array $keypairs): void { diff --git a/test/unit/DeploymentConfig/DeploymentConfigTest.php b/test/unit/DeploymentConfig/DeploymentConfigTest.php index 309f634..e1ac38c 100644 --- a/test/unit/DeploymentConfig/DeploymentConfigTest.php +++ b/test/unit/DeploymentConfig/DeploymentConfigTest.php @@ -101,6 +101,7 @@ public static function provider_is_current_env(): Iterator yield [DeploymentConfig::DEV, ['junk-env'], false]; } + /** @param list $args */ #[DataProvider('provider_is_current_env')] public function testItsIsEnvironmentReturnsWhetherCurrentEnvironmentOneOfThoseListed( string $env, @@ -112,6 +113,7 @@ public function testItsIsEnvironmentReturnsWhetherCurrentEnvironmentOneOfThoseLi $this->assertSame($expect, $result); } + /** @param list $args */ #[DataProvider('provider_is_current_env')] public function testItsNotEnvironmentReturnsWhetherCurrentEnvironmentNoneOfThoseListed( string $env, @@ -130,7 +132,7 @@ public function testItsNotEnvironmentReturnsWhetherCurrentEnvironmentNoneOfThose #[TestWith(['ci', null])] #[TestWith(['imagined', 'who-knows-what-i-am'])] #[TestWith(['standalone', 'i-am-standalone'])] - public function testItsMapReturnsValueOrDefaultForTheCurrentEnv($env, $expect): void + public function testItsMapReturnsValueOrDefaultForTheCurrentEnv(string $env, ?string $expect): void { $subject = $this->newSubjectWithEnv($env); $this->assertSame( @@ -148,7 +150,7 @@ public function testItsMapReturnsValueOrDefaultForTheCurrentEnv($env, $expect): #[TestWith(['dev'])] #[TestWith(['standalone'])] #[TestWith(['ci'])] - public function testItsMapReturnsAnyForEnvThatIsNotDefined($env): void + public function testItsMapReturnsAnyForEnvThatIsNotDefined(string $env): void { $subject = $this->newSubjectWithEnv($env); $this->assertSame( @@ -243,7 +245,7 @@ public function testItsReadJsonAlwaysReturnsNullInStandalone(): void #[TestWith(['string', 'string'])] #[TestWith([1234, 1234])] #[TestWith([1234.5, 1234.5])] - public function testItsReadJsonReturnsJsonDecodedFileContentIfPresentOutsideStandalone($json, $expect): void + public function testItsReadJsonReturnsJsonDecodedFileContentIfPresentOutsideStandalone(mixed $json, mixed $expect): void { $path = $this->givenConfigDirWithFile('config/some_scalar', json_encode($json)); $subject = $this->newSubjectWithEnvAndConfigDir( diff --git a/test/unit/Encryption/CryptoBox/CryptoBoxKeypairTest.php b/test/unit/Encryption/CryptoBox/CryptoBoxKeypairTest.php index 543e862..21ef377 100644 --- a/test/unit/Encryption/CryptoBox/CryptoBoxKeypairTest.php +++ b/test/unit/Encryption/CryptoBox/CryptoBoxKeypairTest.php @@ -38,7 +38,7 @@ public function testItCanBeGeneratedAsANewKeypairAndUsedToDecrypt(): void #[TestWith(['multi words'])] #[TestWith([''])] #[TestWith(['Whoopdedo!'])] - public function testItCannotBeCreatedWithKeypairIdInInvalidFormat($key_id): void + public function testItCannotBeCreatedWithKeypairIdInInvalidFormat(string $key_id): void { $this->expectException(InvalidArgumentException::class); CryptoBoxKeypair::generate($key_id); diff --git a/test/unit/Logging/DefaultLogMetadataTest.php b/test/unit/Logging/DefaultLogMetadataTest.php index 2165cef..565faa8 100644 --- a/test/unit/Logging/DefaultLogMetadataTest.php +++ b/test/unit/Logging/DefaultLogMetadataTest.php @@ -26,26 +26,29 @@ public function testItsDeviceIdentityProvidesDeviceIdAsDeferredValue(): void $this->assertSame(['context' => ['did' => 'abc4567890123456789012']], $result()); } + /** @param array $server */ #[TestWith([['REMOTE_ADDR' => '192.182.382.39'], '192.182.382.39'])] #[TestWith([[], '{na}'])] - public function testItsHttpContextProvidesClientIpFromServerVars($server, $expect): void + public function testItsHttpContextProvidesClientIpFromServerVars(array $server, string $expect): void { $result = DefaultLogMetadata::httpContext($server); $this->assertSame($expect, $result['context']['httpRequest']['remoteIp']); } + /** @param array $server */ #[TestWith([['REQUEST_URI' => '/foobar/foo'], '/foobar/foo'])] #[TestWith([['REQUEST_URI' => '/foobar/foo?arg=what'], '/foobar/foo?arg=what'])] #[TestWith([[], null])] - public function testItsHttpContextProvidesRequestUrlFromServerVars($server, $expect): void + public function testItsHttpContextProvidesRequestUrlFromServerVars(array $server, ?string $expect): void { $result = DefaultLogMetadata::httpContext($server); $this->assertSame($expect, $result['context']['httpRequest']['requestUrl']); } + /** @param array $server */ #[TestWith([['REQUEST_METHOD' => 'POST'], 'POST'])] #[TestWith([[], null])] - public function testItsHttpContextProvidesRequestMethodFromServerVars($server, $expect): void + public function testItsHttpContextProvidesRequestMethodFromServerVars(array $server, ?string $expect): void { $result = DefaultLogMetadata::httpContext($server); $this->assertSame($expect, $result['context']['httpRequest']['requestMethod']); @@ -114,6 +117,7 @@ public static function provider_trace_header(): Iterator ]; } + /** @param array $server */ #[DataProvider('provider_trace_header')] public function testItsRequestTracingDataAddsTraceIdWithFromHeaderAndOptionallyProjectIfAvailable( array $server, @@ -144,7 +148,7 @@ public function testItsServiceContextProvidesServiceName(): void #[TestWith([" $cookie */ #[TestWith([['did' => 'OfLAtnofliaNqvkAjhhsFA']])] #[TestWith([['didf' => 'OfLAtnofliaNqvkAjhhsFA']])] - public function testItsInitDoesNotSetNewCookieIfEitherCookiePresent($cookie): void + public function testItsInitDoesNotSetNewCookieIfEitherCookiePresent(array $cookie): void { $this->cookies = new ArrayCookieWrapperStub($cookie); $this->newSubject()->init(); @@ -48,10 +50,13 @@ public function testItsInitUsesValueAndDeletesFallbackIfBothCookiesPresent(): vo ); } + /** + * @param array $cookie + */ #[TestWith([[]])] #[TestWith([['did' => "i am an abusive person!!! \$\$@@~~##''\$\$\$"]])] #[TestWith([['did' => '', 'didf' => '']])] - public function testItsInitSetsNewCookiesIfNotPresentOrNotValid($cookie): void + public function testItsInitSetsNewCookiesIfNotPresentOrNotValid(array $cookie): void { $this->cookies = new ArrayCookieWrapperStub($cookie); @@ -111,6 +116,9 @@ public function testItSetsOneCookieAsSamesiteNoneAndFallbackWithout(): void ); } + /** + * @param array $cookie + */ #[TestWith([[], '-unset-'])] #[TestWith([['did' => ''], '-unset-'])] #[TestWith([['didf' => ''], '-unset-'])] @@ -119,8 +127,8 @@ public function testItSetsOneCookieAsSamesiteNoneAndFallbackWithout(): void #[TestWith([['did' => 'OfLAtnofliaNqvkAjhhsFA', 'didf' => 'OfLAtnofliaNqvkAjhhsFA'], 'OfLAtnofliaNqvkAjhhsFA'])] #[TestWith([['did' => "i am an abusive person!!! \$\$@@~~##''\$\$\$"], '-invalid-'])] public function testItsGetterReturnsValidCookieValueOrUnsetIfInitialisedNeverCalled( - $cookie, - $expect, + array $cookie, + string $expect, ): void { $this->cookies = new ArrayCookieWrapperStub($cookie); $this->assertSame($expect, $this->newSubject()->getValue()); @@ -209,12 +217,12 @@ protected function setUp(): void $this->cookies = new ArrayCookieWrapperStub(); } - protected function newSubject() + protected function newSubject(): DeviceIdentifier { return ScopeChangingCaller::call( DeviceIdentifier::class, /** @phpstan-ignore new.protectedConstructor (intentional modification of state to reset singleton) */ - fn ($cookies): DeviceIdentifier => new DeviceIdentifier($cookies), + fn (CookieWrapper $cookies): DeviceIdentifier => new DeviceIdentifier($cookies), $this->cookies ); } diff --git a/test/unit/Logging/ExternalCallSiteFinderTest.php b/test/unit/Logging/ExternalCallSiteFinderTest.php index a78a5ae..c9f1cd7 100644 --- a/test/unit/Logging/ExternalCallSiteFinderTest.php +++ b/test/unit/Logging/ExternalCallSiteFinderTest.php @@ -231,16 +231,19 @@ protected function newSubject(): ExternalCallSiteFinder class TestCallsiteCaller extends TestCallSiteCallerParent { + /** @return array */ public function singleExternal(ExternalCallSiteFinder $finder): array { return $finder->findExternalCall(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 5), [static::class]); } + /** @return array */ public function throughInternalMethod(ExternalCallSiteFinder $finder): array { return $this->singleExternal($finder); } + /** @return array */ public function fromManager(ExternalCallSiteFinder $finder): array { return $finder->findExternalCall( @@ -255,9 +258,11 @@ public function fromManager(ExternalCallSiteFinder $finder): array abstract class TestCallSiteCallerParent { - abstract public function singleExternal(ExternalCallSiteFinder $finder); + /** @return array */ + abstract public function singleExternal(ExternalCallSiteFinder $finder): array; - public function throughParentMethod(ExternalCallSiteFinder $finder) + /** @return array */ + public function throughParentMethod(ExternalCallSiteFinder $finder): array { return $this->singleExternal($finder); } @@ -265,6 +270,7 @@ public function throughParentMethod(ExternalCallSiteFinder $finder) class TestCallSiteProxy { + /** @return array */ public function throughExpectedDependency(ExternalCallSiteFinder $finder): array { $caller = new TestCallsiteCaller(); @@ -280,6 +286,8 @@ public function __construct(private readonly ExternalCallSiteFinder $finder) } /** + * @param array $expected + * * @return array */ public function test(array $expected): array diff --git a/test/unit/Logging/StackdriverApplicationLoggerTest.php b/test/unit/Logging/StackdriverApplicationLoggerTest.php index 29bae01..8c49935 100644 --- a/test/unit/Logging/StackdriverApplicationLoggerTest.php +++ b/test/unit/Logging/StackdriverApplicationLoggerTest.php @@ -12,6 +12,7 @@ use Ingenerator\PHPUtils\StringEncoding\JSON; use InvalidArgumentException; use org\bovigo\vfs\vfsStream; +use org\bovigo\vfs\vfsStreamDirectory; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use PHPUnit\Framework\TestCase; @@ -38,10 +39,11 @@ final class StackdriverApplicationLoggerTest extends TestCase { - private $vfs; + private vfsStreamDirectory $vfs; private string $log_stream; + /** @var array */ private array $meta_args = []; public function testItIsInitialisable(): void @@ -78,6 +80,7 @@ public static function provider_log_lines(): array ]; } + /** @param list $messages */ #[DataProvider('provider_log_lines')] public function testItLogsToSpecifiedLocationAsJsonLineWithExpectedMessage(array $messages): void { @@ -87,7 +90,7 @@ public function testItLogsToSpecifiedLocationAsJsonLineWithExpectedMessage(array } $entries = $this->assertLoggedJSONLines(); - $actual = array_map(fn (array $msg) => $msg['message'], $entries); + $actual = array_map(fn (array $msg): mixed => $msg['message'], $entries); $this->assertSame($messages, $actual, 'Expect correct log messages'); } @@ -215,14 +218,15 @@ function () use (&$call_site, &$call_count): array { public function testItCanLazilyRetrieveMetadataFromProviderClass(): void { $meta_provider_class = new class implements LogMetadataProvider { - protected $call_count = 0; + protected int $call_count = 0; + /** @return array */ public function getMetadata(): array { return ['context' => ['call_count' => ++$this->call_count]]; } - public function getCallCount() + public function getCallCount(): int { return $this->call_count; } @@ -263,6 +267,7 @@ public function testItSwallowsAndLogsAnyErrorsWhileRetrievingMetadataCallbacks() function (): never { throw new InvalidArgumentException('Broken'); }, ['sources' => ['fifth_ok']], new class implements LogMetadataProvider { + /** @return array */ public function getMetadata(): array { throw new BadMethodCallException('The class broke'); @@ -296,18 +301,20 @@ public function getMetadata(): array ); } + /** @param array $context */ #[TestWith([[], 'app'])] #[TestWith([['@ingenType' => 'rqst'], 'rqst'])] - public function testItAssignsIngeneratorTypeUnlessOverridden($context, $expect_type): void + public function testItAssignsIngeneratorTypeUnlessOverridden(array $context, string $expect_type): void { $this->newSubject()->warning('Anything', $context); $entry = $this->assertLoggedOneLine(); $this->assertSame($expect_type, $entry['@ingenType']); } + /** @param list $args */ #[TestWith(['log', ['info', 'Some info']])] #[TestWith(['info', ['Some info']])] - public function testItLogsWithSourceLocationAsImmediateCaller($log_method, $args): void + public function testItLogsWithSourceLocationAsImmediateCaller(string $log_method, array $args): void { $expect_line = __LINE__ + 1; call_user_func_array([$this->newSubject(), $log_method], $args); @@ -426,6 +433,7 @@ public static function provider_exception_chains(): array ]; } + /** @param array $expect */ #[DataProvider('provider_exception_chains')] public function testItRecursivelyFormatsExceptionChainAsStructsWithTraceExcludingArgs(InvalidArgumentException|TypeError $e, array $expect): void { @@ -563,7 +571,7 @@ public function testItsRequestLoggerHoistsHttpMetadataToTopLevel(): void #[TestWith(['message'])] #[TestWith(['logging.googleapis.com/sourceLocation'])] - public function testItsRequestLoggerDoesNotLogIrrelevantProperties($prop): void + public function testItsRequestLoggerDoesNotLogIrrelevantProperties(string $prop): void { $this->newSubject()->logRequest([]); $entry = $this->assertLoggedOneLine(); @@ -592,13 +600,14 @@ public function testItsRequestLoggerLogsHttpResponseCode(): void $this->assertSame(402, $entry['httpRequest']['status']); } + /** @param array $server */ #[TestWith([[], ''])] #[TestWith([['HTTP_USER_AGENT' => 'chrome 10'], 'chrome 10'])] #[TestWith([ ['HTTP_USER_AGENT' => "Mozilla/5.0 (compatible; Baiduspider/2.0; \xa3\xa9 and more stuff"], 'Mozilla/5.0 (compatible; Baiduspider/2.0; �� and more stuff', ])] - public function testItsRequestLoggerLogsUserAgentFromGlobalArray($server, $expect): void + public function testItsRequestLoggerLogsUserAgentFromGlobalArray(array $server, string $expect): void { http_response_code(402); $logger = $this->newSubject(); @@ -660,6 +669,7 @@ public function testItsRequestLoggerLogsPeakMemoryUsageInMb(): void ); } + /** @return list> */ protected function assertLoggedJSONLines(): array { if (!is_file($this->log_stream)) { @@ -676,6 +686,7 @@ protected function assertLoggedJSONLines(): array ); } + /** @return array */ protected function assertLoggedOneLine(): array { $entries = $this->assertLoggedJSONLines(); diff --git a/test/unit/Mutex/BasicPDOStatementStub.php b/test/unit/Mutex/BasicPDOStatementStub.php index 076b12b..8dd681d 100644 --- a/test/unit/Mutex/BasicPDOStatementStub.php +++ b/test/unit/Mutex/BasicPDOStatementStub.php @@ -10,13 +10,16 @@ class BasicPDOStatementStub extends PDOStatement { + /** @var array */ protected $result; + /** @param array $result */ public function __construct(array $result) { $this->result = $result; } + /** @return array */ public function fetchAll(?int $mode = null, mixed ...$fetch_argument): array { if ($mode === null) { diff --git a/test/unit/Mutex/BasicPDOStub.php b/test/unit/Mutex/BasicPDOStub.php index 5cbac60..a5bbd65 100644 --- a/test/unit/Mutex/BasicPDOStub.php +++ b/test/unit/Mutex/BasicPDOStub.php @@ -8,8 +8,10 @@ class BasicPDOStub extends PDO { + /** @var list}> */ protected $query_stack = []; + /** @param list}> $stack */ public static function withQueryStack(array $stack): self { $i = new self(); @@ -27,8 +29,11 @@ public function quote($string, $type = PDO::PARAM_STR): string|false return '{quoted-'.$string.'}'; } - public function query($statement, $mode = PDO::ATTR_DEFAULT_FETCH_MODE, ...$fetch_mode_args): PDOStatement|false - { + public function query( + string $statement, + ?int $mode = PDO::ATTR_DEFAULT_FETCH_MODE, + mixed ...$fetch_mode_args, + ): PDOStatement|false { Assert::assertNotEmpty($this->query_stack, 'No expectation defined for query '.$statement); $next_query = array_shift($this->query_stack); Assert::assertSame($next_query['sql'], $statement); diff --git a/test/unit/Object/ConstantDirectoryTest.php b/test/unit/Object/ConstantDirectoryTest.php index 11f364a..1614269 100644 --- a/test/unit/Object/ConstantDirectoryTest.php +++ b/test/unit/Object/ConstantDirectoryTest.php @@ -62,7 +62,7 @@ public function testItReturnsListOfConstantsWithPrefix(): void ); } - protected function newSubject($class = self::class): ConstantDirectory + protected function newSubject(string $class = self::class): ConstantDirectory { return ConstantDirectory::forClass($class); } diff --git a/test/unit/Object/ObjectPropertyPopulatorTest.php b/test/unit/Object/ObjectPropertyPopulatorTest.php index 0c2ff43..63931b9 100644 --- a/test/unit/Object/ObjectPropertyPopulatorTest.php +++ b/test/unit/Object/ObjectPropertyPopulatorTest.php @@ -55,10 +55,11 @@ public function testItThrowsIfAssigningUnknownProperty(): void class TestPopulatingClass { /* @phpstan-ignore property.onlyRead (written by the populator in tests) */ - private $something_private; - protected $something_protected; - protected $already_init = 'Foo'; + private mixed $something_private; + protected mixed $something_protected; + protected string $already_init = 'Foo'; + /** @return array */ public function toArray(): array { return get_object_vars($this); diff --git a/test/unit/Object/ObjectPropertyRipperTest.php b/test/unit/Object/ObjectPropertyRipperTest.php index 3e2a754..444b0d6 100644 --- a/test/unit/Object/ObjectPropertyRipperTest.php +++ b/test/unit/Object/ObjectPropertyRipperTest.php @@ -101,8 +101,8 @@ class TestRippingClass { /* @phpstan-ignore property.onlyWritten (read by the ripper in tests) */ private string $something_private = 'precious'; - protected $something_protected = 'water'; - protected $something_else = 'else'; + protected string $something_protected = 'water'; + protected string $something_else = 'else'; } class ExtensionRippingClass extends TestRippingClass diff --git a/test/unit/Random/ConsistentStringScramblerTest.php b/test/unit/Random/ConsistentStringScramblerTest.php index b18ff67..32598ae 100644 --- a/test/unit/Random/ConsistentStringScramblerTest.php +++ b/test/unit/Random/ConsistentStringScramblerTest.php @@ -35,7 +35,7 @@ public function testItReturnsNullForEmptyString(): void Foo '])] public function testItReturnsSameOutputForSingleWordStringEvenWithExtraWhitespace( - $input, + string $input, ): void { $this->assertSame('Foo', $this->newSubject()->shuffleWords($input, 'any')); } @@ -74,7 +74,7 @@ public function testItProducesDifferentShuffledWordsForDifferentHashInput(): voi spake Zarathustra ', 'spake Zarathustra Thus!'])] #[TestWith([' 51 Niddry St ', 'Niddry St 51'])] - public function testItStripsRepeatedAndEnclosingWhitespaceInIncomingString($input, $expect): void + public function testItStripsRepeatedAndEnclosingWhitespaceInIncomingString(string $input, string $expect): void { $this->assertSame($expect, $this->newSubject()->shuffleWords($input, 'any-hash')); } diff --git a/test/unit/Repository/AbstractArrayRepositoryTest.php b/test/unit/Repository/AbstractArrayRepositoryTest.php index 1326dee..c3521a9 100644 --- a/test/unit/Repository/AbstractArrayRepositoryTest.php +++ b/test/unit/Repository/AbstractArrayRepositoryTest.php @@ -61,14 +61,18 @@ public function testItIsInitialisableWithListOfMultipleEntities(): void $this->assertSame([$e1, $e2], $subject->getEntities()); } + /** + * @param list> $entities + * @param array $expect + */ #[TestWith([[], []])] #[TestWith([[['prop1' => 'foo'], ['prop1' => 'bar'], ['prop1' => 'foo']], ['foo' => 2, 'bar' => 1]])] - public function testItProvidesBaseLayerForCountingEntitiesByGroup($entities, $expect): void + public function testItProvidesBaseLayerForCountingEntitiesByGroup(array $entities, array $expect): void { $subject = AnyArrayRepository::withList($entities); $this->assertSame( $expect, - $subject->countWith(fn (AnyEntity $e) => $e->getProp1()) + $subject->countWith(fn (AnyEntity $e): mixed => $e->getProp1()) ); } @@ -115,15 +119,19 @@ public function testItsFindWithThrowsIfEntityNotUnique(): void $subject->findWith(fn (AnyEntity $e): true => true); } + /** + * @param list> $entities + * @param list $expect + */ #[TestWith([[], []])] #[TestWith([[['prop1' => 'ok', 'prop2' => 0], ['prop1' => 'nah-ah', 'prop2' => 1], ['prop1' => 'ok', 'prop2' => 2]], [0, 2]])] - public function testItsListWithReturnsAllMatchedEntities($entities, $expect): void + public function testItsListWithReturnsAllMatchedEntities(array $entities, array $expect): void { $subject = AnyArrayRepository::withList($entities); $this->assertSame( $expect, array_map( - fn (AnyEntity $e) => $e->getProp2(), + fn (AnyEntity $e): mixed => $e->getProp2(), $subject->listWith(fn (AnyEntity $e): bool => $e->getProp1() === 'ok') ) ); @@ -156,7 +164,7 @@ function () use ($subject): void { ); } - protected function assertAssertionFails($callable): void + protected function assertAssertionFails(callable $callable): void { try { $callable(); @@ -227,6 +235,7 @@ protected static function getEntityBaseClass(): string return AnyEntity::class; } + /** @return list */ public function getEntities(): array { return $this->entities; @@ -270,20 +279,20 @@ public function saveEntity($entity): void class AnyEntity { - protected $prop1; - protected $prop2; + protected mixed $prop1; + protected mixed $prop2; - public function getProp1() + public function getProp1(): mixed { return $this->prop1; } - public function getProp2() + public function getProp2(): mixed { return $this->prop2; } - public function setProp2($string): void + public function setProp2(mixed $string): void { $this->prop2 = $string; } diff --git a/test/unit/Session/MysqlSessionTest.php b/test/unit/Session/MysqlSessionTest.php index cbf88d8..792b69a 100644 --- a/test/unit/Session/MysqlSessionTest.php +++ b/test/unit/Session/MysqlSessionTest.php @@ -22,6 +22,7 @@ final class MysqlSessionTest extends TestCase { + /** @var array */ private array $old_ini_vars = []; public function testItIsInitialisable(): void @@ -72,6 +73,7 @@ public static function provider_validate_invalid_sid(): Iterator ]; } + /** @param array $config */ #[DataProvider('provider_validate_invalid_sid')] public function testItRejectsInvalidSessionIdsWithoutCheckingDatabase(array $config, string $sid): void { @@ -107,6 +109,7 @@ public static function provider_validate_own_sid(): Iterator ]; } + /** @param array $config */ #[DataProvider('provider_validate_own_sid')] public function testSidThatItCreatesIsValid(array $config, string $expected_pattern): void { diff --git a/test/unit/Sitemap/SitemapParserTest.php b/test/unit/Sitemap/SitemapParserTest.php index 55958bb..5411c1e 100644 --- a/test/unit/Sitemap/SitemapParserTest.php +++ b/test/unit/Sitemap/SitemapParserTest.php @@ -153,6 +153,9 @@ public static function provider_parse(): Iterator ]; } + /** + * @param array> $expect + */ #[DataProvider('provider_parse')] public function testItParsesValidSitemapToMapOfUrlToProperties(string $xml, array $expect): void { diff --git a/test/unit/StringEncoding/JSONTest.php b/test/unit/StringEncoding/JSONTest.php index 3508e2b..e1317c6 100644 --- a/test/unit/StringEncoding/JSONTest.php +++ b/test/unit/StringEncoding/JSONTest.php @@ -26,7 +26,7 @@ public static function provider_valid_json(): Iterator } #[DataProvider('provider_valid_json')] - public function testItParsesValidJsonWithObjectsAsArrays(string $json, int|bool|string|array|null $expect): void + public function testItParsesValidJsonWithObjectsAsArrays(string $json, mixed $expect): void { $this->assertSame($expect, JSON::decode($json)); } @@ -34,7 +34,7 @@ public function testItParsesValidJsonWithObjectsAsArrays(string $json, int|bool| #[TestWith([null, 'Cannot decode a null value'])] #[TestWith(['', 'Syntax error'])] #[TestWith(['i am not json', 'Syntax error'])] - public function testItThrowsOnParsingInvalidJson($value, $expect_msg): void + public function testItThrowsOnParsingInvalidJson(?string $value, string $expect_msg): void { $this->expectException(InvalidJSONException::class); $this->expectExceptionMessage($expect_msg); @@ -70,7 +70,7 @@ public static function provider_valid_encode(): Iterator } #[DataProvider('provider_valid_encode')] - public function testEncodeEncodesJsonPrettilyOrNot(int|array $val, bool $pretty, string $expect): void + public function testEncodeEncodesJsonPrettilyOrNot(mixed $val, bool $pretty, string $expect): void { $this->assertSame($expect, JSON::encode($val, $pretty)); } diff --git a/test/unit/StringEncoding/StringSanitiserTest.php b/test/unit/StringEncoding/StringSanitiserTest.php index ced331f..32ed1a4 100644 --- a/test/unit/StringEncoding/StringSanitiserTest.php +++ b/test/unit/StringEncoding/StringSanitiserTest.php @@ -98,6 +98,9 @@ public static function provider_printable_utf8_max_length(): Iterator ]; } + /** + * @param array $expected + */ #[DataProvider('provider_printable_utf8_max_length')] public function testItCanConstrainPrintableUtf8ToAMaxLength(string $input, array $expected): void { diff --git a/test/unit/Validation/StrictDateTest.php b/test/unit/Validation/StrictDateTest.php index e36350c..3b0f134 100644 --- a/test/unit/Validation/StrictDateTest.php +++ b/test/unit/Validation/StrictDateTest.php @@ -32,7 +32,7 @@ final class StrictDateTest extends TestCase #[TestWith(['2016-01-01 50:12:00', false])] #[TestWith(['2016-01-01T10:00:00', false])] #[TestWith(['2016-01-01 10:00:00', true])] - public function testItValidatesIsoDatetime($value, $expect): void + public function testItValidatesIsoDatetime(mixed $value, bool $expect): void { $this->assertSame($expect, StrictDate::iso_datetime($value)); } @@ -45,7 +45,7 @@ public function testItValidatesIsoDatetime($value, $expect): void #[TestWith(['2016-02-30', false])] #[TestWith(['2016-01-01', true])] #[TestWith(['2016-02-30 10:00:00', false])] - public function testItValidatesIsoDate($value, $expect): void + public function testItValidatesIsoDate(mixed $value, bool $expect): void { $this->assertSame($expect, StrictDate::iso_date($value)); } @@ -84,6 +84,9 @@ public static function provider_date_before_after_invalid_inputs(): Iterator yield [['from' => null, 'to' => new DateTimeImmutable()], 'from', 'to', true]; } + /** + * @param array $data + */ #[DataProvider('provider_date_before_after_invalid_inputs')] public function testDateCompareFuncsValidateInvalidInput(array $data, string $from_field, string $to_field): void { @@ -132,7 +135,7 @@ public function testItValidatesDateAfterDate(string $from, string $to, bool $exp #[TestWith(['2017-01-04 00:00:00', '2017-01-04 00:00:00', true])] #[TestWith(['2017-01-04 10:00:00', '2017-01-04 08:00:00', true])] #[TestWith(['2017-05-06 10:00:00', '2018-12-30 00:00:00', true])] - public function testItValidatesDateOnOrAfterDate($from, $to, $expect): void + public function testItValidatesDateOnOrAfterDate(string $from, string $to, bool $expect): void { $this->assertSame( $expect, diff --git a/test/unit/Validation/ValidNumberTest.php b/test/unit/Validation/ValidNumberTest.php index 8179aa0..68ff30d 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($value, $min, $expect): void + public function testItValidatesMinimumAsGreaterOrEqual(mixed $value, mixed $min, bool $expect): void { $this->assertSame($expect, ValidNumber::minimum($value, $min)); }