Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion phpstan.dist.neon
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
parameters:
treatPhpDocTypesAsCertain: false
level: 8
level: 9
paths:
- src
- test
Expand Down
7 changes: 6 additions & 1 deletion src/ArrayHelpers/AssociativeArrayUtils.php
Original file line number Diff line number Diff line change
Expand Up @@ -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];
}

Expand Down
25 changes: 21 additions & 4 deletions src/ArrayHelpers/UniqueMap.php
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, mixed>
* @implements IteratorAggregate<string, mixed>
* @template TValueType
*
* @implements ArrayAccess<string, TValueType>
* @implements IteratorAggregate<string, TValueType>
*/
class UniqueMap implements ArrayAccess, IteratorAggregate, Countable
{
/**
* @param array<string,mixed> $items initial items to put in the map
* @param array<string,TValueType> $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)) {
Expand All @@ -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)) {
Expand All @@ -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<string, mixed> */
/** @return ArrayIterator<string, TValueType> */
public function getIterator(): Traversable
{
return new ArrayIterator($this->items);
Expand Down
2 changes: 1 addition & 1 deletion src/CSV/CSVWriter.php
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ public function open(mixed $file, array $options = []): void
$this->options = array_merge($this->options, $options);
}

/** @param array<array-key, mixed> $row */
/** @param array<array-key, bool|float|int|string|null> $row */
public function write(array $row): void
{
if (!$this->isResourceOpen()) {
Expand Down
39 changes: 36 additions & 3 deletions src/Cookie/CookieWrapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Ingenerator\PHPUtils\Cookie;

use DateTimeImmutable;
use UnexpectedValueException;

use function array_merge;
use function headers_sent;
Expand All @@ -25,7 +26,15 @@
class CookieWrapper
{
/**
* @var mixed[]
* Note: PHP $_COOKIE is normally array<string,string> 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<mixed>
*/
protected array $cookies = [];

Expand Down Expand Up @@ -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
Expand All @@ -99,7 +120,19 @@ public function delete(string $name): void
/** @param array<string, mixed> $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
Expand Down
26 changes: 14 additions & 12 deletions src/DeploymentConfig/DeploymentConfig.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Ingenerator\PHPUtils\StringEncoding\InvalidJSONException;
use Ingenerator\PHPUtils\StringEncoding\JSON;
use Ingenerator\PHPUtils\Superglobals\ServerGlobal;

final class DeploymentConfig
{
Expand All @@ -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;

Expand All @@ -36,19 +37,11 @@ public static function instance()
return $instance;
}

/**
* @param array<string, mixed>|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');
}
Expand Down Expand Up @@ -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);
}
Expand Down
10 changes: 10 additions & 0 deletions src/DeploymentConfig/MissingConfigException.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 `*`");
Expand Down
7 changes: 6 additions & 1 deletion src/Encryption/CryptoBox/CryptoBoxKeypairSet.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@
*/
final class CryptoBoxKeypairSet
{
/**
* @var UniqueMap<CryptoBoxKeypair>
*/
private UniqueMap $keys;

/**
Expand All @@ -43,7 +46,9 @@ public static function fromStrings(
public function __construct(
CryptoBoxKeypair ...$keys,
) {
$this->keys = new UniqueMap([]);
$map = new UniqueMap();
/** @var UniqueMap<CryptoBoxKeypair> $map */
$this->keys = $map;
foreach ($keys as $key) {
$this->keys[$key->keypair_id] = $key;
}
Expand Down
23 changes: 12 additions & 11 deletions src/Logging/DefaultLogMetadata.php
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
<?php

declare(strict_types=1);

namespace Ingenerator\PHPUtils\Logging;

use Ingenerator\PHPUtils\Superglobals\ServerGlobal;
use Throwable;

use function array_shift;
Expand Down Expand Up @@ -33,18 +36,16 @@ public static function deviceIdentityLazy(): callable
* Note that these values are also "hoisted" by the request logger rather than look them up separately so you should
* always include this or an equivalent metadata set with the same values.
*
* @param array<string, mixed> $server the $_SERVER global
*
* @return array<string, array<string, array<string, mixed>>>
*/
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}',
],
],
];
Expand All @@ -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<string, mixed> $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 {
Expand Down
8 changes: 4 additions & 4 deletions src/Logging/ExternalCallSiteFinder.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ class ExternalCallSiteFinder
* }
*/
/**
* @param list<array<string, mixed>> $trace
* @param list<array{file?: string, line?: int, function?: string, class?: string, type?:string}> $trace
* @param list<class-string> $ignore_classes
*
* @return array<string, mixed>
Expand Down Expand Up @@ -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,
];
}
Expand Down
Loading
Loading