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, diff --git a/CHANGELOG.md b/CHANGELOG.md index bb60195..d6df06e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ 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. - 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. - 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. 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 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, 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, 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(); 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'); });