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: 9
level: 10
paths:
- src
- test
Expand Down
4 changes: 2 additions & 2 deletions src/CSV/CSVWriter.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@

class CSVWriter
{
public const UTF8_BOM = "\xEF\xBB\xBF";
final public const UTF8_BOM = "\xEF\xBB\xBF";

/**
* @var resource|null
Expand Down Expand Up @@ -78,7 +78,7 @@ public function write(array $row): void

if ($this->expect_schema === null) {
if ($this->options['write_utf8_bom']) {
fwrite($this->resource, static::UTF8_BOM);
fwrite($this->resource, self::UTF8_BOM);
}
$this->expect_schema = $row_schema;
$this->writeHeaders($this->expect_schema);
Expand Down
4 changes: 2 additions & 2 deletions src/DateTime/DateIntervalUtils.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,8 @@ public static function toHuman(DateInterval $interval): string

$parts = [];
foreach ($supported_components as $key => $human_value) {
$qty = $components[$key] ?? null;
$parts[] = $qty.' '.$human_value.($qty > 1 ? 's' : '');
$qty = $interval->$key ?? null;
$parts[] = sprintf('%s %s%s', $qty, $human_value, $qty > 1 ? 's' : '');
}

$last_part = array_pop($parts);
Expand Down
14 changes: 5 additions & 9 deletions src/DeploymentConfig/DeploymentConfig.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,17 +24,13 @@ final class DeploymentConfig

private readonly ConfigValueDecrypter $value_decrypter;

/**
* @return static
*/
public static function instance()
private static DeploymentConfig $instance;

public static function instance(): self
{
static $instance;
if (!$instance) {
$instance = new self();
}
self::$instance ??= new self();

return $instance;
return self::$instance;
}

private function __construct(
Expand Down
34 changes: 22 additions & 12 deletions src/Logging/DeviceIdentifier.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
<?php

declare(strict_types=1);

namespace Ingenerator\PHPUtils\Logging;

use DateInterval;
Expand All @@ -24,16 +26,24 @@
* It *must not* be used for any application logic as the value is protected only against invalid
* formats, it is not in any way protected against forgery or cloning.
*/
class DeviceIdentifier
final class DeviceIdentifier
{
protected static ?DeviceIdentifier $instance;
private static ?DeviceIdentifier $instance;

/**
* @internal
*/
public static function resetInstance(): void
{
self::$instance = null;
}

/**
* Forces the singleton state to a known value for use in testing.
*/
public static function forceGlobalTestValue(string $id): void
{
static::$instance = new DeviceIdentifier(new ArrayCookieWrapperStub(['did' => $id]));
self::$instance = new DeviceIdentifier(new ArrayCookieWrapperStub(['did' => $id]));
}

/**
Expand All @@ -49,12 +59,12 @@ public static function initAndEnsureCookieSet(bool $ssl_available, bool $is_cli
// Note that as it's not really appropriate to inject the `is_cli` arg to `::get()`, and we can't stub
// PHP_SAPI for testing, that method will still return `-unset-` if it is called before
// ::initAndEnsureCookieSet()
static::forceGlobalTestValue(static::CLI_ID);
self::forceGlobalTestValue(self::CLI_ID);
} else {
static::$instance = new DeviceIdentifier(new CookieWrapper($ssl_available));
self::$instance = new DeviceIdentifier(new CookieWrapper($ssl_available));
}
assert(static::$instance instanceof DeviceIdentifier, 'Should have been assigned by above or by ::forceGlobalTestValue');
static::$instance->init();
assert(self::$instance instanceof DeviceIdentifier, 'Should have been assigned by above or by ::forceGlobalTestValue');
self::$instance->init();
}

/**
Expand All @@ -66,7 +76,7 @@ public static function initAndEnsureCookieSet(bool $ssl_available, bool $is_cli
*/
public static function get(): string
{
$i = static::$instance ?: new DeviceIdentifier(new CookieWrapper());
$i = self::$instance ?? new DeviceIdentifier(new CookieWrapper());

return $i->getValue();
}
Expand All @@ -75,9 +85,9 @@ public static function get(): string
public const COOKIE_LIFETIME = 'P5Y';
public const VALID_REGEX = '/^[a-zA-Z0-9\-_=]{22}$/';

protected ?string $id = null;
private ?string $id = null;

protected function __construct(protected CookieWrapper $cookies)
private function __construct(private readonly CookieWrapper $cookies)
{
}

Expand Down Expand Up @@ -117,10 +127,10 @@ public function init(): void
}
}

protected function assignNewIdAndSetCookies(): void
private function assignNewIdAndSetCookies(): void
{
$this->id = Base64Url::encode(random_bytes(16));
$expire = (new DateTimeImmutable())->add(new DateInterval(static::COOKIE_LIFETIME));
$expire = (new DateTimeImmutable())->add(new DateInterval(self::COOKIE_LIFETIME));

// The cookies are set with httponly=false to allow access from JS (though generally it is
// preferred to render it server-side and inject into javascript through data attributes /
Expand Down
9 changes: 9 additions & 0 deletions src/Logging/StackdriverApplicationLogger.php
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,9 @@ public function log($level, string|Stringable $message, array $context = []): vo
$this->getMetadata(),
$context_overrides
);
// In context, we know that the ::deepMerge above returns an array<string, mixed> since that is the type of all
// the inputs.
/** @var array<string, mixed> $log_entry */

// Find source location here rather than in the initial array merge to avoid having to make this backtrace
// call if it's already been provided / overridden by the caller.
Expand Down Expand Up @@ -223,6 +226,9 @@ protected function getMetadata(): array
$source = $source();
}
$metadata = AssociativeArrayUtils::deepMerge($metadata, $source);
// In context, we know that the ::deepMerge above returns an array<string, mixed> since that is the type of all
// the inputs.
/** @var array<string, mixed> $metadata */
} catch (Throwable $e) {
// @todo: include name/type of metadata source here (need a string helper to get the type name?)
$meta_errors[] = ['idx' => $index, 'throwable' => $e];
Expand Down Expand Up @@ -427,6 +433,9 @@ public function logRequest(
unset($log_entry['context']['httpRequest']);
}

// In context, we know that the ::deepMerge above returns an array<string, mixed> since that is the type of all
// the inputs.
/** @var array<string, mixed> $log_entry */
$this->writeLog($log_entry);
}

