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