From b9f5bd133b64defad2b4d19a717e75aba520ecd4 Mon Sep 17 00:00:00 2001 From: Pollora maintainer Date: Wed, 25 Nov 2026 12:17:25 +0100 Subject: [PATCH 1/8] fix(hook): count the parameters of invokable objects and Class::method strings --- CHANGELOG.md | 4 ++++ src/Domain/Service/AbstractHook.php | 11 ++++++++++ .../Unit/Domain/Service/AbstractHookTest.php | 21 +++++++++++++++++++ 3 files changed, 36 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index ca2d826..7bb6830 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,10 @@ All notable changes to `pollora/hook` are documented in this file. ## [Unreleased] +### Fixed + +- Registering an invokable object (`Action::add('init', new Handler)`) without an argument count threw a `TypeError`, and a static method written as a string (`'Handler::run'`) threw `CallbackAnalysisFailedException`: the parameters were counted with `ReflectionFunction`, which reads neither. They are now read from the object's `__invoke()` and from the named static method. + ## [2.0.2] - 2026-11-25 ### Fixed diff --git a/src/Domain/Service/AbstractHook.php b/src/Domain/Service/AbstractHook.php index bca3be9..f28bf0d 100644 --- a/src/Domain/Service/AbstractHook.php +++ b/src/Domain/Service/AbstractHook.php @@ -471,6 +471,13 @@ private function countParameters(callable|array $callback): int if (is_array($callback)) { [$object, $method] = $callback; $reflection = new \ReflectionMethod($object, $method); + } elseif (is_string($callback) && str_contains($callback, '::')) { + // A static method written 'Class::method' is not a function name + [$class, $staticMethod] = explode('::', $callback, 2); + $reflection = new \ReflectionMethod($class, $staticMethod); + } elseif (is_object($callback) && ! $callback instanceof \Closure) { + // An invokable object: its __invoke() method is what WordPress calls + $reflection = new \ReflectionMethod($callback, '__invoke'); } else { $reflection = new \ReflectionFunction($callback); } @@ -631,6 +638,10 @@ private function getCacheKeyForCallback(callable|array $callback): string } // Closures never reach this method: detectArguments() keys them by the closure itself. + if (is_object($callback)) { + return $callback::class.'::__invoke@'.spl_object_id($callback); + } + // Fallback for any other type of callable return serialize($callback); } diff --git a/tests/Unit/Domain/Service/AbstractHookTest.php b/tests/Unit/Domain/Service/AbstractHookTest.php index 14ace3b..0c79cea 100644 --- a/tests/Unit/Domain/Service/AbstractHookTest.php +++ b/tests/Unit/Domain/Service/AbstractHookTest.php @@ -34,6 +34,27 @@ public function testResolveCallback(string $hook, callable|string|array $callbac AbstractHook::clearReflectionCache(); }); +final class InvokableProbe +{ + public function __invoke(string $a, int $b): void {} + + public static function staticProbe(string $a, int $b, int $c): void {} +} + +describe('Argument detection', function (): void { + it('counts the parameters of an invokable object through its __invoke()', function (): void { + $this->hook->add('init', new InvokableProbe); + + expect($this->hook->callbacks('init')[0]['args'])->toBe(2); + }); + + it('counts the parameters of a static method written Class::method', function (): void { + $this->hook->add('init', InvokableProbe::class.'::staticProbe'); + + expect($this->hook->callbacks('init')[0]['args'])->toBe(3); + }); +}); + describe('P0 — Permissive callback resolution', function (): void { it('stores a string callback that is not yet callable without throwing', function (): void { $this->hook->add('init', 'my_future_function'); From a5b94bedda5287192aeba0ed1a2882b74d8a6a13 Mon Sep 17 00:00:00 2001 From: Pollora maintainer Date: Wed, 25 Nov 2026 12:19:25 +0100 Subject: [PATCH 2/8] fix(async): fail at once when a handler's method is not callable from outside --- CHANGELOG.md | 1 + src/Async/CallableDescriptor.php | 21 ++++++++++++++++++-- src/Async/Exceptions/UnresolvableHandler.php | 5 +++++ tests/Unit/Async/CallableDescriptorTest.php | 13 ++++++++++++ 4 files changed, 38 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7bb6830..4977863 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ All notable changes to `pollora/hook` are documented in this file. ### Fixed - Registering an invokable object (`Action::add('init', new Handler)`) without an argument count threw a `TypeError`, and a static method written as a string (`'Handler::run'`) threw `CallbackAnalysisFailedException`: the parameters were counted with `ReflectionFunction`, which reads neither. They are now read from the object's `__invoke()` and from the named static method. +- An asynchronous handler whose descriptor names a private or protected method was retried as many times as `tries` allowed, each attempt failing the same way with `The handler of … is not callable`. Resolving the descriptor now fails at once with an `UnresolvableHandler` that says the method is not public. ## [2.0.2] - 2026-11-25 diff --git a/src/Async/CallableDescriptor.php b/src/Async/CallableDescriptor.php index 97a1fb9..8428deb 100644 --- a/src/Async/CallableDescriptor.php +++ b/src/Async/CallableDescriptor.php @@ -130,7 +130,7 @@ public function resolve(string $descriptor): callable } if ((new \ReflectionMethod($className, $method))->isStatic()) { - return [$className, $method]; + return $this->callable([$className, $method], $className, $method); } try { @@ -141,7 +141,24 @@ public function resolve(string $descriptor): callable throw UnresolvableHandler::notInstantiable($className, $throwable); } - return [$instance, $method]; + return $this->callable([$instance, $method], $className, $method); + } + + /** + * A method that exists but that nothing outside the class can call is no handler: failing here is final, + * where letting the call fail would send the execution through every retry for nothing. + * + * @param array{0: class-string|object, 1: string} $handler + * + * @throws UnresolvableHandler When the method cannot be called from here + */ + private function callable(array $handler, string $className, string $method): callable + { + if (! is_callable($handler)) { + throw UnresolvableHandler::notPublicMethod($className, $method); + } + + return $handler; } private function describeClosure(\Closure $closure): string diff --git a/src/Async/Exceptions/UnresolvableHandler.php b/src/Async/Exceptions/UnresolvableHandler.php index 8ea7ef4..09b666a 100644 --- a/src/Async/Exceptions/UnresolvableHandler.php +++ b/src/Async/Exceptions/UnresolvableHandler.php @@ -68,6 +68,11 @@ public static function missingMethod(string $className, string $method): self return new self(sprintf("The asynchronous handler method '%s::%s()' no longer exists.", $className, $method)); } + public static function notPublicMethod(string $className, string $method): self + { + return new self(sprintf("The asynchronous handler method '%s::%s()' is not public: nothing outside the class can call it.", $className, $method)); + } + public static function notInstantiable(string $className, \Throwable $previous): self { return new self(sprintf("The asynchronous handler class '%s' could not be instantiated: %s", $className, $previous->getMessage()), 0, $previous); diff --git a/tests/Unit/Async/CallableDescriptorTest.php b/tests/Unit/Async/CallableDescriptorTest.php index ea0835a..7eb756a 100644 --- a/tests/Unit/Async/CallableDescriptorTest.php +++ b/tests/Unit/Async/CallableDescriptorTest.php @@ -12,6 +12,14 @@ function pollora_test_async_handler(int $postId): void {} } +/** + * A class whose method exists but cannot be called from outside. + */ +final class HiddenMethodHandler +{ + protected function hidden(): void {} +} + beforeEach(function (): void { $this->descriptor = new CallableDescriptor; }); @@ -165,6 +173,11 @@ public function resolve(string $className): object 'method' => [InvoiceHandler::class.'@removed', 'InvoiceHandler::removed()'], ]); + it('fails once, with a clear message, when the method is not public, instead of leaving a retry to find out', function (): void { + expect(fn () => $this->descriptor->resolve(HiddenMethodHandler::class.'@hidden')) + ->toThrow(UnresolvableHandler::class, 'HiddenMethodHandler::hidden()\' is not public'); + }); + it('rejects a malformed descriptor', function (string $descriptor): void { expect(fn () => $this->descriptor->resolve($descriptor))->toThrow(UnresolvableHandler::class, 'not a valid handler descriptor'); })->with(['system("id")', 'Foo@bar@baz', '@handle', 'Foo@']); From 3b5a902e87e5dd9770d193558cb38903eb2d5102 Mon Sep 17 00:00:00 2001 From: Pollora maintainer Date: Wed, 25 Nov 2026 12:20:58 +0100 Subject: [PATCH 3/8] refactor(types): state that captured values and hook arguments can be keyed by name (PHPStan level 7) --- src/Async/AsyncContext.php | 2 +- src/Async/AsyncDispatcher.php | 6 +++--- src/Async/AsyncPayload.php | 4 ++-- src/Async/QueuedHandler.php | 2 +- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/Async/AsyncContext.php b/src/Async/AsyncContext.php index 864e6af..c610e1b 100644 --- a/src/Async/AsyncContext.php +++ b/src/Async/AsyncContext.php @@ -18,7 +18,7 @@ * @param string $hook Hook that fired * @param \DateTimeImmutable $dispatchedAt Trigger date * @param int $attempt Attempt number, from 1 - * @param array $captured Values recorded at trigger time + * @param array $captured Values recorded at trigger time */ public function __construct( public int $userId, diff --git a/src/Async/AsyncDispatcher.php b/src/Async/AsyncDispatcher.php index c50d9c5..fc2423f 100644 --- a/src/Async/AsyncDispatcher.php +++ b/src/Async/AsyncDispatcher.php @@ -23,7 +23,7 @@ public function __construct( ) {} /** - * @param array $arguments Hook arguments, as WordPress passed them + * @param array $arguments Hook arguments, as WordPress passed them (named when a caller named them) */ public function dispatch(QueuedHandler $handler, array $arguments): void { @@ -117,8 +117,8 @@ public static function origin(): array /** * Run the capture callback of the registration, or the handler class's capture() method. * - * @param array $arguments - * @return array + * @param array $arguments + * @return array */ private function capture(QueuedHandler $handler, array $arguments): array { diff --git a/src/Async/AsyncPayload.php b/src/Async/AsyncPayload.php index 0c6800a..2201432 100644 --- a/src/Async/AsyncPayload.php +++ b/src/Async/AsyncPayload.php @@ -25,7 +25,7 @@ * @param int $priority Priority of the registration * @param array $arguments Normalized hook arguments, see ArgumentNormalizer * @param array{userId: int, blogId: int, locale: string, dispatchedAt: string} $origin Request that fired the hook - * @param array $captured Normalized values recorded at trigger time + * @param array $captured Normalized values recorded at trigger time * @param int $attempt Attempt number, from 1 * @param int $tries Number of attempts allowed * @param bool $keepMissing Run with null in place of a referenced object that no longer exists @@ -163,7 +163,7 @@ public function retryDelay(int $failedAttempt): int /** * The context handed to the handler, with the captured values rebuilt. * - * @param array $captured Denormalized captured values + * @param array $captured Denormalized captured values */ public function context(array $captured = []): AsyncContext { diff --git a/src/Async/QueuedHandler.php b/src/Async/QueuedHandler.php index 96aba71..243964a 100644 --- a/src/Async/QueuedHandler.php +++ b/src/Async/QueuedHandler.php @@ -21,7 +21,7 @@ final class QueuedHandler * @param int $registeredArgs Argument count of the original registration * @param int $acceptedArgs Hook arguments the handler takes, AsyncContext left out * @param PendingAsync $options Options, read when the hook fires - * @param callable|null $defaultCapture The handler class's public capture() method, used when capture() is not called + * @param callable|array{object, string}|null $defaultCapture The handler class's public capture() method, used when capture() is not called */ public function __construct( public readonly string $hook, From d6e4e155390aee0f2161614a847cf4f337d40837 Mon Sep 17 00:00:00 2001 From: Pollora maintainer Date: Wed, 25 Nov 2026 12:20:58 +0100 Subject: [PATCH 4/8] refactor(types): declare $wpdb as the database or null, and say why the table name is interpolated (PHPStan level 7) --- src/Async/Recovery.php | 3 ++- src/Async/UniqueLock.php | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/Async/Recovery.php b/src/Async/Recovery.php index 849c084..c1569c4 100644 --- a/src/Async/Recovery.php +++ b/src/Async/Recovery.php @@ -63,6 +63,7 @@ public static function run(): void */ public static function recover(): int { + /** @var \wpdb|null $wpdb The database, null before WordPress has loaded it */ global $wpdb; if (! is_object($wpdb)) { @@ -70,7 +71,7 @@ public static function recover(): int } $rows = $wpdb->get_results($wpdb->prepare( - "SELECT option_name, option_value FROM {$wpdb->options} WHERE option_name LIKE %s LIMIT %d", + "SELECT option_name, option_value FROM {$wpdb->options} WHERE option_name LIKE %s LIMIT %d", // @phpstan-ignore argument.type (only the table name, which no placeholder can stand for before WordPress 6.2's %i, is interpolated; every value goes through a placeholder) $wpdb->esc_like(PayloadStore::OPTION_PREFIX).'%', self::BATCH, ), 'ARRAY_A'); diff --git a/src/Async/UniqueLock.php b/src/Async/UniqueLock.php index f6f083e..1bc3d06 100644 --- a/src/Async/UniqueLock.php +++ b/src/Async/UniqueLock.php @@ -78,6 +78,7 @@ public static function release(string $key): void */ public static function prune(int $limit = 500): int { + /** @var \wpdb|null $wpdb The database, null before WordPress has loaded it */ global $wpdb; if (! is_object($wpdb)) { @@ -85,7 +86,7 @@ public static function prune(int $limit = 500): int } $names = $wpdb->get_col($wpdb->prepare( - "SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE %s AND CAST(option_value AS UNSIGNED) < %d LIMIT %d", + "SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE %s AND CAST(option_value AS UNSIGNED) < %d LIMIT %d", // @phpstan-ignore argument.type (only the table name, which no placeholder can stand for before WordPress 6.2's %i, is interpolated; every value goes through a placeholder) $wpdb->esc_like(self::OPTION_PREFIX).'%', time(), $limit, From d9d04f6a08885d9b477fd57bcac86b3e6ce3acc6 Mon Sep 17 00:00:00 2001 From: Pollora maintainer Date: Wed, 25 Nov 2026 12:20:59 +0100 Subject: [PATCH 5/8] refactor(types): update tracked registrations on a local copy, and read functions through a closure (PHPStan level 7) --- src/Domain/Service/AbstractHook.php | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/src/Domain/Service/AbstractHook.php b/src/Domain/Service/AbstractHook.php index f28bf0d..dfcc442 100644 --- a/src/Domain/Service/AbstractHook.php +++ b/src/Domain/Service/AbstractHook.php @@ -294,7 +294,7 @@ protected function resolveCallback(string $hook, callable|string|array $callback * Instantiate a class and resolve its method dynamically. * * @param string $hook The hook name - * @param string $className The class name + * @param class-string $className The class name * @param int|null $acceptedArgs Optional. Number of arguments (auto-detected if null) * @return array{callable: array{object, string}, args: int} Resolved class method callback and argument count * @@ -426,19 +426,24 @@ protected function addHookEvent(string $hook, callable|string|array $callback, i */ protected function replaceTrackedCallback(string $hook, int $priority, callable|string|array $current, callable|string|array $replacement, int $acceptedArgs, callable|string|array|null $handler): void { - foreach ($this->hooks[$hook] ?? [] as $index => $item) { + $registrations = $this->hooks[$hook] ?? []; + + foreach ($registrations as $index => $item) { if ($item['priority'] !== $priority || $item['callback'] !== $current) { continue; } - $this->hooks[$hook][$index]['callback'] = $replacement; - $this->hooks[$hook][$index]['args'] = $acceptedArgs; - unset($this->hooks[$hook][$index]['handler']); + $item['callback'] = $replacement; + $item['args'] = $acceptedArgs; + unset($item['handler']); if ($handler !== null) { - $this->hooks[$hook][$index]['handler'] = $handler; + $item['handler'] = $handler; } + $registrations[$index] = $item; + $this->hooks[$hook] = $registrations; + return; } } @@ -479,7 +484,8 @@ private function countParameters(callable|array $callback): int // An invokable object: its __invoke() method is what WordPress calls $reflection = new \ReflectionMethod($callback, '__invoke'); } else { - $reflection = new \ReflectionFunction($callback); + // A closure or a function name + $reflection = new \ReflectionFunction(\Closure::fromCallable($callback)); } return $reflection->getNumberOfParameters(); From 9ee8e529ee490b065f0fccd5584640252a4c1fd5 Mon Sep 17 00:00:00 2001 From: Pollora maintainer Date: Wed, 25 Nov 2026 12:20:59 +0100 Subject: [PATCH 6/8] test(types): throw on json_encode failures and read registered callbacks without assuming their shape (PHPStan level 7) --- tests/Stubs/wordpress.php | 8 ++++---- tests/Unit/Async/ActionSchedulerDriverTest.php | 4 +++- tests/Unit/Async/ArgumentNormalizerEdgeTest.php | 2 +- tests/Unit/Async/ArgumentNormalizerTest.php | 4 ++-- tests/Unit/Async/AsyncPayloadEdgeTest.php | 8 ++++---- tests/Unit/Async/AsyncPayloadTest.php | 6 +++--- tests/Unit/Async/CallableDescriptorTest.php | 4 +++- tests/Unit/Async/RunnerAndDispatcherEdgeTest.php | 4 +++- tests/Unit/Async/StorageAndRecoveryTest.php | 10 +++++----- tests/Unit/Async/UniqueTest.php | 2 +- tests/Unit/Domain/Service/AbstractHookTest.php | 2 ++ tests/Unit/Domain/Service/AbstractHookTrackingTest.php | 10 ++++++++-- 12 files changed, 39 insertions(+), 25 deletions(-) diff --git a/tests/Stubs/wordpress.php b/tests/Stubs/wordpress.php index d8e462e..e2266e1 100644 --- a/tests/Stubs/wordpress.php +++ b/tests/Stubs/wordpress.php @@ -337,7 +337,7 @@ function wp_stub_wpdb(): object { public string $options = 'wp_options'; - /** @var list}> Every query prepared */ + /** @var list}> Every query prepared */ public array $queries = []; /** @var list The output format asked of each get_results() call */ @@ -349,7 +349,7 @@ public function esc_like(string $text): string } /** - * @return array{query: string, args: list} + * @return array{query: string, args: array} */ public function prepare(string $query, mixed ...$args): array { @@ -359,7 +359,7 @@ public function prepare(string $query, mixed ...$args): array } /** - * @param array{query: string, args: list} $prepared + * @param array{query: string, args: array} $prepared * @return list */ public function get_results(array $prepared, string $output): array @@ -380,7 +380,7 @@ public function get_results(array $prepared, string $output): array /** * Answers the expired-lock query: prefix, time, limit. * - * @param array{query: string, args: list} $prepared + * @param array{query: string, args: array} $prepared * @return list */ public function get_col(array $prepared): array diff --git a/tests/Unit/Async/ActionSchedulerDriverTest.php b/tests/Unit/Async/ActionSchedulerDriverTest.php index af15370..752925e 100644 --- a/tests/Unit/Async/ActionSchedulerDriverTest.php +++ b/tests/Unit/Async/ActionSchedulerDriverTest.php @@ -196,7 +196,9 @@ function runScheduledActions(): void $cronMessage = $GLOBALS['wp_cron_events'][0]['args'][0]; $actionMessage = $GLOBALS['as_actions'][0]['args'][0]; - $long = new AsyncPayload(...[...array_diff_key((array) AsyncPayload::fromJson($actionMessage), ['id' => 1]), 'id' => '11111111-2222-4333-8444-555555555555']); + $longData = json_decode($actionMessage, true, flags: JSON_THROW_ON_ERROR); + $longData['id'] = '11111111-2222-4333-8444-555555555555'; + $long = AsyncPayload::fromJson(json_encode($longData, JSON_THROW_ON_ERROR)); PayloadStore::store($long); $GLOBALS['wp_cron_events'] = []; RecordingHandler::$calls = []; diff --git a/tests/Unit/Async/ArgumentNormalizerEdgeTest.php b/tests/Unit/Async/ArgumentNormalizerEdgeTest.php index 39448c9..4f09efa 100644 --- a/tests/Unit/Async/ArgumentNormalizerEdgeTest.php +++ b/tests/Unit/Async/ArgumentNormalizerEdgeTest.php @@ -23,7 +23,7 @@ final class NormalizerEdgeMutableDate extends DateTime {} $GLOBALS['wp_objects'] = []; $this->normalizer = new ArgumentNormalizer; $this->roundTrip = fn (array $arguments, bool $keepMissing = false): array => $this->normalizer->denormalize( - json_decode(json_encode($this->normalizer->normalize($arguments)), true), + json_decode(json_encode($this->normalizer->normalize($arguments), JSON_THROW_ON_ERROR), true), $keepMissing, ); }); diff --git a/tests/Unit/Async/ArgumentNormalizerTest.php b/tests/Unit/Async/ArgumentNormalizerTest.php index 9563884..e6732f7 100644 --- a/tests/Unit/Async/ArgumentNormalizerTest.php +++ b/tests/Unit/Async/ArgumentNormalizerTest.php @@ -14,7 +14,7 @@ $GLOBALS['wp_objects'] = []; $this->normalizer = new ArgumentNormalizer; $this->roundTrip = fn (array $arguments, bool $keepMissing = false): array => $this->normalizer->denormalize( - json_decode(json_encode($this->normalizer->normalize($arguments), JSON_PRESERVE_ZERO_FRACTION), true), + json_decode(json_encode($this->normalizer->normalize($arguments), JSON_PRESERVE_ZERO_FRACTION | JSON_THROW_ON_ERROR), true), $keepMissing, ); }); @@ -121,7 +121,7 @@ public function supports(object $object): bool public function reference(object $object): array { - return ['key' => $object['key']]; + return ['key' => $object instanceof ArrayObject ? $object['key'] : null]; } public function resolve(array $reference): object diff --git a/tests/Unit/Async/AsyncPayloadEdgeTest.php b/tests/Unit/Async/AsyncPayloadEdgeTest.php index 0d209d3..f6398f6 100644 --- a/tests/Unit/Async/AsyncPayloadEdgeTest.php +++ b/tests/Unit/Async/AsyncPayloadEdgeTest.php @@ -55,7 +55,7 @@ function edgePayload(array $overrides = []): AsyncPayload $data['origin'][$key] = $value; } - expect(fn () => AsyncPayload::fromJson(json_encode($data))) + expect(fn () => AsyncPayload::fromJson(json_encode($data, JSON_THROW_ON_ERROR))) ->toThrow(InvalidPayload::class, "'origin.{$key}'"); })->with([ 'no userId' => ['userId', null, true], @@ -72,7 +72,7 @@ function edgePayload(array $overrides = []): AsyncPayload $data = json_decode(edgePayload()->toJson(), true); unset($data['origin']['blogId']); - expect(fn () => AsyncPayload::fromJson(json_encode($data))) + expect(fn () => AsyncPayload::fromJson(json_encode($data, JSON_THROW_ON_ERROR))) ->toThrow(InvalidPayload::class, "The asynchronous payload field 'origin.blogId' is missing or invalid."); }); }); @@ -119,13 +119,13 @@ function edgePayload(array $overrides = []): AsyncPayload $data = json_decode(edgePayload()->toJson(), true); $data['backoff'] = [0, 5]; - expect(AsyncPayload::fromJson(json_encode($data))->backoff)->toBe([0, 5]); + expect(AsyncPayload::fromJson(json_encode($data, JSON_THROW_ON_ERROR))->backoff)->toBe([0, 5]); }); it('refuses a delay of minus one', function (): void { $data = json_decode(edgePayload()->toJson(), true); $data['backoff'] = [-1]; - expect(fn () => AsyncPayload::fromJson(json_encode($data)))->toThrow(InvalidPayload::class, "'backoff'"); + expect(fn () => AsyncPayload::fromJson(json_encode($data, JSON_THROW_ON_ERROR)))->toThrow(InvalidPayload::class, "'backoff'"); }); }); diff --git a/tests/Unit/Async/AsyncPayloadTest.php b/tests/Unit/Async/AsyncPayloadTest.php index 3db08c7..0d79c1f 100644 --- a/tests/Unit/Async/AsyncPayloadTest.php +++ b/tests/Unit/Async/AsyncPayloadTest.php @@ -80,7 +80,7 @@ function makeAsyncPayload(array $overrides = []): AsyncPayload $data[$field] = $value; } - expect(fn () => AsyncPayload::fromJson(json_encode($data)))->toThrow(InvalidPayload::class, "'{$reported}'"); + expect(fn () => AsyncPayload::fromJson(json_encode($data, JSON_THROW_ON_ERROR)))->toThrow(InvalidPayload::class, "'{$reported}'"); })->with([ ['handler', null, 'handler'], ['priority', '10', 'priority'], @@ -94,7 +94,7 @@ function makeAsyncPayload(array $overrides = []): AsyncPayload $data = json_decode(makeAsyncPayload()->toJson(), true); unset($data['driver'], $data['queue'], $data['asUser'], $data['backoff']); - $payload = AsyncPayload::fromJson(json_encode($data)); + $payload = AsyncPayload::fromJson(json_encode($data, JSON_THROW_ON_ERROR)); expect($payload->driver)->toBeNull() ->and($payload->queue)->toBeNull() @@ -107,7 +107,7 @@ function makeAsyncPayload(array $overrides = []): AsyncPayload $data = json_decode(makeAsyncPayload()->toJson(), true); $data['backoff'] = $backoff; - expect(fn () => AsyncPayload::fromJson(json_encode($data)))->toThrow(InvalidPayload::class, "'backoff'"); + expect(fn () => AsyncPayload::fromJson(json_encode($data, JSON_THROW_ON_ERROR)))->toThrow(InvalidPayload::class, "'backoff'"); })->with([ 'negative' => [[10, -5]], 'not a list' => [['a' => 10]], diff --git a/tests/Unit/Async/CallableDescriptorTest.php b/tests/Unit/Async/CallableDescriptorTest.php index 7eb756a..18ff05a 100644 --- a/tests/Unit/Async/CallableDescriptorTest.php +++ b/tests/Unit/Async/CallableDescriptorTest.php @@ -152,7 +152,9 @@ public function resolve(string $className): object $callable = (new CallableDescriptor($resolver))->resolve(InvoiceHandler::class.'@send'); - expect($callable[0]->source)->toBe('container'); + $target = is_array($callable) ? $callable[0] : null; + + expect($target instanceof InvoiceHandler ? $target->source : null)->toBe('container'); }); it('resolves a static method without instantiating', function (): void { diff --git a/tests/Unit/Async/RunnerAndDispatcherEdgeTest.php b/tests/Unit/Async/RunnerAndDispatcherEdgeTest.php index 824c3c9..9e945f0 100644 --- a/tests/Unit/Async/RunnerAndDispatcherEdgeTest.php +++ b/tests/Unit/Async/RunnerAndDispatcherEdgeTest.php @@ -355,6 +355,8 @@ public function resolve(string $class): object $action->setCallbackResolver($resolver); $action->add('init', $class); - expect($action->callbacks('init')[0]['callback'][0])->toBe($instance); + $registered = $action->callbacks('init')[0]['callback'] ?? null; + + expect(is_array($registered) ? $registered[0] : null)->toBe($instance); }); }); diff --git a/tests/Unit/Async/StorageAndRecoveryTest.php b/tests/Unit/Async/StorageAndRecoveryTest.php index 8e3ffb7..75b500b 100644 --- a/tests/Unit/Async/StorageAndRecoveryTest.php +++ b/tests/Unit/Async/StorageAndRecoveryTest.php @@ -75,7 +75,7 @@ public function esc_like(string $text): string } /** - * @return array{query: string, args: list} + * @return array{query: string, args: array} */ public function prepare(string $query, mixed ...$args): array { @@ -83,7 +83,7 @@ public function prepare(string $query, mixed ...$args): array } /** - * @param array{query: string, args: list} $prepared + * @param array{query: string, args: array} $prepared */ public function get_results(array $prepared, string $output): mixed { @@ -91,7 +91,7 @@ public function get_results(array $prepared, string $output): mixed } /** - * @param array{query: string, args: list} $prepared + * @param array{query: string, args: array} $prepared */ public function get_col(array $prepared): mixed { @@ -382,13 +382,13 @@ function executionEventsOf(): array $lengthWith = function (int $padding): int { $payload = storagePayload(['arguments' => [str_repeat('a', $padding)]]); - return strlen(json_encode([$payload->toJson()])); + return strlen(json_encode([$payload->toJson()], JSON_THROW_ON_ERROR)); }; $base = $lengthWith(0); $atLimit = storagePayload(['arguments' => [str_repeat('a', ScheduledDriver::MAX_ARGUMENTS_LENGTH - $base)]]); $beyond = storagePayload(['arguments' => [str_repeat('a', ScheduledDriver::MAX_ARGUMENTS_LENGTH - $base + 1)]]); - expect(strlen(json_encode([$atLimit->toJson()])))->toBe(ScheduledDriver::MAX_ARGUMENTS_LENGTH); + expect(strlen(json_encode([$atLimit->toJson()], JSON_THROW_ON_ERROR)))->toBe(ScheduledDriver::MAX_ARGUMENTS_LENGTH); ScheduledDriver::actionScheduler()->dispatch($atLimit); ScheduledDriver::actionScheduler()->dispatch($beyond); diff --git a/tests/Unit/Async/UniqueTest.php b/tests/Unit/Async/UniqueTest.php index 885fa57..2cb7efb 100644 --- a/tests/Unit/Async/UniqueTest.php +++ b/tests/Unit/Async/UniqueTest.php @@ -174,5 +174,5 @@ function uniqueLocks(): array ))->toJson(), true); unset($data['uniqueKey']); - expect(AsyncPayload::fromJson(json_encode($data))->uniqueKey)->toBeNull(); + expect(AsyncPayload::fromJson(json_encode($data, JSON_THROW_ON_ERROR))->uniqueKey)->toBeNull(); }); diff --git a/tests/Unit/Domain/Service/AbstractHookTest.php b/tests/Unit/Domain/Service/AbstractHookTest.php index 0c79cea..c513fec 100644 --- a/tests/Unit/Domain/Service/AbstractHookTest.php +++ b/tests/Unit/Domain/Service/AbstractHookTest.php @@ -107,6 +107,7 @@ public function handle(string $value): string // Create a class that has a method matching the hook name pattern $className = 'TestHookClass_'.uniqid(); eval(sprintf('class %s { public function myHook($a) { return $a; } }', $className)); + assert(class_exists($className)); $this->hook->add('my_hook', $className); @@ -141,6 +142,7 @@ public function myHook(): void {} it('falls back to direct instantiation when no resolver is set', function (): void { $className = 'DirectInstantiationTest_'.uniqid(); eval(sprintf('class %s { public function myHook() {} }', $className)); + assert(class_exists($className)); // No resolver set $this->hook->add('my_hook', $className); diff --git a/tests/Unit/Domain/Service/AbstractHookTrackingTest.php b/tests/Unit/Domain/Service/AbstractHookTrackingTest.php index 4e5a3cd..f276894 100644 --- a/tests/Unit/Domain/Service/AbstractHookTrackingTest.php +++ b/tests/Unit/Domain/Service/AbstractHookTrackingTest.php @@ -56,12 +56,16 @@ function trackingHook(): TrackingHook /** * Declare a class and return its name. + * + * @return class-string */ function declareHookClass(string $body, string $extends = ''): string { $name = 'TrackingFixture_'.str_replace('.', '', uniqid('', true)); eval(sprintf('class %s %s { %s }', $name, $extends === '' ? '' : 'extends '.$extends, $body)); + assert(class_exists($name)); + return $name; } @@ -415,9 +419,11 @@ function declareHookClass(string $body, string $extends = ''): string $hook->remove('init', [$class, 'handle'], 10); + $kept = $hook->callbacks('init')[0]['callback'] ?? null; + expect($hook->removed[0]['priority'])->toBe(10) ->and($hook->removed[0]['callback'][0])->toBeInstanceOf($class) - ->and($hook->removed[0]['callback'][0])->not->toBe($hook->callbacks('init')[0]['callback'][0]) + ->and($hook->removed[0]['callback'][0])->not->toBe(is_array($kept) ? $kept[0] : null) ->and($hook->callbacks('init'))->toHaveCount(1) ->and($hook->callbacks('init')[0]['priority'])->toBe(5); }); @@ -480,7 +486,7 @@ function declareHookClass(string $body, string $extends = ''): string $callbacks = $hook->callbacks('init'); expect($callbacks[1]['callback'])->toBe('replacement_fn') - ->and($callbacks[1]['handler'])->toBe('handler_fn') + ->and($callbacks[1]['handler'] ?? null)->toBe('handler_fn') ->and($callbacks[0])->not->toHaveKey('handler'); }); From bab4fa6e24d0c0d6b3df14877d37d3ceddc10268 Mon Sep 17 00:00:00 2001 From: Pollora maintainer Date: Wed, 25 Nov 2026 12:20:59 +0100 Subject: [PATCH 7/8] chore(qa): raise PHPStan to level 7 --- phpstan.neon | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/phpstan.neon b/phpstan.neon index d50092c..fc5f4c7 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -3,7 +3,7 @@ includes: - vendor/pollora/harness/presets/phpstan/base.neon parameters: - level: 6 + level: 7 paths: - src - tests From 9748706bdd4de74cf5ed1cc3d23c7da84701a674 Mon Sep 17 00:00:00 2001 From: Pollora maintainer Date: Wed, 25 Nov 2026 12:20:59 +0100 Subject: [PATCH 8/8] chore(qa): record PHPStan level 7 in the ratchet --- .harness.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.harness.json b/.harness.json index 9fb6e75..5c98d89 100644 --- a/.harness.json +++ b/.harness.json @@ -5,7 +5,7 @@ "framework" ], "ratchet": { - "phpstan_level": 6, + "phpstan_level": 7, "phpstan_baseline": 0, "coverage": 93.05, "type_coverage": 99.66,