Expand Down
11 changes: 7 additions & 4 deletions src/Mutex/DbBackedMutexWrapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,13 @@ protected function getLock(string $name, int $timeout_seconds): void
$query = $this->runQuery("SELECT GET_LOCK($name_param, $timeout_seconds)");
$result = $query->fetchAll(PDO::FETCH_COLUMN, 0);

// Need to explicitly cast the result to an int for comparison as PDO value types vary between 8.0 and 8.1+
// And we should keep this cast even when we drop 8.0, because the PDO int/string mode is actually
// configurable with a PDO attribute so could vary at runtime too.
if (1 !== (int) $result[0]) {
// Need to explicitly check as int and as string because the PDO int/string mode varies depending on the
// runtime configurable PDO attribute.
$got_lock = match ($result[0]) {
1, '1' => true,
default => false,
};
if (!$got_lock) {
throw new MutexTimedOutException($name, $timeout_seconds, $result);
}
}
Expand Down
11 changes: 9 additions & 2 deletions src/Object/ObjectPropertyRipper.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public static function rip(object $object, array $properties): array
$class = $object::class;
$ripper = static::getRipper($class);

return $ripper($object, $properties);
return $ripper($object, array_values($properties));
}

/**
Expand All @@ -59,6 +59,10 @@ public static function ripAll(object $object): array
fn (): array => get_object_vars($object),
$object,
))();
// Currently phpstan doesn't support typing a method to take a callable with arbitrary arguments so
// it's not possible to tell it that the ::bindScopedClosure return will be the return of the closure.
// See https://github.com/phpstan/phpstan/issues/8214
/** @var array<string, mixed> $props */

// Safety check - the method above is efficient but can't return private props from parent classes
// And actually, turning complex classes like that into arrays is probelematic anyway because there's
Expand Down Expand Up @@ -87,13 +91,16 @@ public static function ripOne(object $object, string $property): mixed
* properties.
*
* @param class-string $class
*
* @return Closure(object, list<string>): array<string, mixed>
*/
protected static function getRipper(string $class): Closure
{
static::$rippers[$class] ??= self::bindScopedClosure(
function ($object, $properties): array {
function (object $object, array $properties): array {
$values = [];
foreach ($properties as $property) {
assert(is_string($property), 'Should have been called with string property names');
$values[$property] = $object->$property;
}

Expand Down
18 changes: 9 additions & 9 deletions src/Repository/AbstractArrayRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -175,24 +175,24 @@ protected function entityToArray(object $entity, ?WeakMap $seen_objects = null):
$seen_objects[$entity] = true;

$all_props = Closure::bind(
fn ($e): array => get_object_vars($e),
fn (object $e): array => get_object_vars($e),
null,
$entity,
);
$obj_identity = (fn ($a): string => $a::class.'#'.spl_object_id($a));
$obj_identity = (fn (object $a): string => $a::class.'#'.spl_object_id($a));
$result = [];
foreach ($all_props($entity) as $key => $var) {
if (!is_object($var)) {
$result[$key] = $var;
} elseif ($var instanceof Collection) {
$result[$key] = [];
foreach ($var as $collection_item) {
$result[$key][] = [
$obj_identity($var) => $this->entityToArray($collection_item, $seen_objects),
];
}
$result[$key] = array_map(
fn (mixed $collection_item): array => [
$obj_identity($var) => is_object($collection_item) ? $this->entityToArray($collection_item, $seen_objects) : '**NOT OBJECT**',
],
[...$var]
);
} elseif ($var instanceof DateTimeInterface) {
$result[$key][$var::class] = $var->format(DateTime::ISO8601);
$result[$key] = [$var::class => $var->format(DateTime::ISO8601)];
} else {
$result[$key] = [
$obj_identity($var) => $this->entityToArray($var, $seen_objects),
Expand Down
14 changes: 11 additions & 3 deletions src/Session/MysqlSession.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ class MysqlSession implements SessionHandlerInterface, SessionUpdateTimestampHan
protected ?string $session_lock = null;

/**
* @var string[]
* @var array<string, string>
*/
protected array $data_cache;

Expand Down Expand Up @@ -186,11 +186,19 @@ public function validateId($session_id): bool
// it is recommended to use fetchAll so that PDO can close the DB cursor, even tho we only expect one row
$rows = $query->fetchAll(PDO::FETCH_ASSOC);

if ($session_data = ($rows[0]['session_data'] ?? null)) {
if ($rows !== []) {
if (!is_array($rows[0]) || !isset($rows[0]['session_data'])) {
throw new RuntimeException('Unexpected data type returned from database');
}

if (!is_string($rows[0]['session_data'])) {
throw new RuntimeException('Unexpected data type returned from database');
}

// OK, they have a session, not expired and the hash is correct
// Cache the data for the read call that will immediately follow
// And keep the lock as we need to hold it till the end of their request
$this->data_cache[$session_id] = $session_data;
$this->data_cache[$session_id] = $rows[0]['session_data'];

return true;
}
Expand Down
2 changes: 1 addition & 1 deletion test/unit/ArrayHelpers/AssociativeArrayUtilsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ public static function provider_paths_to_nested(): Iterator
}

/**
* @param array<mixed> $input
* @param array<string, mixed> $input
* @param array<mixed> $expect
*/
#[DataProvider('provider_paths_to_nested')]
Expand Down
2 changes: 1 addition & 1 deletion test/unit/Cookie/CookieWrapperTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

final class CookieWrapperTest extends TestCase
{
/** @var array<string, mixed> */
/** @var array<mixed> */
private array $_old_cookie_var;

private bool $ssl_available = true;
Expand Down
3 changes: 3 additions & 0 deletions test/unit/DateTime/Clock/RealtimeClockTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,9 @@ public static function provider_relative_times(): Iterator
];
}

/**
* @param Closure(RealtimeClock): DateTimeImmutable $test_method
*/
#[DataProvider('provider_relative_times')]
public function testItReturnsRelativeTimes(Closure $test_method, string $expect_result, bool $expect_zero_time): void
{
Expand Down
20 changes: 4 additions & 16 deletions test/unit/Logging/DeviceIdentifierTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -145,11 +145,7 @@ public function testItsGetterReturnsInitialisedValueIfInitialised(): void

public function testItsStaticInitCreatesInstanceAndInitialises(): void
{
ScopeChangingCaller::call(
DeviceIdentifier::class,
/** @phpstan-ignore staticProperty.protected (intentional modification of state to reset singleton) */
function (): void { DeviceIdentifier::$instance = null; }
);
DeviceIdentifier::resetInstance();

$old_cookie = $_COOKIE;
try {
Expand All @@ -172,11 +168,7 @@ function (): void { DeviceIdentifier::$instance = null; }

public function testItsStaticInitCreatesInstanceAndInitialisesWithFixedIdInCli(): void
{
ScopeChangingCaller::call(
DeviceIdentifier::class,
/** @phpstan-ignore staticProperty.protected (intentional modification of state to reset singleton) */
function (): void { DeviceIdentifier::$instance = null; }
);
DeviceIdentifier::resetInstance();

DeviceIdentifier::initAndEnsureCookieSet(true); // Fall back to default arg
$this->assertSame(DeviceIdentifier::CLI_ID, DeviceIdentifier::get());
Expand All @@ -185,11 +177,7 @@ function (): void { DeviceIdentifier::$instance = null; }

public function testItsStaticGetCanReadFromCookiesEvenIfNotInitialised(): void
{
ScopeChangingCaller::call(
DeviceIdentifier::class,
/** @phpstan-ignore staticProperty.protected (intentional modification of state to reset singleton) */
function (): void { DeviceIdentifier::$instance = null; }
);
DeviceIdentifier::resetInstance();

$old_cookie = $_COOKIE;
try {
Expand Down Expand Up @@ -221,7 +209,7 @@ protected function newSubject(): DeviceIdentifier
{
return ScopeChangingCaller::call(
DeviceIdentifier::class,
/** @phpstan-ignore new.protectedConstructor (intentional modification of state to reset singleton) */
/** @phpstan-ignore new.privateConstructor (intentional modification of state to reset singleton) */
fn (CookieWrapper $cookies): DeviceIdentifier => new DeviceIdentifier($cookies),
$this->cookies
);
Expand Down
2 changes: 2 additions & 0 deletions test/unit/Logging/ExternalCallSiteFinderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,8 @@ public function testItCanHandleAllPossibleCallSites(string $code): void
unlink($temp);
}

$this->assertIsArray($result);
$this->assertSame(['expected', 'actual'], array_keys($result));
$this->assertSame($result['expected'], $result['actual']);
}

Expand Down
3 changes: 2 additions & 1 deletion test/unit/Logging/StackdriverApplicationLoggerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -573,9 +573,10 @@ public function testItsRequestLoggerHoistsHttpMetadataToTopLevel(): void
$logger = $this->newSubject();
$logger->logRequest(ServerGlobal::fake([]));
$entry = $this->assertLoggedOneLine();
$this->assertIsArray($entry['httpRequest'] ?? null);
$this->assertSame(
$original_http_meta,
array_intersect_key($entry['httpRequest'] ?? null, $original_http_meta),
array_intersect_key($entry['httpRequest'], $original_http_meta),
'Should include metadata in top-level httpRequest struct'
);
$this->assertArrayNotHasKey('httpRequest', $entry['context'], 'Should not duplicate httpRequest meta in context');
Expand Down
Loading
Loading