From 1978354a56f82daa7a9e56be9a5fc0f142d6d49a Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Thu, 19 Nov 2026 15:52:09 +0000 Subject: [PATCH 01/14] Require queue inspection and retry checks on their contracts Laravel master adds the queue size and job inspection methods to the Queue contract and drops JsonFormatter's method_exists() checks for ExceptionHandler methods. Every Hypervel driver already implemented the inspection methods, so FailoverQueue loses its stale analysis ignores, QueueConnectionFake forwards them explicitly, and the Queue facade lists them with the contract. Porting the JsonFormatter change exposed the same check in Worker: shouldStopRetries() was only called when method_exists() found it. Exceptions::fake() forwards through __call and withoutExceptionHandling() wraps the handler, so under either the worker ignored dontRetry() and dontRetryWhen() and released the job. Unlike Laravel, the ExceptionHandler contract now requires shouldStopRetries(); the exception fake and the without-handling handler delegate it to the real handler, and the contracts README and porting guide tell custom handler authors. Port laravel/framework #62403, its facade docblock update 5817474817 and #62399 at master 30d8726227. QueueWorkerTest carries both changes, so they share this commit. Validation: the exception-fake and without-handling retry regressions fail before and pass after; Queue, Bus, Integration/Queue, Foundation, Support, Sentry, Grpc, Scout, Horizon, Integration/Horizon and Integration/Log suites, FacadeDocblocksTest, formatting and full static analysis pass. --- src/contracts/README.md | 2 + src/contracts/src/Debug/ExceptionHandler.php | 9 +- src/contracts/src/Queue/Queue.php | 64 +++++++++++++ src/docs/porting-from-laravel.md | 2 + .../InteractsWithExceptionHandling.php | 9 ++ src/log/src/Formatters/JsonFormatter.php | 6 +- src/queue/src/FailoverQueue.php | 20 ++-- src/queue/src/Worker.php | 3 +- src/support/src/Facades/Queue.php | 20 ++-- .../Testing/Fakes/ExceptionHandlerFake.php | 8 ++ .../src/Testing/Fakes/QueueConnectionFake.php | 94 +++++++++++++++++++ .../InteractsWithExceptionHandlingTest.php | 9 ++ tests/Grpc/ServerTest.php | 8 ++ tests/Queue/FailoverQueueTest.php | 50 ++++++++++ tests/Queue/PooledJobWorkerTest.php | 8 +- tests/Queue/QueueWorkerTest.php | 68 ++++++++++++++ .../Fixtures/TestCaseExceptionHandler.php | 8 ++ 17 files changed, 357 insertions(+), 31 deletions(-) diff --git a/src/contracts/README.md b/src/contracts/README.md index 3e768426aa..f77e51affc 100644 --- a/src/contracts/README.md +++ b/src/contracts/README.md @@ -11,4 +11,6 @@ The `Container` contract also requires `isScoped()`, `isScopedInstance()`, `reso The `View` contract also requires `gatherData(): array`, which exposes the data used to render the view, including shared values, for response assertions. The standard `Hypervel\View\View` already provides it. +The `ExceptionHandler` contract also requires `shouldStopRetries(Throwable $e): bool`, so handlers that wrap another handler, such as the exception fake, keep its `dontRetry()` and `dontRetryWhen()` rules for queued jobs. Extending `Hypervel\Foundation\Exceptions\Handler` supplies it. + Ported from: https://github.com/laravel/framework/tree/13.x/src/Illuminate/Contracts diff --git a/src/contracts/src/Debug/ExceptionHandler.php b/src/contracts/src/Debug/ExceptionHandler.php index 5880140170..6ff804403f 100644 --- a/src/contracts/src/Debug/ExceptionHandler.php +++ b/src/contracts/src/Debug/ExceptionHandler.php @@ -10,9 +10,6 @@ use Symfony\Component\HttpFoundation\Response; use Throwable; -/** - * @method bool shouldStopRetries(Throwable $e) - */ interface ExceptionHandler { /** @@ -58,4 +55,10 @@ public function buildContextForException(Throwable $e): array; * Register a callback to be called after an HTTP error response is rendered. */ public function afterResponse(callable $callback): void; + + // Unlike Laravel, this is required so wrapping handlers, such as the exception fake, keep the retry policy. + /** + * Determine if jobs should stop retrying for the given exception. + */ + public function shouldStopRetries(Throwable $e): bool; } diff --git a/src/contracts/src/Queue/Queue.php b/src/contracts/src/Queue/Queue.php index 89f3ddc4a4..da2687d49f 100644 --- a/src/contracts/src/Queue/Queue.php +++ b/src/contracts/src/Queue/Queue.php @@ -6,7 +6,9 @@ use DateInterval; use DateTimeInterface; +use Hypervel\Queue\Jobs\InspectedJob; use Hypervel\Support\Attributes\BootOrTestsOnly; +use Hypervel\Support\Collection; use UnitEnum; interface Queue @@ -31,11 +33,73 @@ public function delayedSize(UnitEnum|string|null $queue = null): int; */ public function reservedSize(UnitEnum|string|null $queue = null): int; + /** + * Get the number of jobs across every queue. + */ + public function totalSize(): int; + + /** + * Get the number of pending jobs across every queue. + */ + public function totalPendingSize(): int; + + /** + * Get the number of delayed jobs across every queue. + */ + public function totalDelayedSize(): int; + + /** + * Get the number of reserved jobs across every queue. + */ + public function totalReservedSize(): int; + /** * Get the creation timestamp of the oldest pending job, excluding delayed jobs. */ public function creationTimeOfOldestPendingJob(UnitEnum|string|null $queue = null): ?int; + /** + * Get the pending jobs for the given queue. + * + * @return Collection + */ + public function pendingJobs(UnitEnum|string|null $queue = null): Collection; + + /** + * Get the delayed jobs for the given queue. + * + * @return Collection + */ + public function delayedJobs(UnitEnum|string|null $queue = null): Collection; + + /** + * Get the reserved jobs for the given queue. + * + * @return Collection + */ + public function reservedJobs(UnitEnum|string|null $queue = null): Collection; + + /** + * Get all pending jobs across every queue. + * + * @return Collection + */ + public function allPendingJobs(): Collection; + + /** + * Get all delayed jobs across every queue. + * + * @return Collection + */ + public function allDelayedJobs(): Collection; + + /** + * Get all reserved jobs across every queue. + * + * @return Collection + */ + public function allReservedJobs(): Collection; + /** * Push a new job onto the queue. */ diff --git a/src/docs/porting-from-laravel.md b/src/docs/porting-from-laravel.md index e9843e7bf2..667329ae03 100644 --- a/src/docs/porting-from-laravel.md +++ b/src/docs/porting-from-laravel.md @@ -182,6 +182,8 @@ Some packages also define package-local contracts, such as `Hypervel\Permission\ Custom `Hypervel\Contracts\View\View` implementations must provide `gatherData(): array`, returning the data used to render the view, including any shared values. Extending `Hypervel\View\View` supplies it. +Custom `Hypervel\Contracts\Debug\ExceptionHandler` implementations must provide `shouldStopRetries(Throwable $e): bool`, which tells queue workers whether a job should stop retrying after the exception. Extending `Hypervel\Foundation\Exceptions\Handler` supplies it. + Custom `Hypervel\View\ViewFinderInterface` implementations must provide `prependLocation()`, `getPaths()` and `getHints()`; extending `Hypervel\View\FileViewFinder` supplies them. diff --git a/src/foundation/src/Testing/Concerns/InteractsWithExceptionHandling.php b/src/foundation/src/Testing/Concerns/InteractsWithExceptionHandling.php index 5b630f6ac1..d004b80556 100644 --- a/src/foundation/src/Testing/Concerns/InteractsWithExceptionHandling.php +++ b/src/foundation/src/Testing/Concerns/InteractsWithExceptionHandling.php @@ -169,6 +169,15 @@ public function buildContextForException(Throwable $e): array public function afterResponse(callable $callback): void { } + + /** + * Determine if jobs should stop retrying for the given exception. + */ + public function shouldStopRetries(Throwable $e): bool + { + // Retry policy is configuration, not exception handling. + return $this->originalHandler->shouldStopRetries($e); + } }; $currentExceptionHandler = app(ExceptionHandler::class); diff --git a/src/log/src/Formatters/JsonFormatter.php b/src/log/src/Formatters/JsonFormatter.php index 0a93621dee..22b65ab5de 100644 --- a/src/log/src/Formatters/JsonFormatter.php +++ b/src/log/src/Formatters/JsonFormatter.php @@ -27,10 +27,8 @@ protected function normalizeException(Throwable $e, int $depth = 0): array } // Active reports already carry this context at record level; rebuilding it can re-enter user callbacks. - if (! method_exists($handler, 'isReporting') || ! $handler->isReporting($e)) { - if (method_exists($handler, 'buildContextForException') - && is_array($normalizedHandlerExceptionContext = $this->normalize($handler->buildContextForException($e), $depth + 1)) - ) { + if (! $handler->isReporting($e)) { + if (is_array($normalizedHandlerExceptionContext = $this->normalize($handler->buildContextForException($e), $depth + 1))) { $response = array_replace($normalizedHandlerExceptionContext, $response); } elseif (method_exists($e, 'context')) { $response = array_replace($this->getExceptionContext($e, $depth), $response); diff --git a/src/queue/src/FailoverQueue.php b/src/queue/src/FailoverQueue.php index 4c205febf8..e2af20277b 100644 --- a/src/queue/src/FailoverQueue.php +++ b/src/queue/src/FailoverQueue.php @@ -87,7 +87,7 @@ public function reservedSize(UnitEnum|string|null $queue = null): int */ public function totalSize(): int { - return $this->manager->connection($this->connections[0])->totalSize(); // @phpstan-ignore method.notFound (optional driver capability outside the Queue contract) + return $this->manager->connection($this->connections[0])->totalSize(); } /** @@ -95,7 +95,7 @@ public function totalSize(): int */ public function totalPendingSize(): int { - return $this->manager->connection($this->connections[0])->totalPendingSize(); // @phpstan-ignore method.notFound (optional driver capability outside the Queue contract) + return $this->manager->connection($this->connections[0])->totalPendingSize(); } /** @@ -103,7 +103,7 @@ public function totalPendingSize(): int */ public function totalDelayedSize(): int { - return $this->manager->connection($this->connections[0])->totalDelayedSize(); // @phpstan-ignore method.notFound (optional driver capability outside the Queue contract) + return $this->manager->connection($this->connections[0])->totalDelayedSize(); } /** @@ -111,7 +111,7 @@ public function totalDelayedSize(): int */ public function totalReservedSize(): int { - return $this->manager->connection($this->connections[0])->totalReservedSize(); // @phpstan-ignore method.notFound (optional driver capability outside the Queue contract) + return $this->manager->connection($this->connections[0])->totalReservedSize(); } /** @@ -119,7 +119,7 @@ public function totalReservedSize(): int */ public function pendingJobs(UnitEnum|string|null $queue = null): Collection { - return $this->manager->connection($this->connections[0])->pendingJobs($this->resolveForwardedQueue($queue)); // @phpstan-ignore method.notFound (optional driver capability outside the Queue contract) + return $this->manager->connection($this->connections[0])->pendingJobs($this->resolveForwardedQueue($queue)); } /** @@ -127,7 +127,7 @@ public function pendingJobs(UnitEnum|string|null $queue = null): Collection */ public function delayedJobs(UnitEnum|string|null $queue = null): Collection { - return $this->manager->connection($this->connections[0])->delayedJobs($this->resolveForwardedQueue($queue)); // @phpstan-ignore method.notFound (optional driver capability outside the Queue contract) + return $this->manager->connection($this->connections[0])->delayedJobs($this->resolveForwardedQueue($queue)); } /** @@ -135,7 +135,7 @@ public function delayedJobs(UnitEnum|string|null $queue = null): Collection */ public function reservedJobs(UnitEnum|string|null $queue = null): Collection { - return $this->manager->connection($this->connections[0])->reservedJobs($this->resolveForwardedQueue($queue)); // @phpstan-ignore method.notFound (optional driver capability outside the Queue contract) + return $this->manager->connection($this->connections[0])->reservedJobs($this->resolveForwardedQueue($queue)); } /** @@ -143,7 +143,7 @@ public function reservedJobs(UnitEnum|string|null $queue = null): Collection */ public function allPendingJobs(): Collection { - return $this->manager->connection($this->connections[0])->allPendingJobs(); // @phpstan-ignore method.notFound (optional driver capability outside the Queue contract) + return $this->manager->connection($this->connections[0])->allPendingJobs(); } /** @@ -151,7 +151,7 @@ public function allPendingJobs(): Collection */ public function allDelayedJobs(): Collection { - return $this->manager->connection($this->connections[0])->allDelayedJobs(); // @phpstan-ignore method.notFound (optional driver capability outside the Queue contract) + return $this->manager->connection($this->connections[0])->allDelayedJobs(); } /** @@ -159,7 +159,7 @@ public function allDelayedJobs(): Collection */ public function allReservedJobs(): Collection { - return $this->manager->connection($this->connections[0])->allReservedJobs(); // @phpstan-ignore method.notFound (optional driver capability outside the Queue contract) + return $this->manager->connection($this->connections[0])->allReservedJobs(); } /** diff --git a/src/queue/src/Worker.php b/src/queue/src/Worker.php index 4c7752be23..a5713806d9 100644 --- a/src/queue/src/Worker.php +++ b/src/queue/src/Worker.php @@ -1631,8 +1631,7 @@ protected function markJobAsFailedIfWillExceedMaxExceptions(string $connectionNa */ protected function markJobAsFailedIfItShouldntBeRetried(string $connectionName, JobContract $job, Throwable $e): void { - if (method_exists($this->exceptions, 'shouldStopRetries') - && $this->exceptions->shouldStopRetries($e)) { + if ($this->exceptions->shouldStopRetries($e)) { $this->failJob($job, $e); } } diff --git a/src/support/src/Facades/Queue.php b/src/support/src/Facades/Queue.php index 84f89ad096..509e8674d0 100644 --- a/src/support/src/Facades/Queue.php +++ b/src/support/src/Facades/Queue.php @@ -48,20 +48,30 @@ * @method static void stopping(mixed $callback) * @method static void whenJobRunsLongerThan(\DateTimeInterface|\Carbon\CarbonInterval|int|float $threshold, callable $handler) * @method static void withoutInterruptionPolling() + * @method static \Hypervel\Support\Collection allDelayedJobs() + * @method static \Hypervel\Support\Collection allPendingJobs() + * @method static \Hypervel\Support\Collection allReservedJobs() * @method static mixed bulk(array $jobs, mixed $data = '', \UnitEnum|string|null $queue = null) * @method static int|null creationTimeOfOldestPendingJob(\UnitEnum|string|null $queue = null) + * @method static \Hypervel\Support\Collection delayedJobs(\UnitEnum|string|null $queue = null) * @method static int delayedSize(\UnitEnum|string|null $queue = null) * @method static string getConnectionName() * @method static mixed later(\DateInterval|\DateTimeInterface|int $delay, object|string $job, mixed $data = '', \UnitEnum|string|null $queue = null) * @method static mixed laterOn(\UnitEnum|string|null $queue, \DateInterval|\DateTimeInterface|int $delay, object|string $job, mixed $data = '') + * @method static \Hypervel\Support\Collection pendingJobs(\UnitEnum|string|null $queue = null) * @method static int pendingSize(\UnitEnum|string|null $queue = null) * @method static \Hypervel\Contracts\Queue\Job|null pop(\UnitEnum|string|null $queue = null) * @method static mixed push(object|string $job, mixed $data = '', \UnitEnum|string|null $queue = null) * @method static mixed pushOn(\UnitEnum|string|null $queue, object|string $job, mixed $data = '') * @method static mixed pushRaw(string $payload, \UnitEnum|string|null $queue = null, array $options = []) + * @method static \Hypervel\Support\Collection reservedJobs(\UnitEnum|string|null $queue = null) * @method static int reservedSize(\UnitEnum|string|null $queue = null) * @method static \Hypervel\Contracts\Queue\Queue setConnectionName(string $name) * @method static int size(\UnitEnum|string|null $queue = null) + * @method static int totalDelayedSize() + * @method static int totalPendingSize() + * @method static int totalReservedSize() + * @method static int totalSize() * @method static void flushState() * @method static array getConfig() * @method static \Hypervel\Contracts\Container\Container getContainer() @@ -72,9 +82,6 @@ * @method static \Hypervel\Queue\Queue setConfig(array $config) * @method static \Hypervel\Queue\Queue setContainer(\Hypervel\Contracts\Container\Container $container) * @method static \Hypervel\Support\Testing\Fakes\QueueFake afterPushing(callable $callback) - * @method static \Hypervel\Support\Collection allDelayedJobs() - * @method static \Hypervel\Support\Collection allPendingJobs() - * @method static \Hypervel\Support\Collection allReservedJobs() * @method static void assertClosureNotPushed(null|array|callable $callback = null) * @method static void assertClosurePushed(null|array|callable|int $callback = null) * @method static void assertCount(int $expectedCount) @@ -88,24 +95,17 @@ * @method static void assertPushedWithoutChain(string $job, null|array|callable $callback = null) * @method static \Hypervel\Support\Testing\Fakes\QueueFake beforePushing(callable $callback) * @method static void clearReserved() - * @method static \Hypervel\Support\Collection delayedJobs(\UnitEnum|string|null $queue = null) * @method static \Hypervel\Support\Testing\Fakes\QueueFake except(array|string $jobsToBeQueued) * @method static bool hasPushed(string $job) * @method static \Hypervel\Support\Collection listenersPushed(string $listenerClass, callable|null $callback = null) - * @method static \Hypervel\Support\Collection pendingJobs(\UnitEnum|string|null $queue = null) * @method static \Hypervel\Support\Collection pushed(string $job, null|array|callable $callback = null) * @method static array pushedJobs() * @method static \Hypervel\Support\Collection pushedRaw(null|\Closure $callback = null) * @method static array rawPushes() * @method static void releaseUniqueJobLocks() * @method static void reserve(object|string $job, \UnitEnum|string|null $queue = null) - * @method static \Hypervel\Support\Collection reservedJobs(\UnitEnum|string|null $queue = null) * @method static \Hypervel\Support\Testing\Fakes\QueueFake serializeAndRestore(bool $serializeAndRestore = true) * @method static bool shouldFakeJob(object|string $job) - * @method static int totalDelayedSize() - * @method static int totalPendingSize() - * @method static int totalReservedSize() - * @method static int totalSize() * * @see \Hypervel\Queue\QueueManager * @see \Hypervel\Queue\Queue diff --git a/src/support/src/Testing/Fakes/ExceptionHandlerFake.php b/src/support/src/Testing/Fakes/ExceptionHandlerFake.php index 3d91adbd68..80dca78253 100644 --- a/src/support/src/Testing/Fakes/ExceptionHandlerFake.php +++ b/src/support/src/Testing/Fakes/ExceptionHandlerFake.php @@ -281,6 +281,14 @@ public function buildContextForException(Throwable $e): array return $this->handler->buildContextForException($e); } + /** + * Determine if jobs should stop retrying for the given exception. + */ + public function shouldStopRetries(Throwable $e): bool + { + return $this->handler->shouldStopRetries($e); + } + /** * Handle dynamic method calls to the handler. */ diff --git a/src/support/src/Testing/Fakes/QueueConnectionFake.php b/src/support/src/Testing/Fakes/QueueConnectionFake.php index 8c465f3aa6..f33f0be1aa 100644 --- a/src/support/src/Testing/Fakes/QueueConnectionFake.php +++ b/src/support/src/Testing/Fakes/QueueConnectionFake.php @@ -8,6 +8,8 @@ use DateTimeInterface; use Hypervel\Contracts\Queue\Job; use Hypervel\Contracts\Queue\Queue; +use Hypervel\Queue\Jobs\InspectedJob; +use Hypervel\Support\Collection; use UnitEnum; /** @@ -58,6 +60,38 @@ public function reservedSize(UnitEnum|string|null $queue = null): int return $this->fake->reservedSize($queue); } + /** + * Get the number of jobs across every queue. + */ + public function totalSize(): int + { + return $this->fake->totalSize(); + } + + /** + * Get the number of pending jobs across every queue. + */ + public function totalPendingSize(): int + { + return $this->fake->totalPendingSize(); + } + + /** + * Get the number of delayed jobs across every queue. + */ + public function totalDelayedSize(): int + { + return $this->fake->totalDelayedSize(); + } + + /** + * Get the number of reserved jobs across every queue. + */ + public function totalReservedSize(): int + { + return $this->fake->totalReservedSize(); + } + /** * Get the creation timestamp of the oldest pending job, excluding delayed jobs. */ @@ -66,6 +100,66 @@ public function creationTimeOfOldestPendingJob(UnitEnum|string|null $queue = nul return $this->fake->creationTimeOfOldestPendingJob($queue); } + /** + * Get the pending jobs for the given queue. + * + * @return Collection + */ + public function pendingJobs(UnitEnum|string|null $queue = null): Collection + { + return $this->fake->pendingJobs($queue); + } + + /** + * Get the delayed jobs for the given queue. + * + * @return Collection + */ + public function delayedJobs(UnitEnum|string|null $queue = null): Collection + { + return $this->fake->delayedJobs($queue); + } + + /** + * Get the reserved jobs for the given queue. + * + * @return Collection + */ + public function reservedJobs(UnitEnum|string|null $queue = null): Collection + { + return $this->fake->reservedJobs($queue); + } + + /** + * Get all pending jobs across every queue. + * + * @return Collection + */ + public function allPendingJobs(): Collection + { + return $this->fake->allPendingJobs(); + } + + /** + * Get all delayed jobs across every queue. + * + * @return Collection + */ + public function allDelayedJobs(): Collection + { + return $this->fake->allDelayedJobs(); + } + + /** + * Get all reserved jobs across every queue. + * + * @return Collection + */ + public function allReservedJobs(): Collection + { + return $this->fake->allReservedJobs(); + } + /** * Push a new job onto the queue. */ diff --git a/tests/Foundation/Testing/Concerns/InteractsWithExceptionHandlingTest.php b/tests/Foundation/Testing/Concerns/InteractsWithExceptionHandlingTest.php index d135181885..ffdddbc2c0 100644 --- a/tests/Foundation/Testing/Concerns/InteractsWithExceptionHandlingTest.php +++ b/tests/Foundation/Testing/Concerns/InteractsWithExceptionHandlingTest.php @@ -148,6 +148,15 @@ public function testWithoutExceptionHandlingShouldReportReturnsFalse(): void $this->assertFalse($handler->shouldReport(new RuntimeException)); } + public function testWithoutExceptionHandlingKeepsTheRetryPolicy(): void + { + $this->app->make(ExceptionHandler::class)->dontRetry(RuntimeException::class); + + $this->withoutExceptionHandling(); + + $this->assertTrue($this->app->make(ExceptionHandler::class)->shouldStopRetries(new RuntimeException)); + } + public function testThrowOnReportWithoutExceptionHandling(): void { Exceptions::fake()->throwOnReport(); diff --git a/tests/Grpc/ServerTest.php b/tests/Grpc/ServerTest.php index 768a934391..466d594167 100644 --- a/tests/Grpc/ServerTest.php +++ b/tests/Grpc/ServerTest.php @@ -764,4 +764,12 @@ public function buildContextForException(Throwable $e): array public function afterResponse(callable $callback): void { } + + /** + * Determine if jobs should stop retrying for the given exception. + */ + public function shouldStopRetries(Throwable $e): bool + { + return false; + } } diff --git a/tests/Queue/FailoverQueueTest.php b/tests/Queue/FailoverQueueTest.php index 5bc689a211..2f09ac5b76 100644 --- a/tests/Queue/FailoverQueueTest.php +++ b/tests/Queue/FailoverQueueTest.php @@ -838,11 +838,61 @@ public function reservedSize(UnitEnum|string|null $queue = null): int return 0; } + public function totalSize(): int + { + return 0; + } + + public function totalPendingSize(): int + { + return 0; + } + + public function totalDelayedSize(): int + { + return 0; + } + + public function totalReservedSize(): int + { + return 0; + } + public function creationTimeOfOldestPendingJob(UnitEnum|string|null $queue = null): ?int { return null; } + public function pendingJobs(UnitEnum|string|null $queue = null): Collection + { + return new Collection; + } + + public function delayedJobs(UnitEnum|string|null $queue = null): Collection + { + return new Collection; + } + + public function reservedJobs(UnitEnum|string|null $queue = null): Collection + { + return new Collection; + } + + public function allPendingJobs(): Collection + { + return new Collection; + } + + public function allDelayedJobs(): Collection + { + return new Collection; + } + + public function allReservedJobs(): Collection + { + return new Collection; + } + public function pushOn(UnitEnum|string|null $queue, object|string $job, mixed $data = ''): mixed { return $this->push($job, $data, $queue); diff --git a/tests/Queue/PooledJobWorkerTest.php b/tests/Queue/PooledJobWorkerTest.php index bb7f8ae13d..2d2b0fc89a 100644 --- a/tests/Queue/PooledJobWorkerTest.php +++ b/tests/Queue/PooledJobWorkerTest.php @@ -131,7 +131,9 @@ public function testWorkerExceptionReleasesTheBackendBeforeReturningTheLease(): $events->expects('hasListeners')->with(JobReleasedAfterException::class)->returns(true); $events->expects('hasListeners')->with(JobAttempted::class)->returns(true); $events->expects('dispatch')->times(4)->returns([]); - $worker = new Worker(Double::for(Factory::class)->strict(), $events, Double::for(ExceptionHandler::class)->strict(), fn () => false); + $exceptions = Double::for(ExceptionHandler::class)->strict(); + $exceptions->allows('shouldStopRetries')->returns(false); + $worker = new Worker(Double::for(Factory::class)->strict(), $events, $exceptions, fn () => false); try { $worker->process('connection', $job, new WorkerOptions(maxTries: 0, backoff: 3)); @@ -171,7 +173,9 @@ public function testWorkerTerminalFailureDeletesBeforeReturningTheLease(): void $events->expects('hasListeners')->with(JobAttempted::class)->returns(true); $events->expects('dispatch')->times(4)->returns([]); $container->instance(Dispatcher::class, $events); - $worker = new Worker(Double::for(Factory::class)->strict(), $events, Double::for(ExceptionHandler::class)->strict(), fn () => false); + $exceptions = Double::for(ExceptionHandler::class)->strict(); + $exceptions->allows('shouldStopRetries')->returns(false); + $worker = new Worker(Double::for(Factory::class)->strict(), $events, $exceptions, fn () => false); try { $worker->process('connection', $job, new WorkerOptions(maxTries: 1)); diff --git a/tests/Queue/QueueWorkerTest.php b/tests/Queue/QueueWorkerTest.php index 065e5508a9..ebc8feb1f6 100644 --- a/tests/Queue/QueueWorkerTest.php +++ b/tests/Queue/QueueWorkerTest.php @@ -76,6 +76,7 @@ use Hypervel\RateLimiter\LimitResult; use Hypervel\RateLimiter\RateLimiter; use Hypervel\Support\CarbonImmutable; +use Hypervel\Support\Collection; use Hypervel\Support\Testing\Fakes\EventFake; use Hypervel\Support\Testing\Fakes\ExceptionHandlerFake; use Hypervel\Testing\ParallelTesting; @@ -849,6 +850,7 @@ public function testNonKillingTimeoutHandlesCleanupAndReportingFailures(bool $re if ($reportingMode !== 'normal') { $errorLog = $this->captureErrorLog(); $this->exceptionHandler = Double::for(ExceptionHandlerContract::class)->strict(); + $this->exceptionHandler->allows('shouldStopRetries')->returns(false); $report = $this->exceptionHandler->expects('report')->with(Argument::same($cleanupException)); if ($reportingMode === 'cancellation') { $report->resolves(function () use ($reportingFailure): never { @@ -2129,6 +2131,21 @@ public function testJobIsFailedIfExceptionHandlerSaysItShouldntRetry(): void $this->events->assertNotDispatched(JobReleasedAfterException::class); } + public function testExceptionFakeKeepsTheHandlersRetryPolicy(): void + { + $exception = new RuntimeException; + $job = new WorkerFakeJob(static function () use ($exception): never { + throw $exception; + }); + $this->exceptionHandler = new ExceptionHandlerFake(new ShouldntRetryExceptionHandler); + + $worker = $this->getWorker('default', ['queue' => [$job]]); + $worker->runNextJob('default', 'queue', $this->workerOptions(['backoff' => 10])); + + $this->assertNull($job->releaseAfter); + $this->assertSame($exception, $job->failedWith); + } + public function testExceptionIsNotReportedIfReportJobExceptionsIsDisabled(): void { $exception = new RuntimeException; @@ -3019,6 +3036,7 @@ public function testWorkerStopsWithLostConnectionReason(Throwable $failure, bool if ($reportingThrows) { $this->captureErrorLog(); $this->exceptionHandler = Double::for(ExceptionHandlerContract::class)->strict(); + $this->exceptionHandler->allows('shouldStopRetries')->returns(false); $this->exceptionHandler->expects('report')->with(Argument::same($failure))->throws(new RuntimeException('Reporting failed.')); } $workerOptions = new WorkerOptions(stopWhenEmpty: true); @@ -3958,11 +3976,61 @@ public function reservedSize(UnitEnum|string|null $queue = null): int return 0; } + public function totalSize(): int + { + return 0; + } + + public function totalPendingSize(): int + { + return 0; + } + + public function totalDelayedSize(): int + { + return 0; + } + + public function totalReservedSize(): int + { + return 0; + } + public function creationTimeOfOldestPendingJob(UnitEnum|string|null $queue = null): ?int { return null; } + public function pendingJobs(UnitEnum|string|null $queue = null): Collection + { + return new Collection; + } + + public function delayedJobs(UnitEnum|string|null $queue = null): Collection + { + return new Collection; + } + + public function reservedJobs(UnitEnum|string|null $queue = null): Collection + { + return new Collection; + } + + public function allPendingJobs(): Collection + { + return new Collection; + } + + public function allDelayedJobs(): Collection + { + return new Collection; + } + + public function allReservedJobs(): Collection + { + return new Collection; + } + public function push(object|string $job, mixed $data = '', UnitEnum|string|null $queue = null): mixed { $this->jobs[$this->normalizeQueue($queue)][] = $job; diff --git a/tests/Sentry/Fixtures/TestCaseExceptionHandler.php b/tests/Sentry/Fixtures/TestCaseExceptionHandler.php index ff10b8e285..bd3915d811 100644 --- a/tests/Sentry/Fixtures/TestCaseExceptionHandler.php +++ b/tests/Sentry/Fixtures/TestCaseExceptionHandler.php @@ -92,6 +92,14 @@ public function afterResponse(callable $callback): void $this->handler->afterResponse($callback); } + /** + * Determine if jobs should stop retrying for the given exception. + */ + public function shouldStopRetries(Throwable $e): bool + { + return $this->handler->shouldStopRetries($e); + } + /** * Forward calls to the wrapped handler. */ From deaf64f44a433f242fcb2aad6c19241955881138 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Thu, 19 Nov 2026 15:52:22 +0000 Subject: [PATCH 02/14] Render prompts statically when output is not a terminal Laravel prompts stops spinners and tasks animating when decorated output is not a terminal, since --ansi forces decoration in CI and build logs where each frame lands on its own line. Hypervel's Progress and Stream made the same assumption and now use the same check, decided once per run. Porting it exposed upstream defects: - isOutputTty() checked STDOUT for Artisan's OutputStyle and buffered outputs, so captured command output animated whenever the process ran in a terminal. It now follows getOutput() to the real destination and treats buffered outputs as non-terminals. - Static rendering still wrote cursor hide/show, moves and erases, and clear() and title() their controls, to non-terminal output. These controls and the animation decision now share Prompt::canControlTerminal(), so logs keep their text and colors. The pcntl check stays out of shouldRenderStatically(): spinners animate in a coroutine, and tasks check pcntl only when they fork. Port laravel/prompts #280 at e84c227ae8. Validation: upstream spinner, task and terminal tests ported; the non-terminal Spinner, Task, Progress, Stream, Clear and Title cases and a PTY test of each output destination fail before and pass after; Prompts, Console and Testing suites, formatting and full static analysis pass. --- src/prompts/src/Clear.php | 2 +- src/prompts/src/Concerns/Cursor.php | 10 +++--- src/prompts/src/Concerns/Erase.php | 4 +-- src/prompts/src/Concerns/FakesInputOutput.php | 1 + .../src/Concerns/RendersAnimations.php | 22 +++++++++++++ src/prompts/src/Progress.php | 14 ++++++-- src/prompts/src/Prompt.php | 13 ++++++++ src/prompts/src/Spinner.php | 4 ++- src/prompts/src/Stream.php | 3 +- src/prompts/src/Task.php | 3 +- src/prompts/src/Terminal.php | 18 ++++++++++ src/prompts/src/Title.php | 2 +- tests/Prompts/ClearPromptTest.php | 10 ++++++ tests/Prompts/Fixtures/output-tty.php | 25 ++++++++++++++ tests/Prompts/ProgressTest.php | 19 +++++++++++ tests/Prompts/SpinnerTest.php | 33 +++++++++++++++++++ tests/Prompts/StreamTest.php | 13 ++++++++ tests/Prompts/TaskTest.php | 23 +++++++++++++ tests/Prompts/TerminalTest.php | 26 +++++++++++++++ tests/Prompts/TitlePromptTest.php | 10 ++++++ 20 files changed, 240 insertions(+), 15 deletions(-) create mode 100644 src/prompts/src/Concerns/RendersAnimations.php create mode 100644 tests/Prompts/Fixtures/output-tty.php diff --git a/src/prompts/src/Clear.php b/src/prompts/src/Clear.php index eae0d22508..8b49c2f7e1 100644 --- a/src/prompts/src/Clear.php +++ b/src/prompts/src/Clear.php @@ -18,7 +18,7 @@ public function prompt(): bool $frame = $this->renderTheme(); - $this->writeDirectly(static::output()->isDecorated() ? $frame : Utils::stripTerminalControls($frame)); + $this->writeDirectly(static::canControlTerminal() ? $frame : Utils::stripTerminalControls($frame)); return true; } diff --git a/src/prompts/src/Concerns/Cursor.php b/src/prompts/src/Concerns/Cursor.php index c7618adf85..d592c1d0e6 100644 --- a/src/prompts/src/Concerns/Cursor.php +++ b/src/prompts/src/Concerns/Cursor.php @@ -18,7 +18,7 @@ trait Cursor */ public function hideCursor(): void { - if (! static::output()->isDecorated()) { + if (! static::canControlTerminal()) { return; } @@ -34,7 +34,7 @@ public function hideCursor(): void */ public function showCursor(): void { - if (! static::output()->isDecorated()) { + if (! static::canControlTerminal()) { static::$cursorHidden = false; return; @@ -60,7 +60,7 @@ public function restoreCursor(): void */ public function moveCursor(int $x, int $y = 0): void { - if (! static::output()->isDecorated()) { + if (! static::canControlTerminal()) { return; } @@ -86,7 +86,7 @@ public function moveCursor(int $x, int $y = 0): void */ public function moveCursorToColumn(int $column): void { - if (! static::output()->isDecorated()) { + if (! static::canControlTerminal()) { return; } @@ -98,7 +98,7 @@ public function moveCursorToColumn(int $column): void */ public function moveCursorUp(int $lines): void { - if (! static::output()->isDecorated()) { + if (! static::canControlTerminal()) { return; } diff --git a/src/prompts/src/Concerns/Erase.php b/src/prompts/src/Concerns/Erase.php index 7811e5b0f9..c94064768a 100644 --- a/src/prompts/src/Concerns/Erase.php +++ b/src/prompts/src/Concerns/Erase.php @@ -11,7 +11,7 @@ trait Erase */ public function eraseLines(int $count): void { - if ($count <= 0 || ! static::output()->isDecorated()) { + if ($count <= 0 || ! static::canControlTerminal()) { return; } @@ -30,7 +30,7 @@ public function eraseLines(int $count): void */ public function eraseDown(): void { - if (! static::output()->isDecorated()) { + if (! static::canControlTerminal()) { return; } diff --git a/src/prompts/src/Concerns/FakesInputOutput.php b/src/prompts/src/Concerns/FakesInputOutput.php index 477e47ceb7..68f7055fdd 100644 --- a/src/prompts/src/Concerns/FakesInputOutput.php +++ b/src/prompts/src/Concerns/FakesInputOutput.php @@ -39,6 +39,7 @@ public static function fake(array $keys = []): void $mock->shouldReceive('lines')->byDefault()->andReturn(24); $mock->shouldReceive('initDimensions')->byDefault(); $mock->shouldReceive('supportsTrueColor')->byDefault()->andReturn(false); + $mock->shouldReceive('isOutputTty')->byDefault()->andReturn(true); static::fakeKeyPresses($keys, function (string $key) use ($mock): void { $mock->shouldReceive('read')->once()->andReturn($key); diff --git a/src/prompts/src/Concerns/RendersAnimations.php b/src/prompts/src/Concerns/RendersAnimations.php new file mode 100644 index 0000000000..945b59d9a0 --- /dev/null +++ b/src/prompts/src/Concerns/RendersAnimations.php @@ -0,0 +1,22 @@ +progress = 0; $this->state = 'initial'; $this->prevFrame = ''; + $this->static = $this->shouldRenderStatically(); $this->capturePreviousNewLines(); if (function_exists('pcntl_signal') && ! Coroutine::inCoroutine()) { @@ -151,7 +159,7 @@ public function start(): void try { $this->hideCursor(); - if (static::output()->isDecorated()) { + if (! $this->static) { $this->render(); } @@ -172,7 +180,7 @@ public function advance(int $step = 1): void $this->progress = $this->total; } - if (static::output()->isDecorated()) { + if (! $this->static) { $this->render(); } } @@ -229,7 +237,7 @@ public function render(): void */ protected function renderTerminalFrame(): void { - if (static::output()->isDecorated()) { + if (! $this->static) { $this->render(); return; diff --git a/src/prompts/src/Prompt.php b/src/prompts/src/Prompt.php index 0d2467762c..8838a4546e 100644 --- a/src/prompts/src/Prompt.php +++ b/src/prompts/src/Prompt.php @@ -319,6 +319,19 @@ protected static function writeDirectly(string $message): void }; } + /** + * Determine whether cursor and screen controls can be written to the output. + * + * Unlike Laravel, this requires a terminal as well as decorated output, so + * `--ansi` output in CI and build logs keeps its colors without cursor + * movement or erasing. + */ + protected static function canControlTerminal(): bool + { + return static::output()->isDecorated() + && static::terminal()->isOutputTty(static::output()); + } + /** * Get the terminal instance. */ diff --git a/src/prompts/src/Spinner.php b/src/prompts/src/Spinner.php index a19413aed0..88874dde99 100644 --- a/src/prompts/src/Spinner.php +++ b/src/prompts/src/Spinner.php @@ -13,6 +13,8 @@ class Spinner extends Prompt { + use Concerns\RendersAnimations; + /** * How long to wait between rendering each frame. */ @@ -51,7 +53,7 @@ public function spin(Closure $callback): mixed $this->prevFrame = ''; $this->capturePreviousNewLines(); - if (! static::output()->isDecorated() || ! Coroutine::inCoroutine()) { + if ($this->shouldRenderStatically() || ! Coroutine::inCoroutine()) { return $this->renderStatically($callback); } diff --git a/src/prompts/src/Stream.php b/src/prompts/src/Stream.php index 4fd7f48e75..bd2010048f 100644 --- a/src/prompts/src/Stream.php +++ b/src/prompts/src/Stream.php @@ -14,6 +14,7 @@ class Stream extends Prompt { + use Concerns\RendersAnimations; use InteractsWithStrings; protected int $minWidth = 0; @@ -38,7 +39,7 @@ class Stream extends Prompt */ public function __construct() { - $this->direct = ! static::output()->isDecorated(); + $this->direct = $this->shouldRenderStatically(); if ($this->direct) { return; diff --git a/src/prompts/src/Task.php b/src/prompts/src/Task.php index bd713cf868..9227458803 100644 --- a/src/prompts/src/Task.php +++ b/src/prompts/src/Task.php @@ -18,6 +18,7 @@ class Task extends Prompt { + use Concerns\RendersAnimations; use Concerns\TracksTaskOutput; /** @@ -154,7 +155,7 @@ public function run(Closure $callback): mixed $this->capturePreviousNewLines(); - if (! static::output()->isDecorated()) { + if ($this->shouldRenderStatically()) { return $this->renderStatically($callback); } diff --git a/src/prompts/src/Terminal.php b/src/prompts/src/Terminal.php index debb5943dc..d97c5dfed8 100644 --- a/src/prompts/src/Terminal.php +++ b/src/prompts/src/Terminal.php @@ -4,8 +4,12 @@ namespace Hypervel\Prompts; +use Hypervel\Prompts\Output\BufferedConsoleOutput; use ReflectionClass; use RuntimeException; +use Symfony\Component\Console\Output\BufferedOutput; +use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Console\Output\StreamOutput; use Symfony\Component\Console\Terminal as SymfonyTerminal; class Terminal @@ -164,6 +168,20 @@ protected function execWithInput(string $command, $input = null): string return $stdout; } + /** + * Determine if the output is written to a terminal. + */ + public function isOutputTty(?OutputInterface $output = null): bool + { + // Unlike Laravel, Artisan's output style and buffered outputs are checked at their real destination rather than at STDOUT. + return match (true) { + $output instanceof BufferedOutput, $output instanceof BufferedConsoleOutput => false, + $output instanceof StreamOutput => stream_isatty($output->getStream()), + $output !== null && method_exists($output, 'getOutput') => $this->isOutputTty($output->getOutput()), + default => stream_isatty(STDOUT), + }; + } + /** * Determine if the terminal supports true color (24-bit). */ diff --git a/src/prompts/src/Title.php b/src/prompts/src/Title.php index 2ffdcb5a0e..63975c780e 100644 --- a/src/prompts/src/Title.php +++ b/src/prompts/src/Title.php @@ -22,7 +22,7 @@ public function prompt(): bool { $frame = $this->renderTheme(); - $this->writeDirectly(static::output()->isDecorated() ? $frame : Utils::stripTerminalControls($frame)); + $this->writeDirectly(static::canControlTerminal() ? $frame : Utils::stripTerminalControls($frame)); return true; } diff --git a/tests/Prompts/ClearPromptTest.php b/tests/Prompts/ClearPromptTest.php index dde7fd8a30..c431739033 100644 --- a/tests/Prompts/ClearPromptTest.php +++ b/tests/Prompts/ClearPromptTest.php @@ -19,4 +19,14 @@ public function testPromptClear(): void Prompt::assertOutputContains("\033[H\033[J"); } + + public function testDoesNotClearOutputThatIsNotATerminal(): void + { + Prompt::fake(); + Prompt::terminal()->shouldReceive('isOutputTty')->andReturn(false); + + clear(); + + Prompt::assertOutputDoesntContain("\033[H\033[J"); + } } diff --git a/tests/Prompts/Fixtures/output-tty.php b/tests/Prompts/Fixtures/output-tty.php new file mode 100644 index 0000000000..d224fb1da1 --- /dev/null +++ b/tests/Prompts/Fixtures/output-tty.php @@ -0,0 +1,25 @@ + new StreamOutput(fopen('php://memory', 'w')); + +echo json_encode([ + 'console' => $terminal->isOutputTty(new ConsoleOutput), + 'artisan' => $terminal->isOutputTty(new OutputStyle(new ArrayInput([]), new ConsoleOutput)), + 'memory' => $terminal->isOutputTty($memory()), + 'captured artisan' => $terminal->isOutputTty(new OutputStyle(new ArrayInput([]), $memory())), + 'buffered' => $terminal->isOutputTty(new BufferedOutput), + 'prompts buffer' => $terminal->isOutputTty(new BufferedConsoleOutput), +], JSON_THROW_ON_ERROR); diff --git a/tests/Prompts/ProgressTest.php b/tests/Prompts/ProgressTest.php index 50a8c93c7e..0ddf87758e 100644 --- a/tests/Prompts/ProgressTest.php +++ b/tests/Prompts/ProgressTest.php @@ -7,6 +7,7 @@ use Hypervel\Prompts\Output\BufferedConsoleOutput; use Hypervel\Prompts\Progress; use Hypervel\Prompts\Prompt; +use Hypervel\Prompts\Support\Utils; use Hypervel\Support\Collection; use Hypervel\Tests\TestCase; use InvalidArgumentException; @@ -88,6 +89,24 @@ public function testUndecoratedProgressEmitsOnlyOneTerminalFrame(): void $this->assertStringNotContainsString("\e", Prompt::content()); } + public function testDecoratedProgressOutsideATerminalEmitsOnlyOneFrame(): void + { + Prompt::fake(); + Prompt::terminal()->shouldReceive('isOutputTty')->andReturn(false); + $progress = new Progress('Adding States', 2); + + $progress->start(); + $progress->advance(); + $progress->advance(); + $this->assertStringNotContainsString('Adding States', Prompt::content()); + + $progress->finish(); + + $this->assertSame(1, substr_count(Prompt::content(), 'Adding States')); + $this->assertStringContainsString('2 / 2', Prompt::strippedContent()); + $this->assertSame(Utils::sanitizeTerminalFormatting(Prompt::content()), Prompt::content()); + } + public function testAbandonedUndecoratedProgressEmitsNothing(): void { Prompt::fake(); diff --git a/tests/Prompts/SpinnerTest.php b/tests/Prompts/SpinnerTest.php index 6e3548f090..3fe08cbf5c 100644 --- a/tests/Prompts/SpinnerTest.php +++ b/tests/Prompts/SpinnerTest.php @@ -10,6 +10,7 @@ use Hypervel\Prompts\Output\BufferedConsoleOutput; use Hypervel\Prompts\Prompt; use Hypervel\Prompts\Spinner; +use Hypervel\Prompts\Support\Utils; use Hypervel\Tests\TestCase; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; @@ -49,6 +50,38 @@ public function testRendersStaticallyWhenOutputIsNotDecorated(): void $this->assertStringNotContainsString("\e", $output->content()); } + public function testRendersStaticallyWhenOutputIsNotATerminalEvenIfItIsDecorated(): void + { + Prompt::fake(); + Prompt::terminal()->shouldReceive('isOutputTty')->andReturn(false); + + $output = new BufferedConsoleOutput(decorated: true); + Prompt::setOutput($output); + + $spinner = new Spinner('Running...'); + + $result = $spinner->spin(fn () => 'done'); + + $this->assertSame('done', $result); + $this->assertTrue($spinner->static); + $this->assertStringContainsString('Running...', $output->content()); + $this->assertSame(Utils::sanitizeTerminalFormatting($output->content()), $output->content()); + } + + public function testAnimatesWhenOutputIsADecoratedTerminal(): void + { + Prompt::fake(); + + $output = new BufferedConsoleOutput(decorated: true); + Prompt::setOutput($output); + + $spinner = new Spinner('Running...'); + + $spinner->spin(fn () => 'done'); + + $this->assertFalse($spinner->static); + } + public function testRestoresThePreviousSignalHandler(): void { Prompt::fake(); diff --git a/tests/Prompts/StreamTest.php b/tests/Prompts/StreamTest.php index abf78c98d2..9c40b9ccbd 100644 --- a/tests/Prompts/StreamTest.php +++ b/tests/Prompts/StreamTest.php @@ -64,6 +64,19 @@ public function testUndecoratedStreamWritesExactChunksWithoutTerminalWork(): voi $this->assertStringNotContainsString("\e", Prompt::content()); } + public function testDecoratedStreamOutsideATerminalWritesExactChunks(): void + { + Prompt::fake(); + Prompt::terminal()->shouldReceive('isOutputTty')->andReturn(false); + $stream = new Stream; + + $stream->append('Hello, '); + $stream->append("World!\nDone."); + $stream->close(); + + $this->assertSame("Hello, World!\nDone.", Prompt::content()); + } + public function testCloseRestoresCursorBeforeRetainedStreamIsDestroyed(): void { Prompt::fake(); diff --git a/tests/Prompts/TaskTest.php b/tests/Prompts/TaskTest.php index 49e3f294f5..3b0800151d 100644 --- a/tests/Prompts/TaskTest.php +++ b/tests/Prompts/TaskTest.php @@ -271,6 +271,29 @@ public function testRendersTaskAndReturnsValue(): void Prompt::assertOutputContains('Running...'); } + public function testRendersTaskStaticallyWhenOutputIsNotATerminalEvenIfItIsDecorated(): void + { + Prompt::fake(); + Prompt::terminal()->shouldReceive('isOutputTty')->andReturn(false); + + $output = new BufferedConsoleOutput(decorated: true); + Prompt::setOutput($output); + + $task = new Task(label: 'Running...', keepSummary: true); + + $result = $task->run(function (Logger $logger): string { + $logger->success('Built'); + + return 'done'; + }); + + $this->assertSame('done', $result); + $this->assertTrue($task->static); + $this->assertStringContainsString('Running...', $output->content()); + $this->assertStringContainsString('Built', $output->content()); + $this->assertSame(Utils::sanitizeTerminalFormatting($output->content()), $output->content()); + } + public function testReturnsNullWhenCallbackDoesNotReturnValue(): void { Prompt::fake(); diff --git a/tests/Prompts/TerminalTest.php b/tests/Prompts/TerminalTest.php index 10a5ba2aad..587fcb82c7 100644 --- a/tests/Prompts/TerminalTest.php +++ b/tests/Prompts/TerminalTest.php @@ -6,6 +6,8 @@ use Hypervel\Prompts\Terminal; use Hypervel\Tests\TestCase; +use Symfony\Component\Console\Output\StreamOutput; +use Symfony\Component\Process\Process; class TerminalTest extends TestCase { @@ -66,6 +68,30 @@ public function testUnavailableTtyUsesFallbackColorsWithoutQueryingTerminal(): v $this->assertSame([0, 0, 0], $terminal->backgroundColor()); $this->assertSame([], $terminal->commands); } + + public function testStreamOutputThatIsNotATerminalIsNotATty(): void + { + $output = new StreamOutput(fopen('php://memory', 'w')); + + $this->assertFalse((new Terminal)->isOutputTty($output)); + } + + public function testOutputIsCheckedAtItsDestination(): void + { + // STDOUT is a terminal here, so outputs written elsewhere must not report it. + $process = new Process([PHP_BINARY, __DIR__ . '/Fixtures/output-tty.php'], timeout: 10); + $process->setPty(true); + $process->mustRun(); + + $this->assertSame([ + 'console' => true, + 'artisan' => true, + 'memory' => false, + 'captured artisan' => false, + 'buffered' => false, + 'prompts buffer' => false, + ], json_decode($process->getOutput(), true, flags: JSON_THROW_ON_ERROR)); + } } class QueryingTerminalFixture extends Terminal diff --git a/tests/Prompts/TitlePromptTest.php b/tests/Prompts/TitlePromptTest.php index 4ce1b88ef8..721c11bf4e 100644 --- a/tests/Prompts/TitlePromptTest.php +++ b/tests/Prompts/TitlePromptTest.php @@ -19,4 +19,14 @@ public function testUpdatesTheTitle(): void Prompt::assertOutputContains("\033]0;Hello, World!\007"); } + + public function testDoesNotUpdateTheTitleWhenOutputIsNotATerminal(): void + { + Prompt::fake(); + Prompt::terminal()->shouldReceive('isOutputTty')->andReturn(false); + + title('Hello, World!'); + + $this->assertSame('', Prompt::content()); + } } From c91377888afcb5a1cf3bfec4fcceb6a758cb6661 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:02:40 +0000 Subject: [PATCH 03/14] Size prompts from the terminal showing their output Prompts read the terminal size on every redraw through Symfony's Terminal, which runs `stty -a` on the inherited STDIN. With piped input the query failed, so prompts assumed 80x50 even when their output was a terminal. Symfony also keeps no failed result, so every later read started another process: 20 progress steps with piped input ran 109 queries. Laravel has the same defect. Terminal::initDimensions() now runs `stty size` on the first standard stream that is a terminal, in the order STDOUT, STDERR, STDIN, so output on stderr is sized correctly while stdout is piped. It skips the query when COLUMNS and LINES are set, since Symfony uses them directly, and stores the fallback after a failed query. cols() and lines() read the size once before the first redraw, so prompts that size themselves in their constructors see the same terminal. Found while porting laravel/prompts #280 (e84c227ae8). Validation: PTY tests with piped input, and with piped input and stdout while stderr is the terminal, fail before and pass after; the Prompts suite, formatting and full static analysis pass. --- src/prompts/src/Terminal.php | 53 ++++++++++++++++++++++-- tests/Prompts/Fixtures/terminal-size.php | 11 +++++ tests/Prompts/TerminalTest.php | 25 +++++++++++ 3 files changed, 85 insertions(+), 4 deletions(-) create mode 100644 tests/Prompts/Fixtures/terminal-size.php diff --git a/src/prompts/src/Terminal.php b/src/prompts/src/Terminal.php index d97c5dfed8..8db31b3bac 100644 --- a/src/prompts/src/Terminal.php +++ b/src/prompts/src/Terminal.php @@ -5,7 +5,7 @@ namespace Hypervel\Prompts; use Hypervel\Prompts\Output\BufferedConsoleOutput; -use ReflectionClass; +use ReflectionProperty; use RuntimeException; use Symfony\Component\Console\Output\BufferedOutput; use Symfony\Component\Console\Output\OutputInterface; @@ -43,6 +43,11 @@ class Terminal */ protected SymfonyTerminal $terminal; + /** + * Whether the terminal dimensions have been read. + */ + protected bool $dimensionsRead = false; + /** * Create a new Terminal instance. */ @@ -96,6 +101,10 @@ public function restoreTty(): void */ public function cols(): int { + if (! $this->dimensionsRead) { + $this->initDimensions(); + } + return $this->terminal->getWidth(); } @@ -104,6 +113,10 @@ public function cols(): int */ public function lines(): int { + if (! $this->dimensionsRead) { + $this->initDimensions(); + } + return $this->terminal->getHeight(); } @@ -112,9 +125,41 @@ public function lines(): int */ public function initDimensions(): void { - (new ReflectionClass($this->terminal)) - ->getMethod('initDimensions') - ->invoke($this->terminal); + $this->dimensionsRead = true; + + // Symfony uses explicit dimensions directly, so querying the terminal would only start a process. + if (getenv('COLUMNS') !== false && getenv('LINES') !== false) { + return; + } + + // Unlike Laravel, a terminal showing output is queried first: Symfony's query reads STDIN, so piped input hid the size. + $tty = match (true) { + stream_isatty(STDOUT) => STDOUT, + stream_isatty(STDERR) => STDERR, + stream_isatty(STDIN) => STDIN, + default => null, + }; + + $size = []; + + if ($tty !== null) { + try { + preg_match('/^(?\d+) (?\d+)$/', trim($this->execWithInput('stty size', $tty)), $size); + } catch (RuntimeException) { + // The configured or fallback dimensions below still apply. + } + } + + // Symfony does not cache a failed query, so its getters would otherwise query again on every call. + foreach (['width' => 80, 'height' => 50] as $name => $fallback) { + $property = new ReflectionProperty(SymfonyTerminal::class, $name); + + if (isset($size[$name])) { + $property->setValue(null, (int) $size[$name]); + } elseif ($property->getValue() === null) { + $property->setValue(null, $fallback); + } + } } /** diff --git a/tests/Prompts/Fixtures/terminal-size.php b/tests/Prompts/Fixtures/terminal-size.php new file mode 100644 index 0000000000..702aba1e09 --- /dev/null +++ b/tests/Prompts/Fixtures/terminal-size.php @@ -0,0 +1,11 @@ +cols(), $terminal->lines()], JSON_THROW_ON_ERROR); diff --git a/tests/Prompts/TerminalTest.php b/tests/Prompts/TerminalTest.php index 587fcb82c7..d063cc4268 100644 --- a/tests/Prompts/TerminalTest.php +++ b/tests/Prompts/TerminalTest.php @@ -6,6 +6,7 @@ use Hypervel\Prompts\Terminal; use Hypervel\Tests\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; use Symfony\Component\Console\Output\StreamOutput; use Symfony\Component\Process\Process; @@ -69,6 +70,30 @@ public function testUnavailableTtyUsesFallbackColorsWithoutQueryingTerminal(): v $this->assertSame([], $terminal->commands); } + #[DataProvider('redirectedStreams')] + public function testSizesTheTerminalShowingOutput(string $redirection): void + { + $process = Process::fromShellCommandline('stty rows 30 cols 70 && "${:PHP}" "${:FIXTURE}" ' . $redirection, timeout: 10); + $process->setPty(true); + $process->mustRun(env: [ + 'PHP' => PHP_BINARY, + 'FIXTURE' => __DIR__ . '/Fixtures/terminal-size.php', + 'COLUMNS' => false, + 'LINES' => false, + ]); + + $this->assertSame([70, 30], json_decode($process->getOutput(), true, flags: JSON_THROW_ON_ERROR)); + } + + public static function redirectedStreams(): array + { + return [ + 'piped input' => ['< /dev/null'], + // Process keeps stderr on a pipe in PTY mode, so stderr is pointed at the terminal first. + 'piped input and stdout' => ['2>&0 < /dev/null | cat'], + ]; + } + public function testStreamOutputThatIsNotATerminalIsNotATty(): void { $output = new StreamOutput(fopen('php://memory', 'w')); From bb819a169c4127027d26c85ea8e75c8ecbc07323 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:02:40 +0000 Subject: [PATCH 04/14] Limit automatic progress bar redraws Every Progress::advance() redrew the bar, and each redraw reads the terminal size through a subprocess. 3,000 fast steps started 3,002 processes and took 6.4 seconds instead of 3.5. advance() now redraws at most every 40 ms, matching Symfony's ProgressBar limit of 25 frames per second. Each step still counts immediately, and the final step, start(), finish(), errors and explicit render() calls draw at once, so a finished bar always shows the final count. 3,000 fast steps now start 3 processes; resizing mid-run behaves as before. Validation: ProgressTest's rendering cases take 41 ms per step so every step is still drawn; a new test checks that fast advances skip intermediate frames and still draw the final count, and fails without the limit; the Prompts suite, formatting and full static analysis pass. --- src/prompts/src/Progress.php | 15 ++++++++++++++- tests/Prompts/ProgressTest.php | 25 ++++++++++++++++++++++++- 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/src/prompts/src/Progress.php b/src/prompts/src/Progress.php index 830fce27be..c8c9a0bb44 100644 --- a/src/prompts/src/Progress.php +++ b/src/prompts/src/Progress.php @@ -20,6 +20,11 @@ class Progress extends Prompt { use Concerns\RendersAnimations; + /** + * The minimum time between automatic redraws, matching Symfony's 25 frames per second. + */ + protected const int REDRAW_INTERVAL_NANOSECONDS = 40_000_000; + /** * The current progress bar item count. */ @@ -35,6 +40,11 @@ class Progress extends Prompt */ protected bool $static = false; + /** + * When the progress bar was last rendered, in nanoseconds. + */ + protected int $renderedAt = 0; + /** * The original value of pcntl_async_signals. */ @@ -180,7 +190,8 @@ public function advance(int $step = 1): void $this->progress = $this->total; } - if (! $this->static) { + // Unlike Laravel, automatic redraws are limited, because each one reads the terminal size through a subprocess. + if (! $this->static && ($this->progress === $this->total || hrtime(true) - $this->renderedAt >= self::REDRAW_INTERVAL_NANOSECONDS)) { $this->render(); } } @@ -230,6 +241,8 @@ private function settleOperation(?Throwable $failure = null): ?Throwable public function render(): void { parent::render(); + + $this->renderedAt = hrtime(true); } /** diff --git a/tests/Prompts/ProgressTest.php b/tests/Prompts/ProgressTest.php index 0ddf87758e..848370bf12 100644 --- a/tests/Prompts/ProgressTest.php +++ b/tests/Prompts/ProgressTest.php @@ -23,6 +23,11 @@ class ProgressTest extends TestCase { + /** + * A step duration longer than the redraw interval, so every step is drawn. + */ + private const int STEP_MICROSECONDS = 41_000; + public function testMaterializesGeneratorOnceAndPreservesValueOrder(): void { Prompt::fake(); @@ -107,6 +112,22 @@ public function testDecoratedProgressOutsideATerminalEmitsOnlyOneFrame(): void $this->assertSame(Utils::sanitizeTerminalFormatting(Prompt::content()), Prompt::content()); } + public function testFastAdvancesSkipIntermediateRedrawsButDrawTheFinalStep(): void + { + Prompt::fake(); + $progress = new Progress('Working', 100); + + $progress->start(); + + for ($i = 0; $i < 100; ++$i) { + $progress->advance(); + } + + $this->assertSame(100, $progress->progress); + $this->assertLessThan(100, substr_count(Prompt::strippedContent(), ' / 100')); + $this->assertStringContainsString('100 / 100', Prompt::strippedContent()); + } + public function testAbandonedUndecoratedProgressEmitsNothing(): void { Prompt::fake(); @@ -355,7 +376,7 @@ public function testRendersProgressBar($steps): void progress( label: 'Adding States', steps: $steps, - callback: fn () => null, + callback: fn () => usleep(self::STEP_MICROSECONDS), ); Prompt::assertStrippedOutputContains(<<<'OUTPUT' @@ -446,6 +467,7 @@ public function testCanUpdateLabelAndHintWhileRendering(): void label: 'Adding States', steps: $states, callback: function ($item, $progress) { + usleep(self::STEP_MICROSECONDS); $progress->label(strtoupper($item)); $progress->hint(strtolower($item)); } @@ -510,6 +532,7 @@ public function testCanUpdateLabelAndHintInManualMode(): void $progress->start(); foreach ($states as $state) { + usleep(self::STEP_MICROSECONDS); $progress ->label(strtoupper($state)) ->hint(strtolower($state)) From ef8ef6f013a8d2f8383b6edfe0801d53ce6a3054 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:02:44 +0000 Subject: [PATCH 05/14] Document Hypervel PHPStan setup and inline ignore identifiers --- src/docs/porting-from-laravel.md | 6 ++---- src/phpstan/README.md | 3 +-- src/phpstan/extension.neon | 2 -- tests/PHPStan/Type/GeneralTypeTest.php | 3 ++- 4 files changed, 5 insertions(+), 9 deletions(-) diff --git a/src/docs/porting-from-laravel.md b/src/docs/porting-from-laravel.md index 667329ae03..6c7562194e 100644 --- a/src/docs/porting-from-laravel.md +++ b/src/docs/porting-from-laravel.md @@ -524,11 +524,9 @@ Replace `laravel/doctor` with `hypervel/doctor` and the `Laravel\Doctor` namespa ### Static Analysis -Replace `larastan/larastan` with `hypervel/phpstan`. For manual configuration, replace Larastan's include with `vendor/hypervel/phpstan/extension.neon` and `vendor/phpstan/phpstan-deprecation-rules/rules.neon`. +Use `hypervel/phpstan` and start with the configuration in the [Static Analysis guide](/docs/{{version}}/static-analysis). -Rename ignored identifiers from `larastan.*` to `hypervel.*`, and `rules.modelAppends` to `hypervel.modelAppends`. PHPStan's own identifiers are unchanged. Remove ignores for Octane and deferred provider diagnostics, and remove the unsupported `checkOctaneCompatibility`, `generalizeEnvReturnType` and `redisDriver` parameters. - -Supported parameters retain their names, but several defaults are stricter. The extension also reports ignores without reasons and uses of deprecated APIs. See [Static Analysis](/docs/{{version}}/static-analysis) for setup and configuration. +Review inline `@phpstan-ignore` comments in ported code. Remove ignores for Octane and deferred providers. Replace the `larastan.` prefix with `hypervel.` on remaining ignores, and replace `rules.modelAppends` with `hypervel.modelAppends`. Hypervel also reports ignores without reasons and uses of deprecated APIs. ### Scheduling diff --git a/src/phpstan/README.md b/src/phpstan/README.md index 760b20301a..8248b541b7 100644 --- a/src/phpstan/README.md +++ b/src/phpstan/README.md @@ -15,10 +15,9 @@ Documentation: https://hypervel.org/docs/static-analysis - Collections keep Laravel's covariant value type, so a `Collection` is accepted where a `Collection` is expected. Upstream's stubs make it invariant. With bleeding edge, PHPStan does not widen a covariant value type it has already inferred, so a call such as `collect([1, 2, 3])->push(4)` is reported. See [Collection Types](https://hypervel.org/docs/static-analysis#collection-types). - `now()`, `today()` and the `Date` facade return `CarbonInterface`, as declared, rather than the date class configured when analysis runs. Code that needs a specific class should convert the value, for example with `toImmutable()`. - Configuration value types apply to reads through the `config()` helper, the `Config` facade and application-container calls such as `app('config')`. A repository received as a parameter or property, or created with `new Repository($items)`, keeps its declared return types. Upstream applies the application's configuration types to `get()` on any `Repository` instance. See [Configuration and Services](https://hypervel.org/docs/static-analysis#configuration-and-services). -- The `generalizeEnvReturnType` and `redisDriver` settings are omitted. An `env()` default does not decide the type of the value it reads, and Redis types always describe Hypervel's phpredis connection. - Request input getters return the types the input can hold. A keyed `query()`, `post()` or `cookie()` value can be a string, number, boolean, array or `Stringable`, a keyed `server()` or `route()` value is `mixed`, and `header()` can return null even with a default. Whole query, post, cookie and file arrays have `array-key` keys, because a query string or JSON list body can use integer keys. Upstream's narrower types do not cover these values. `FormRequest::validated()` and `safe($keys)` return `array` for the same reason. - `Storage::disk()` and `FilesystemManager::disk()` are typed per disk from the booted configuration, such as `ClientPooledFilesystem` for a pooled S3 disk, instead of always `FilesystemAdapter`. Calls the `Storage` facade forwards to the default disk use that disk's methods. `Storage::cloud()` is not supported. -- Connection-bound Redis methods such as `client()` and `auth()` are reported when called through `Redis::connection()` or the manager, because the pooled proxy rejects them. Call them on a held connection from `Redis::withConnection()`. +- Connection-bound phpredis methods such as `client()` and `auth()` are reported when called through `Redis::connection()` or the manager, because the pooled proxy rejects them. Call them on a held connection from `Redis::withConnection()`. - A builder method called through a relation returns the relation only when it is declared to return `static` or `$this`, as a relation returns itself when the builder returns itself. Upstream does so for any builder result. `static` is treated as the fluent convention, not proof of identity, so a custom `static` method that returns a clone is still typed as the relation; declare `$this` where identity matters. Builder's own `clone()`, `cloneWithout()`, `cloneWithoutBindings()` and `applyScopes()` return the builder. - A `@method scopeActive()` tag does not add an `active()` scope, because Eloquent only calls scope methods that exist. Upstream adds one. - The model visibility rule makes only a private scope or accessor protected automatically. A public one may be called directly from other files, so it is reported without a fix. diff --git a/src/phpstan/extension.neon b/src/phpstan/extension.neon index 7c088285c1..d4581f3a3b 100644 --- a/src/phpstan/extension.neon +++ b/src/phpstan/extension.neon @@ -31,7 +31,6 @@ parameters: checkMissingTranslations: true checkModelAppends: true checkModelMethodVisibility: true - # generalizeEnvReturnType is omitted: env() declares its return type, which a default does not decide. checkConfigTypes: true checkAuthCallsWhenInRequestScope: false parseModelCastsMethod: true @@ -72,7 +71,6 @@ parameters: noLegacyQueueProperties: true noPipeSeparatedValidationRules: true checkRedisConnectionBoundMethods: true - # redisDriver is omitted: Redis types always describe Hypervel's phpredis connection. # Builder macros added by model traits' global scopes: trait => interface declaring the macros. eloquentBuilderMacros: Hypervel\Database\Eloquent\SoftDeletes: Hypervel\PHPStan\Methods\Macros\SoftDeletingMacros diff --git a/tests/PHPStan/Type/GeneralTypeTest.php b/tests/PHPStan/Type/GeneralTypeTest.php index 0470be1be7..023ba84436 100644 --- a/tests/PHPStan/Type/GeneralTypeTest.php +++ b/tests/PHPStan/Type/GeneralTypeTest.php @@ -110,10 +110,11 @@ public static function dataFileAsserts(): iterable yield from self::gatherAssertTypes(__DIR__ . '/data/paginator-extension.php'); // REMOVED: passthru.php; it asserts Laravel releases before 12.15. yield from self::gatherAssertTypes(__DIR__ . '/data/passthru-l12-15.php'); + // REMOVED: PivotTypesInCollectionsTest.php; Hypervel always keeps pivot types, so the cases need no separate configuration. yield from self::gatherAssertTypes(__DIR__ . '/data/query-builder.php'); // Upstream runs this per redisDriver setting; Hypervel only has phpredis, so it runs once here. yield from self::gatherAssertTypes(__DIR__ . '/data/redis-driver-phpredis.php'); - // REMOVED: RedisDriverNullTypeTest.php and RedisDriverPredisTypeTest.php; the redisDriver setting is omitted. + // REMOVED: RedisDriverNullTypeTest.php and RedisDriverPredisTypeTest.php; Hypervel only uses phpredis. yield from self::gatherAssertTypes(__DIR__ . '/data/relationship-query-callbacks.php'); yield from self::gatherAssertTypes(__DIR__ . '/data/relation-of-type.php'); yield from self::gatherAssertTypes(__DIR__ . '/data/request-header.php'); From eea069d8bedd7361ff229503a7e53d0915e1b2d1 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:03:54 +0000 Subject: [PATCH 06/14] Port Larastan's pivot accessor, SoftDeletes and passthru type tests Hypervel already analyzes these cases. Framework PHPDoc types as() and using() with the pivot accessor, and collections keep each model's pivot because they are covariant. SoftDeletes builder methods keep static and template model types through SoftDeletingMacros. BuilderHelper reads insertOrIgnoreReturning from each builder's own $passthru list. Upstream's regression cases now run in GeneralTypeTest. Adaptations: - belongs-to-many-pivot-accessor.php: paginators keep their third type argument, a literal-union accessor gives optional properties as Laravel's types do, and template collections keep the pivot. - pivot-types-in-collections.php runs with the default configuration, since Hypervel always keeps pivot types; upstream's separate test harness is not needed. - passthru-l13-30-1.php expects Collection, the rows Hypervel's query builder declares, without upstream's version gate. The Collection Types docs now show that many-to-many results keep their pivot, including a custom as() accessor. Port larastan/larastan #2634, #2617 and direct commit ad65a795d8 at 3.x 7379a05a. Validation: GeneralTypeTest passes (2,258 assertions); formatting and full static analysis pass. --- src/docs/static-analysis.md | 12 +++ tests/PHPStan/Type/GeneralTypeTest.php | 4 + .../data/belongs-to-many-pivot-accessor.php | 83 +++++++++++++++++++ tests/PHPStan/Type/data/passthru-l13-30-1.php | 28 +++++++ .../Type/data/pivot-types-in-collections.php | 62 ++++++++++++++ .../Type/data/soft-deletes-static-builder.php | 68 +++++++++++++++ 6 files changed, 257 insertions(+) create mode 100644 tests/PHPStan/Type/data/belongs-to-many-pivot-accessor.php create mode 100644 tests/PHPStan/Type/data/passthru-l13-30-1.php create mode 100644 tests/PHPStan/Type/data/pivot-types-in-collections.php create mode 100644 tests/PHPStan/Type/data/soft-deletes-static-builder.php diff --git a/src/docs/static-analysis.md b/src/docs/static-analysis.md index 29304049ea..19d7f61926 100644 --- a/src/docs/static-analysis.md +++ b/src/docs/static-analysis.md @@ -301,6 +301,18 @@ Declare the type the collection is meant to hold when you create it: $ids = collect([1, 2, 3]); ``` +Models loaded through a `BelongsToMany` or `MorphToMany` relation keep their pivot in collections too, including a custom accessor name set with `as()`: + +```php +/** @return BelongsToMany */ +public function podcasts(): BelongsToMany +{ + return $this->belongsToMany(Podcast::class)->as('subscription')->using(Subscription::class); +} + +$user->podcasts->first()?->subscription; // Subscription|null +``` + A custom collection class that fixes its item type, such as a `UserCollection` that extends `Collection`, keeps that type when methods such as `map()`, `mapWithKeys()`, `groupBy()` and `chunk()` return the same class holding other items. This is a PHPStan limitation. For example, `$users->groupBy('team_id')` is typed as a `UserCollection` of users, although it holds user collections. Declare the result's type where your code relies on it: ```php diff --git a/tests/PHPStan/Type/GeneralTypeTest.php b/tests/PHPStan/Type/GeneralTypeTest.php index 023ba84436..f4c07a438e 100644 --- a/tests/PHPStan/Type/GeneralTypeTest.php +++ b/tests/PHPStan/Type/GeneralTypeTest.php @@ -32,6 +32,7 @@ public static function dataFileAsserts(): iterable yield from self::gatherAssertTypes(__DIR__ . '/data/artisan.php'); yield from self::gatherAssertTypes(__DIR__ . '/data/auth.php'); yield from self::gatherAssertTypes(__DIR__ . '/data/benchmark.php'); + yield from self::gatherAssertTypes(__DIR__ . '/data/belongs-to-many-pivot-accessor.php'); yield from self::gatherAssertTypes(__DIR__ . '/data/builder-of-type.php'); yield from self::gatherAssertTypes(__DIR__ . '/data/bug-1346.php'); yield from self::gatherAssertTypes(__DIR__ . '/data/bug-1565.php'); @@ -110,6 +111,8 @@ public static function dataFileAsserts(): iterable yield from self::gatherAssertTypes(__DIR__ . '/data/paginator-extension.php'); // REMOVED: passthru.php; it asserts Laravel releases before 12.15. yield from self::gatherAssertTypes(__DIR__ . '/data/passthru-l12-15.php'); + yield from self::gatherAssertTypes(__DIR__ . '/data/passthru-l13-30-1.php'); + yield from self::gatherAssertTypes(__DIR__ . '/data/pivot-types-in-collections.php'); // REMOVED: PivotTypesInCollectionsTest.php; Hypervel always keeps pivot types, so the cases need no separate configuration. yield from self::gatherAssertTypes(__DIR__ . '/data/query-builder.php'); // Upstream runs this per redisDriver setting; Hypervel only has phpredis, so it runs once here. @@ -122,6 +125,7 @@ public static function dataFileAsserts(): iterable // Upstream never registers request-user.php, which shares request-object.php's namespace. yield from self::gatherAssertTypes(__DIR__ . '/data/request-user.php'); yield from self::gatherAssertTypes(__DIR__ . '/data/route.php'); + yield from self::gatherAssertTypes(__DIR__ . '/data/soft-deletes-static-builder.php'); yield from self::gatherAssertTypes(__DIR__ . '/data/storage-disks.php'); yield from self::gatherAssertTypes(__DIR__ . '/data/tappable.php'); yield from self::gatherAssertTypes(__DIR__ . '/data/throw.php'); diff --git a/tests/PHPStan/Type/data/belongs-to-many-pivot-accessor.php b/tests/PHPStan/Type/data/belongs-to-many-pivot-accessor.php new file mode 100644 index 0000000000..683f8f2929 --- /dev/null +++ b/tests/PHPStan/Type/data/belongs-to-many-pivot-accessor.php @@ -0,0 +1,83 @@ + */ + public function podcasts(): BelongsToMany + { + return $this->belongsToMany(Podcast::class)->as('subscription')->using(Subscription::class); + } + + /** @return BelongsToMany */ + public function defaultPodcasts(): BelongsToMany + { + return $this->belongsToMany(Podcast::class); + } + + /** @return MorphToMany */ + public function tags(): MorphToMany + { + return $this->morphToMany(Tag::class, 'taggable')->as('tagging'); + } +} + +function test(Member $member, string $name, bool $condition): void +{ + assertType('(BelongsToManyPivotAccessor\Podcast&object{subscription: BelongsToManyPivotAccessor\Subscription})|null', $member->podcasts()->first()); + assertType('BelongsToManyPivotAccessor\Subscription', $member->podcasts()->firstOrFail()->subscription); + assertType('BelongsToManyPivotAccessor\Podcast&object{subscription: BelongsToManyPivotAccessor\Subscription}', $member->podcasts()->findOrFail(1)); + assertType('Hypervel\Pagination\LengthAwarePaginator>', $member->podcasts()->paginate()); + assertType('Hypervel\Support\LazyCollection', $member->podcasts()->cursor()); + + $member->podcasts()->each(function ($podcast) { + assertType('BelongsToManyPivotAccessor\Podcast&object{subscription: BelongsToManyPivotAccessor\Subscription}', $podcast); + }); + + $member->podcasts()->chunk(10, function ($podcasts) { + assertType('Hypervel\Database\Eloquent\Collection', $podcasts); + }); + + assertType('(BelongsToManyPivotAccessor\Podcast&object{subscription: BelongsToManyPivotAccessor\Subscription})|null', $member->belongsToMany(Podcast::class, 'a')->as('subscription')->using(Subscription::class)->first()); + assertType('(BelongsToManyPivotAccessor\Podcast&object{subscription: Hypervel\Database\Eloquent\Relations\Pivot})|null', $member->belongsToMany(Podcast::class, 'b')->as('subscription')->first()); + assertType('(BelongsToManyPivotAccessor\Podcast&object{pivot: Hypervel\Database\Eloquent\Relations\Pivot})|null', $member->defaultPodcasts()->first()); + assertType('(BelongsToManyPivotAccessor\Tag&object{tagging: Hypervel\Database\Eloquent\Relations\MorphPivot})|null', $member->tags()->first()); + + // Without a single known accessor, no pivot property can be promised. + assertType('BelongsToManyPivotAccessor\Podcast|null', $member->belongsToMany(Podcast::class, 'c')->as($name)->first()); + // Unlike upstream, and as Laravel's own types do, each possible accessor is an optional property. + assertType('(BelongsToManyPivotAccessor\Podcast&object{a?: Hypervel\Database\Eloquent\Relations\Pivot, b?: Hypervel\Database\Eloquent\Relations\Pivot})|null', $member->belongsToMany(Podcast::class, 'd')->as($condition ? 'a' : 'b')->first()); +} + +/** + * @template TModel of Model + * @param BelongsToMany $relation + */ +function testTemplate(BelongsToMany $relation): void +{ + // Unlike upstream, collections keep the pivot; see pivot-types-in-collections.php. + assertType('Hypervel\Database\Eloquent\Collection', $relation->get()); + assertType('Hypervel\Database\Eloquent\Collection', $relation->getResults()); + assertType('Hypervel\Database\Eloquent\Collection', $relation->findMany([1, 2])); +} diff --git a/tests/PHPStan/Type/data/passthru-l13-30-1.php b/tests/PHPStan/Type/data/passthru-l13-30-1.php new file mode 100644 index 0000000000..daf141a870 --- /dev/null +++ b/tests/PHPStan/Type/data/passthru-l13-30-1.php @@ -0,0 +1,28 @@ +', User::query()->insertOrIgnoreReturning([])); +} + +class Post extends Model +{ +} + +/** @extends Builder */ +class PassthruBuilder extends Builder +{ + public function test(): void + { + assertType('Hypervel\Support\Collection', $this->insertOrIgnoreReturning([])); + } +} diff --git a/tests/PHPStan/Type/data/pivot-types-in-collections.php b/tests/PHPStan/Type/data/pivot-types-in-collections.php new file mode 100644 index 0000000000..88dff996b0 --- /dev/null +++ b/tests/PHPStan/Type/data/pivot-types-in-collections.php @@ -0,0 +1,62 @@ + */ + public function podcasts(): BelongsToMany + { + return $this->belongsToMany(Podcast::class)->as('subscription')->using(Subscription::class); + } +} + +function test(User $user, Post $post, Member $member, User|Account $union): void +{ + assertType('App\RoleCollection', $user->roles); + assertType('Hypervel\Database\Eloquent\Relations\Pivot', $user->roles->firstOrFail()->pivot); + assertType('Hypervel\Database\Eloquent\Collection', $user->posts); + assertType('Hypervel\Database\Eloquent\Collection', $union->posts); + assertType('Hypervel\Database\Eloquent\Collection', $post->tags); + assertType('App\RoleCollection', $user->roles()->findMany([1, 2])); + assertType('App\RoleCollection', $user->roles()->get()); + assertType('App\RoleCollection', $user->roles()->where('name', 'admin')->get(['name'])); + assertType('App\RoleCollection', $user->roles()->getResults()); + + assertType('Hypervel\Database\Eloquent\Collection', $member->podcasts); + assertType('PivotTypesInCollections\Subscription', $member->podcasts->firstOrFail()->subscription); + assertType('Hypervel\Database\Eloquent\Collection', $member->podcasts()->findMany([1, 2])); + assertType('Hypervel\Database\Eloquent\Collection', $member->podcasts()->get()); + assertType('Hypervel\Database\Eloquent\Collection', $member->podcasts()->getResults()); + + // Relations without a pivot are unaffected. + assertType('App\AccountCollection', $user->accounts); +} + +/** + * @template TModel of Model + * @param BelongsToMany $relation + */ +function testTemplate(BelongsToMany $relation): void +{ + assertType('Hypervel\Database\Eloquent\Collection', $relation->get()); + assertType('Hypervel\Database\Eloquent\Collection', $relation->getResults()); + assertType('Hypervel\Database\Eloquent\Collection', $relation->findMany([1, 2])); +} diff --git a/tests/PHPStan/Type/data/soft-deletes-static-builder.php b/tests/PHPStan/Type/data/soft-deletes-static-builder.php new file mode 100644 index 0000000000..93de9cabc1 --- /dev/null +++ b/tests/PHPStan/Type/data/soft-deletes-static-builder.php @@ -0,0 +1,68 @@ + + */ +class RenamedTemplateBuilder extends Builder +{ +} + +class Post extends Model +{ + use SoftDeletes; + + /** @param Builder $query */ + public function staticBuilder(Builder $query): void + { + assertType('Hypervel\Database\Eloquent\Builder', $query->onlyTrashed()); + assertType('Hypervel\Database\Eloquent\Builder', $query->withTrashed()); + assertType('Hypervel\Database\Eloquent\Builder', $query->withoutTrashed()); + assertType('Hypervel\Database\Eloquent\Builder', $query->onlyTrashed()->where('id', 1)); + assertType('static(SoftDeletesStaticBuilder\Post)', $query->restoreOrCreate(['id' => 1])); + assertType('static(SoftDeletesStaticBuilder\Post)', $query->createOrRestore(['id' => 1])); + assertType('int', $query->restore()); + } + + /** @param Builder<$this> $query */ + public function thisBuilder(Builder $query): void + { + assertType('Hypervel\Database\Eloquent\Builder<$this(SoftDeletesStaticBuilder\Post)>', $query->onlyTrashed()); + assertType('$this(SoftDeletesStaticBuilder\Post)', $query->restoreOrCreate(['id' => 1])); + } + + /** @param RenamedTemplateBuilder $query */ + public function renamedTemplateBuilder(RenamedTemplateBuilder $query): void + { + assertType('SoftDeletesStaticBuilder\RenamedTemplateBuilder', $query->onlyTrashed()); + assertType('static(SoftDeletesStaticBuilder\Post)', $query->restoreOrCreate(['id' => 1])); + assertType('static(SoftDeletesStaticBuilder\Post)', $query->createOrRestore(['id' => 1])); + } +} + +/** + * @template TPost of Post + * @param Builder $query + */ +function templateBuilder(Builder $query): void +{ + assertType('Hypervel\Database\Eloquent\Builder', $query->onlyTrashed()); + assertType('TPost of SoftDeletesStaticBuilder\Post (function SoftDeletesStaticBuilder\templateBuilder(), argument)', $query->restoreOrCreate(['id' => 1])); +} + +/** @param Builder $query */ +function concreteBuilder(Builder $query): void +{ + assertType('Hypervel\Database\Eloquent\Builder', $query->onlyTrashed()); +} From bb6497c79c7170ff8be98fb1d94df12d63bc0f30 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:03:54 +0000 Subject: [PATCH 07/14] Port Larastan's foreignIdFor() schema tests Hypervel's SchemaAggregator already names foreignIdFor(), foreignUuidFor() and foreignUlidFor() columns with the model's getForeignKey(). Upstream's cases now run in SchemaAggregatorTest with its Country fixture. For a model that cannot be loaded, upstream guesses an integer column named after the class. Hypervel adds no column and marks the table incomplete, because the model's key name and type are unknown; the ported test asserts that. Port larastan/larastan #2638 at 3.x 7379a05a. Validation: SchemaAggregatorTest (81 tests) and MigrationHelperTest pass; formatting and full static analysis pass. --- .../Fixtures/SchemaAggregator/Country.php | 16 ++++++++ tests/PHPStan/Unit/SchemaAggregatorTest.php | 38 +++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 tests/PHPStan/Fixtures/SchemaAggregator/Country.php diff --git a/tests/PHPStan/Fixtures/SchemaAggregator/Country.php b/tests/PHPStan/Fixtures/SchemaAggregator/Country.php new file mode 100644 index 0000000000..4946c6e50c --- /dev/null +++ b/tests/PHPStan/Fixtures/SchemaAggregator/Country.php @@ -0,0 +1,16 @@ +columns($aggregator, 'attachments')); } + #[Test] + public function itReadsColumnsFromForeignIdForMethods(): void + { + $aggregator = $this->aggregate(<<<'PHP' + Schema::create('countries', function (Blueprint $table) { + $table->string('code', 2)->primary(); + }); + + Schema::create('cities', function (Blueprint $table) { + $table->foreignIdFor(Country::class); + $table->foreignUuidFor(\App\UuidModel::class); + $table->foreignUlidFor(\App\UlidModel::class, 'custom_foreign_ulid_for_name')->nullable(); + }); + PHP); + + $this->assertSame([ + 'country_code' => ['string', false], + 'uuid_model_id' => ['string', false], + 'custom_foreign_ulid_for_name' => ['string', true], + ], $this->columns($aggregator, 'cities')); + } + + /** + * Unlike upstream, which guessed an integer column named after the class, the model's key name and type are unknown. + */ + #[Test] + public function itReadsForeignIdForColumnsOfUnknownModels(): void + { + $aggregator = $this->aggregate(<<<'PHP' + Schema::create('cities', function (Blueprint $table) { + $table->foreignIdFor(MissingModel::class); + }); + PHP); + + $this->assertSame([], $this->columns($aggregator, 'cities')); + $this->assertFalse($this->table($aggregator, 'cities')->complete); + } + /** * Unlike upstream, which skipped the calls, names that are not strings make what they change unknown. */ From a3fea58cfae47540ccfaa850285a03c0279e20d4 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:00:16 +0000 Subject: [PATCH 08/14] Port Larastan's named-argument rule and collector tests Rules and collectors receive calls as written, so a named argument can appear at any position. Hypervel's rules and collectors already read their arguments by parameter name, so upstream's CallArgumentsHelper needs no equivalent; its new test cases now run against Hypervel's rules. Corrections found while porting: - The worker-lifetime analysis did not treat makeWith() as a container resolution, so makeWith(parameters: [], abstract: 'request') in a #[BindWhen] condition went unreported. It now shares make()'s handling. - The value() fix now also drops literal arguments without interpolation, which cannot have side effects, so value(foo: 1, value: 'bar') is fixed to 'bar' as upstream does. Calls, interpolated strings and unresolved constants still keep the call. - Comments comparing the view collectors and useless-construct rules with upstream's positional reads are removed, as upstream now reads by name too. Adaptations: - Hypervel's overlapping named-argument cases are consolidated under upstream's names and view fixtures. Its distinct cases are kept: mailable text views, mail message view(), chains held in variables and bulk() data. - The named config collection expectation is unconditional; upstream gates it on Laravel 12.20. - contains() with named arguments is not reported, as Hypervel never reports contains(). - The Octane compatibility rule is not ported; upstream's named makeWith() case is covered by the request-dependent binding test. Port larastan/larastan direct commits 392336282c and ffb2968070 at 3.x 7379a05a. Validation: the PHPStan test suite passes (3,468 tests); formatting and full static analysis pass. --- .../src/Collectors/UsedEmailViewCollector.php | 3 +- .../UsedRouteFacadeViewCollector.php | 1 - .../UsedViewFacadeMakeCollector.php | 1 - .../Collectors/UsedViewFunctionCollector.php | 1 - .../src/Collectors/UsedViewMakeCollector.php | 1 - .../src/Rules/Coroutine/WorkerStateHelper.php | 2 +- .../NoUselessValueFunctionCallsRule.php | 17 +++++++---- .../NoUselessWithFunctionCallsRule.php | 9 +++--- ...CompatibleWithClassConstructorRuleTest.php | 14 +++++---- .../Rules/ConfigCollectionRuleTest.php | 4 +++ .../Rules/NoMissingTranslationsRuleTest.php | 28 +++++++++++++++++ .../NoUnnecessaryCollectionCallRuleTest.php | 2 +- ...edInTransactionUsesAfterCommitRuleTest.php | 25 ++++++++-------- .../Queue/NoBatchedUniqueJobRuleTest.php | 22 +++++++------- .../Rules/Queue/data/batched-unique-jobs.php | 8 +++-- .../Rules/Queue/data/transaction-dispatch.php | 4 +++ .../Rules/RequestDependentBindingRuleTest.php | 19 ++++++------ .../NoUselessValueFunctionCallsRuleTest.php | 2 ++ .../NoUselessWithFunctionCallsRuleTest.php | 1 + .../data/CorrectValueFunctionCall.php | 6 ++-- .../data/CorrectWithFunctionCall.php | 4 +-- .../data/UselessValueFunctionCall.php | 10 +++++++ .../data/UselessValueFunctionCallFixed.php | 10 +++++++ .../data/UselessWithFunctionCall.php | 5 ++++ .../data/UselessWithFunctionCallFixed.php | 5 ++++ tests/PHPStan/Rules/data/FooController.php | 30 ++++++++++++++----- tests/PHPStan/Rules/data/Translation.php | 17 +++++++++++ .../UnnecessaryCollectionCallsEloquent.php | 5 ++++ .../Rules/data/config-collection-rule.php | 6 ++++ tests/PHPStan/Rules/data/job-dispatch.php | 2 ++ .../Rules/data/request-dependent-bindings.php | 5 ++++ .../named-arguments/facade-make.blade.php | 0 .../named-arguments/factory-make.blade.php | 0 .../views/named-arguments/helper.blade.php | 0 .../mail-message-markdown.blade.php | 1 + .../named-arguments/mailable-view.blade.php | 1 + .../named-arguments/route-view.blade.php | 1 + .../view-factory-make.blade.php | 1 + .../named-arguments/view-function.blade.php | 1 + .../view-static-make.blade.php | 1 + 40 files changed, 205 insertions(+), 70 deletions(-) delete mode 100644 tests/PHPStan/application/resources/views/named-arguments/facade-make.blade.php delete mode 100644 tests/PHPStan/application/resources/views/named-arguments/factory-make.blade.php delete mode 100644 tests/PHPStan/application/resources/views/named-arguments/helper.blade.php create mode 100644 tests/PHPStan/application/resources/views/named-arguments/mail-message-markdown.blade.php create mode 100644 tests/PHPStan/application/resources/views/named-arguments/mailable-view.blade.php create mode 100644 tests/PHPStan/application/resources/views/named-arguments/view-factory-make.blade.php create mode 100644 tests/PHPStan/application/resources/views/named-arguments/view-function.blade.php create mode 100644 tests/PHPStan/application/resources/views/named-arguments/view-static-make.blade.php diff --git a/src/phpstan/src/Collectors/UsedEmailViewCollector.php b/src/phpstan/src/Collectors/UsedEmailViewCollector.php index 1392918420..c3fba3cc56 100644 --- a/src/phpstan/src/Collectors/UsedEmailViewCollector.php +++ b/src/phpstan/src/Collectors/UsedEmailViewCollector.php @@ -77,8 +77,7 @@ public function processNode(Node $node, Scope $scope): ?array return null; } - // Upstream reads the first argument by position, which misses reordered named arguments. The - // mailable and mail message text() methods name it textView; the others name it view. + // The mailable and mail message text() methods name the view parameter textView; the others name it view. $parameter = $method === 'text' && ! $isContent ? 'textView' : 'view'; return $this->getMailViews($node->getArg($parameter, 0)?->value, $scope); diff --git a/src/phpstan/src/Collectors/UsedRouteFacadeViewCollector.php b/src/phpstan/src/Collectors/UsedRouteFacadeViewCollector.php index ae9ffe9659..2b2b5c80dc 100644 --- a/src/phpstan/src/Collectors/UsedRouteFacadeViewCollector.php +++ b/src/phpstan/src/Collectors/UsedRouteFacadeViewCollector.php @@ -59,7 +59,6 @@ public function processNode(Node $node, Scope $scope): ?array return null; } - // Upstream reads the second argument by position, which misses reordered named arguments. return $this->getViewNames($node->getArg('view', 1)?->value, $scope); } } diff --git a/src/phpstan/src/Collectors/UsedViewFacadeMakeCollector.php b/src/phpstan/src/Collectors/UsedViewFacadeMakeCollector.php index 809b1ea974..95d3bb9a5e 100644 --- a/src/phpstan/src/Collectors/UsedViewFacadeMakeCollector.php +++ b/src/phpstan/src/Collectors/UsedViewFacadeMakeCollector.php @@ -59,7 +59,6 @@ public function processNode(Node $node, Scope $scope): ?array return null; } - // Upstream reads the first argument by position, which misses reordered named arguments. return $this->getViewNames($node->getArg('view', 0)?->value, $scope); } } diff --git a/src/phpstan/src/Collectors/UsedViewFunctionCollector.php b/src/phpstan/src/Collectors/UsedViewFunctionCollector.php index f1802c4c18..6c93f6b5f8 100644 --- a/src/phpstan/src/Collectors/UsedViewFunctionCollector.php +++ b/src/phpstan/src/Collectors/UsedViewFunctionCollector.php @@ -55,7 +55,6 @@ public function processNode(Node $node, Scope $scope): ?array return null; } - // Upstream reads the first argument by position, which misses reordered named arguments. return $this->getViewNames($node->getArg('view', 0)?->value, $scope); } } diff --git a/src/phpstan/src/Collectors/UsedViewMakeCollector.php b/src/phpstan/src/Collectors/UsedViewMakeCollector.php index 9d687aa944..34e3602f59 100644 --- a/src/phpstan/src/Collectors/UsedViewMakeCollector.php +++ b/src/phpstan/src/Collectors/UsedViewMakeCollector.php @@ -52,7 +52,6 @@ public function processNode(Node $node, Scope $scope): ?array return null; } - // Upstream reads the first argument by position, which misses reordered named arguments. return $this->getViewNames($node->getArg('view', 0)?->value, $scope); } } diff --git a/src/phpstan/src/Rules/Coroutine/WorkerStateHelper.php b/src/phpstan/src/Rules/Coroutine/WorkerStateHelper.php index b7a10cfa80..aa8c8d5511 100644 --- a/src/phpstan/src/Rules/Coroutine/WorkerStateHelper.php +++ b/src/phpstan/src/Rules/Coroutine/WorkerStateHelper.php @@ -97,7 +97,7 @@ class WorkerStateHelper /** * The resolving container methods, each with its abstract's parameter name and whether parameters follow. */ - private const array RESOLVING_METHODS = ['make' => ['abstract', true], 'get' => ['id', false], 'factory' => ['abstract', false]]; + private const array RESOLVING_METHODS = ['make' => ['abstract', true], 'makewith' => ['abstract', true], 'get' => ['id', false], 'factory' => ['abstract', false]]; /** * The attributes that restrict a method to boot time or tests. diff --git a/src/phpstan/src/Rules/UselessConstructs/NoUselessValueFunctionCallsRule.php b/src/phpstan/src/Rules/UselessConstructs/NoUselessValueFunctionCallsRule.php index 04723e671f..aec26d5b60 100644 --- a/src/phpstan/src/Rules/UselessConstructs/NoUselessValueFunctionCallsRule.php +++ b/src/phpstan/src/Rules/UselessConstructs/NoUselessValueFunctionCallsRule.php @@ -8,6 +8,8 @@ use PhpParser\Node\Arg; use PhpParser\Node\Expr\ConstFetch; use PhpParser\Node\Expr\FuncCall; +use PhpParser\Node\Scalar; +use PhpParser\Node\Scalar\InterpolatedString; use PHPStan\Analyser\Scope; use PHPStan\DependencyInjection\AutowiredService; use PHPStan\Reflection\ReflectionProvider; @@ -21,10 +23,9 @@ use function strtolower; /** - * Upstream matches the written name and takes the first argument as the value, so an - * unpacked list or a reordered named argument was misread. Its fix dropped the evaluation - * of the other arguments, and took the value from the analyzed tree instead of the fixer's - * copy of the call, which broke the fixed file for values such as `new Foo()`. + * Upstream matches the written name and misreads an unpacked list as the value. Its fix + * dropped the evaluation of the other arguments, and took the value from the analyzed tree + * instead of the fixer's copy of the call, which broke the fixed file for values such as `new Foo()`. * * @implements Rule */ @@ -79,9 +80,13 @@ public function processNode(Node $node, Scope $scope): array ->line($node->getStartLine()) ->identifier('hypervel.uselessConstructs.value'); - // value() still evaluates its other arguments, so the call is replaced only when they are null, true or false. + // value() still evaluates its other arguments, so the call is replaced only when they are + // literals without interpolation, or null, true or false. foreach ($args as $arg) { - if ($arg !== $valueArg && ! ($arg->value instanceof ConstFetch && in_array($arg->value->name->toLowerString(), ['null', 'true', 'false'], true))) { + if ($arg !== $valueArg + && ! ($arg->value instanceof Scalar && ! $arg->value instanceof InterpolatedString) + && ! ($arg->value instanceof ConstFetch && in_array($arg->value->name->toLowerString(), ['null', 'true', 'false'], true)) + ) { return [$error->build()]; } } diff --git a/src/phpstan/src/Rules/UselessConstructs/NoUselessWithFunctionCallsRule.php b/src/phpstan/src/Rules/UselessConstructs/NoUselessWithFunctionCallsRule.php index 3d0b7343d7..feacbc8169 100644 --- a/src/phpstan/src/Rules/UselessConstructs/NoUselessWithFunctionCallsRule.php +++ b/src/phpstan/src/Rules/UselessConstructs/NoUselessWithFunctionCallsRule.php @@ -19,11 +19,10 @@ use function strtolower; /** - * Upstream matches the written name and takes the first two arguments by position, so an - * unpacked list or reordered named arguments were misread. It also reported callbacks that - * are not callable, which throw instead of returning the value. Its fix dropped the - * evaluation of the other arguments, and took the value from the analyzed tree instead of - * the fixer's copy of the call, which broke the fixed file for values such as `new Foo()`. + * Upstream matches the written name and misreads an unpacked list as the arguments. It also + * reported callbacks that are not callable, which throw instead of returning the value. Its + * fix dropped the evaluation of the other arguments, and took the value from the analyzed tree + * instead of the fixer's copy of the call, which broke the fixed file for values such as `new Foo()`. * * @implements Rule */ diff --git a/tests/PHPStan/Rules/CheckDispatchArgumentTypesCompatibleWithClassConstructorRuleTest.php b/tests/PHPStan/Rules/CheckDispatchArgumentTypesCompatibleWithClassConstructorRuleTest.php index 7238cabb57..100cd0a2a4 100644 --- a/tests/PHPStan/Rules/CheckDispatchArgumentTypesCompatibleWithClassConstructorRuleTest.php +++ b/tests/PHPStan/Rules/CheckDispatchArgumentTypesCompatibleWithClassConstructorRuleTest.php @@ -58,12 +58,14 @@ public function testJobDispatch(): void ['Job class Hypervel\Tests\PHPStan\Rules\Data\HypervelJobWithoutConstructor does not have a constructor and must be dispatched without any parameters.', 27], ['Job class Hypervel\Tests\PHPStan\Rules\Data\HypervelJobWithoutConstructor does not have a constructor and must be dispatched without any parameters.', 29], ['Job class Hypervel\Tests\PHPStan\Rules\Data\HypervelJobWithoutConstructor does not have a constructor and must be dispatched without any parameters.', 32], - ['Parameter #1 $foo of job class Hypervel\Tests\PHPStan\Rules\Data\HypervelJob constructor expects string in Hypervel\Tests\PHPStan\Rules\Data\HypervelJob::dispatchIf(), int given.', 36], - ['Parameter #2 $bar of job class Hypervel\Tests\PHPStan\Rules\Data\HypervelJob constructor expects int in Hypervel\Tests\PHPStan\Rules\Data\HypervelJob::dispatchIf(), string given.', 36], - ['Missing parameter $bar (int) in call to Hypervel\Tests\PHPStan\Rules\Data\HypervelJob constructor.', 37], - ['Parameter #1 $foo of job class Hypervel\Tests\PHPStan\Rules\Data\HypervelJob constructor expects string in Hypervel\Tests\PHPStan\Rules\Data\HypervelJob::dispatch(), int given.', 42], - ['Parameter #2 $bar of job class Hypervel\Tests\PHPStan\Rules\Data\HypervelJob constructor expects int in Hypervel\Tests\PHPStan\Rules\Data\HypervelJob::dispatch(), string given.', 42], - ['Parameter #1 $bar of job class Hypervel\Tests\PHPStan\Rules\Data\HypervelChildJob constructor expects int in Hypervel\Tests\PHPStan\Rules\Data\HypervelChildJob::dispatch(), string given.', 70], + ['Parameter $foo of job class Hypervel\Tests\PHPStan\Rules\Data\HypervelJob constructor expects string in Hypervel\Tests\PHPStan\Rules\Data\HypervelJob::dispatchIf(), int given.', 34], + ['Parameter $bar of job class Hypervel\Tests\PHPStan\Rules\Data\HypervelJob constructor expects int in Hypervel\Tests\PHPStan\Rules\Data\HypervelJob::dispatchIf(), string given.', 34], + ['Parameter #1 $foo of job class Hypervel\Tests\PHPStan\Rules\Data\HypervelJob constructor expects string in Hypervel\Tests\PHPStan\Rules\Data\HypervelJob::dispatchIf(), int given.', 38], + ['Parameter #2 $bar of job class Hypervel\Tests\PHPStan\Rules\Data\HypervelJob constructor expects int in Hypervel\Tests\PHPStan\Rules\Data\HypervelJob::dispatchIf(), string given.', 38], + ['Missing parameter $bar (int) in call to Hypervel\Tests\PHPStan\Rules\Data\HypervelJob constructor.', 39], + ['Parameter #1 $foo of job class Hypervel\Tests\PHPStan\Rules\Data\HypervelJob constructor expects string in Hypervel\Tests\PHPStan\Rules\Data\HypervelJob::dispatch(), int given.', 44], + ['Parameter #2 $bar of job class Hypervel\Tests\PHPStan\Rules\Data\HypervelJob constructor expects int in Hypervel\Tests\PHPStan\Rules\Data\HypervelJob::dispatch(), string given.', 44], + ['Parameter #1 $bar of job class Hypervel\Tests\PHPStan\Rules\Data\HypervelChildJob constructor expects int in Hypervel\Tests\PHPStan\Rules\Data\HypervelChildJob::dispatch(), string given.', 72], ]); } diff --git a/tests/PHPStan/Rules/ConfigCollectionRuleTest.php b/tests/PHPStan/Rules/ConfigCollectionRuleTest.php index 96f11322cb..9bd4627253 100644 --- a/tests/PHPStan/Rules/ConfigCollectionRuleTest.php +++ b/tests/PHPStan/Rules/ConfigCollectionRuleTest.php @@ -35,6 +35,10 @@ public function testRule(): void "Config key 'test.missing' is not an array, so collection() throws. Correct the config value or use the getter that matches its type.", 25, ], + [ + "Config key 'test.foo' is not an array, so collection() throws. Correct the config value or use the getter that matches its type.", + 35, + ], ]); } diff --git a/tests/PHPStan/Rules/NoMissingTranslationsRuleTest.php b/tests/PHPStan/Rules/NoMissingTranslationsRuleTest.php index 44c3fbff6f..5d4a4e4451 100644 --- a/tests/PHPStan/Rules/NoMissingTranslationsRuleTest.php +++ b/tests/PHPStan/Rules/NoMissingTranslationsRuleTest.php @@ -163,6 +163,34 @@ public function testRule(): void 'Translation "messages.test" has not been found.', 50, ], + [ + 'Translation "messages.named" has not been found.', + 55, + ], + [ + 'Translation "messages.named" has not been found.', + 56, + ], + [ + 'Translation "messages.named" has not been found.', + 57, + ], + [ + 'Translation "messages.named" has not been found.', + 59, + ], + [ + 'Translation "messages.named" has not been found.', + 60, + ], + [ + 'Translation "messages.named" has not been found.', + 62, + ], + [ + 'Translation "messages.named" has not been found.', + 63, + ], ]); } diff --git a/tests/PHPStan/Rules/NoUnnecessaryCollectionCallRuleTest.php b/tests/PHPStan/Rules/NoUnnecessaryCollectionCallRuleTest.php index 24b12af7e6..d6dce3525e 100644 --- a/tests/PHPStan/Rules/NoUnnecessaryCollectionCallRuleTest.php +++ b/tests/PHPStan/Rules/NoUnnecessaryCollectionCallRuleTest.php @@ -54,7 +54,7 @@ public function testNoFalseNegativesEloquent(): void // Hypervel: App\User uses SoftDeletes, whose global scope the rule cannot show leaves the result unchanged, // so lines 18, 23, 29, 34, 39, 62, 72 and 92 are not reported. Line 45 calls a relation and line 57 a variable, // whose queries are not in view. - // REMOVED: contains() (line 67), where() (78), diff() (84), containsStrict() (97) and sum() (103), whose query + // REMOVED: contains() (lines 67 and 108), where() (78), diff() (84), containsStrict() (97) and sum() (103), whose query // forms compare or aggregate values differently. $this->analyse([__DIR__ . '/data/UnnecessaryCollectionCallsEloquent.php'], [ ['Called \'count\' on Hypervel collection, but could have been retrieved as a query with \'count()\'.', 50], diff --git a/tests/PHPStan/Rules/Queue/JobDispatchedInTransactionUsesAfterCommitRuleTest.php b/tests/PHPStan/Rules/Queue/JobDispatchedInTransactionUsesAfterCommitRuleTest.php index 2ceb1dabbe..449cc02d3e 100644 --- a/tests/PHPStan/Rules/Queue/JobDispatchedInTransactionUsesAfterCommitRuleTest.php +++ b/tests/PHPStan/Rules/Queue/JobDispatchedInTransactionUsesAfterCommitRuleTest.php @@ -43,19 +43,20 @@ public function testRule(): void [$message, 52], [$message, 55], [$message, 78], - [str_replace('NotifyOwner', 'DatabaseQueuedJob', $message), 128], + [$message, 120], [str_replace('NotifyOwner', 'DatabaseQueuedJob', $message), 132], - [str_replace('NotifyOwner', 'QueueableNotifyOwner', $message), 173], - [str_replace('NotifyOwner', 'QueueableNotifyOwner', $message), 179], - [str_replace('Hypervel\Tests\PHPStan\Rules\Queue\Data\NotifyOwner', 'Hypervel\Queue\CallQueuedClosure', $message), 191], - [$message, 199], - [str_replace('NotifyOwner', 'DatabaseQueuedJob', $message), 205], - [str_replace('NotifyOwner', 'SyncAttributeJob', $message), 225], - [str_replace('NotifyOwner', 'RedisPropertyJob', $message), 226], - [str_replace('NotifyOwner', 'ConstructorQueueJob', $message), 314], - [$message, 353], - [$message, 354], - [$message, 355], + [str_replace('NotifyOwner', 'DatabaseQueuedJob', $message), 136], + [str_replace('NotifyOwner', 'QueueableNotifyOwner', $message), 177], + [str_replace('NotifyOwner', 'QueueableNotifyOwner', $message), 183], + [str_replace('Hypervel\Tests\PHPStan\Rules\Queue\Data\NotifyOwner', 'Hypervel\Queue\CallQueuedClosure', $message), 195], + [$message, 203], + [str_replace('NotifyOwner', 'DatabaseQueuedJob', $message), 209], + [str_replace('NotifyOwner', 'SyncAttributeJob', $message), 229], + [str_replace('NotifyOwner', 'RedisPropertyJob', $message), 230], + [str_replace('NotifyOwner', 'ConstructorQueueJob', $message), 318], + [$message, 357], + [$message, 358], + [$message, 359], ]); } diff --git a/tests/PHPStan/Rules/Queue/NoBatchedUniqueJobRuleTest.php b/tests/PHPStan/Rules/Queue/NoBatchedUniqueJobRuleTest.php index 8cd13fc80f..d6c4d88b9c 100644 --- a/tests/PHPStan/Rules/Queue/NoBatchedUniqueJobRuleTest.php +++ b/tests/PHPStan/Rules/Queue/NoBatchedUniqueJobRuleTest.php @@ -39,37 +39,37 @@ public function testRule(): void "Unique job Hypervel\\Tests\\PHPStan\\Rules\\Queue\\Data\\UniqueJobWithUniqueForProperty is dispatched via batch().\n 💡 Dispatch unique jobs individually.", 44, ], + [ + "Unique job Hypervel\\Tests\\PHPStan\\Rules\\Queue\\Data\\UniqueJobWithUniqueForProperty is dispatched via bulk().\n 💡 Dispatch unique jobs individually.", + 48, + ], [ "Unique job Hypervel\\Tests\\PHPStan\\Rules\\Queue\\Data\\UniqueJobWithUniqueForProperty is dispatched via batch().\n 💡 Dispatch unique jobs individually.", - 47, + 52, ], [ "Unique job Hypervel\\Tests\\PHPStan\\Rules\\Queue\\Data\\UniqueJobWithUniqueForMethod is dispatched via add().\n 💡 Dispatch unique jobs individually.", - 51, + 56, ], [ "Unique job Hypervel\\Tests\\PHPStan\\Rules\\Queue\\Data\\UniqueJobWithUniqueForProperty is dispatched via batch().\n 💡 Dispatch unique jobs individually.", - 59, - ], - [ - "Unique job Hypervel\\Tests\\PHPStan\\Rules\\Queue\\Data\\UniqueJobWithUniqueForProperty is dispatched via bulk().\n 💡 Dispatch unique jobs individually.", - 61, + 64, ], [ "Unique job Hypervel\\Tests\\PHPStan\\Rules\\Queue\\Data\\UniqueJobWithUniqueForProperty is dispatched via batch().\n 💡 Dispatch unique jobs individually.", - 68, + 72, ], [ "Unique job Hypervel\\Tests\\PHPStan\\Rules\\Queue\\Data\\UniqueJobWithUniqueForMethod|Hypervel\\Tests\\PHPStan\\Rules\\Queue\\Data\\UniqueJobWithUniqueForProperty is dispatched via batch().\n 💡 Dispatch unique jobs individually.", - 75, + 79, ], [ "Unique job Hypervel\\Tests\\PHPStan\\Rules\\Queue\\Data\\UniqueJobWithUniqueForMethod|Hypervel\\Tests\\PHPStan\\Rules\\Queue\\Data\\UniqueJobWithUniqueForProperty is dispatched via batch().\n 💡 Dispatch unique jobs individually.", - 76, + 80, ], [ "Unique job Hypervel\\Tests\\PHPStan\\Rules\\Queue\\Data\\UniqueJobWithUniqueForMethod|Hypervel\\Tests\\PHPStan\\Rules\\Queue\\Data\\UniqueJobWithUniqueForProperty is dispatched via batch().\n 💡 Dispatch unique jobs individually.", - 77, + 81, ], ]); } diff --git a/tests/PHPStan/Rules/Queue/data/batched-unique-jobs.php b/tests/PHPStan/Rules/Queue/data/batched-unique-jobs.php index 90be1c896d..05640411be 100644 --- a/tests/PHPStan/Rules/Queue/data/batched-unique-jobs.php +++ b/tests/PHPStan/Rules/Queue/data/batched-unique-jobs.php @@ -43,6 +43,11 @@ Bus::batch($jobs); +// Named arguments in a different order than the parameters. +Queue::bulk(queue: 'default', jobs: [ + new UniqueJobWithUniqueForProperty(), +]); + // Hypervel: a single job is wrapped into a batch, and adding to a batch bypasses the lock too. Bus::batch(new UniqueJobWithUniqueForProperty()); @@ -51,14 +56,13 @@ function addUniqueJobToBatch(Batch $batch): void $batch->add([new UniqueJobWithUniqueForMethod()]); } -// Hypervel: a chain held in a variable is inspected too, and the jobs argument binds by name. +// Hypervel: a chain held in a variable is inspected too. A unique job passed as bulk() data is not dispatched. function batchAndBulkUniqueJobs(): void { $chain = [new UniqueJobWithUniqueForProperty()]; Bus::batch([$chain]); Queue::bulk(data: new UniqueJobWithUniqueForProperty(), jobs: [new RegularJob(1)]); - Queue::bulk(data: '', jobs: [new UniqueJobWithUniqueForProperty()]); } // Hypervel: an entry that may be a job or a chain is reported when any job it may hold is unique. diff --git a/tests/PHPStan/Rules/Queue/data/transaction-dispatch.php b/tests/PHPStan/Rules/Queue/data/transaction-dispatch.php index 50e32c04ca..42c21558fd 100644 --- a/tests/PHPStan/Rules/Queue/data/transaction-dispatch.php +++ b/tests/PHPStan/Rules/Queue/data/transaction-dispatch.php @@ -116,6 +116,10 @@ class QueueableNotifyOwnerAfterCommit extends QueueableNotifyOwner QueueableNotifyOwnerAfterCommit::dispatch(); }); +DB::transaction(attempts: 2, callback: static function (): void { + NotifyOwner::dispatch(1); +}); + // Hypervel: the connection and driver decide whether the queue waits for the commit. #[Connection('transaction-database')] class DatabaseQueuedJob implements ShouldQueue diff --git a/tests/PHPStan/Rules/RequestDependentBindingRuleTest.php b/tests/PHPStan/Rules/RequestDependentBindingRuleTest.php index 1fd16be744..c6629810b4 100644 --- a/tests/PHPStan/Rules/RequestDependentBindingRuleTest.php +++ b/tests/PHPStan/Rules/RequestDependentBindingRuleTest.php @@ -32,15 +32,16 @@ public function testRule(): void $error('UsesGuard', 44), $error('ResolvesRequestAlias', 49), $error('ResolvesRequestByName', 54), - $error('UsesConditionMethod', 59), - $error('UsesConditionFunction', 64), - $error('ReadsInCallback', 108), - $error('CapturesContainer', 121), - $error('NamesRequestContextRead', 145), - $error('NamesAuthRead', 150), - $error('UsesConditionConstant', 160), - $error('SelectsWithOwnMethod', 211), - $error('SelectsWithParentMethod', 220), + $error('ResolvesRequestWithMakeWith', 59), + $error('UsesConditionMethod', 64), + $error('UsesConditionFunction', 69), + $error('ReadsInCallback', 113), + $error('CapturesContainer', 126), + $error('NamesRequestContextRead', 150), + $error('NamesAuthRead', 155), + $error('UsesConditionConstant', 165), + $error('SelectsWithOwnMethod', 216), + $error('SelectsWithParentMethod', 225), $error('LocalRequest\UsesHelperFromAnotherNamespace', 12), ]); } diff --git a/tests/PHPStan/Rules/UselessConstructs/NoUselessValueFunctionCallsRuleTest.php b/tests/PHPStan/Rules/UselessConstructs/NoUselessValueFunctionCallsRuleTest.php index 5183ee442c..5520a7abc6 100644 --- a/tests/PHPStan/Rules/UselessConstructs/NoUselessValueFunctionCallsRuleTest.php +++ b/tests/PHPStan/Rules/UselessConstructs/NoUselessValueFunctionCallsRuleTest.php @@ -38,6 +38,8 @@ public function testUselessValueCalls(): void [$message, 33], [$message, 38], [$message, 43], + [$message, 48], + [$message, 53], ], ); } diff --git a/tests/PHPStan/Rules/UselessConstructs/NoUselessWithFunctionCallsRuleTest.php b/tests/PHPStan/Rules/UselessConstructs/NoUselessWithFunctionCallsRuleTest.php index dfadc5debf..8c2c6b95fc 100644 --- a/tests/PHPStan/Rules/UselessConstructs/NoUselessWithFunctionCallsRuleTest.php +++ b/tests/PHPStan/Rules/UselessConstructs/NoUselessWithFunctionCallsRuleTest.php @@ -31,6 +31,7 @@ public function testUselessWithCalls(): void ["Calling the helper function 'with()' with only one argument simply returns the value itself. If you want to chain methods on a construct, use '(new ClassName())->foo()' instead", 11], ["Calling the helper function 'with()' without a callable as the second argument simply returns the value without doing anything", 16], ["Calling the helper function 'with()' with only one argument simply returns the value itself. If you want to chain methods on a construct, use '(new ClassName())->foo()' instead", 26], + ["Calling the helper function 'with()' without a callable as the second argument simply returns the value without doing anything", 31], ], ); } diff --git a/tests/PHPStan/Rules/UselessConstructs/data/CorrectValueFunctionCall.php b/tests/PHPStan/Rules/UselessConstructs/data/CorrectValueFunctionCall.php index d0ed92e33b..e6e3069b7b 100644 --- a/tests/PHPStan/Rules/UselessConstructs/data/CorrectValueFunctionCall.php +++ b/tests/PHPStan/Rules/UselessConstructs/data/CorrectValueFunctionCall.php @@ -19,8 +19,10 @@ public function unpacked(array $arguments): string return value(...$arguments); } - public function reorderedNamed(): string + public function namedArguments(): string { - return value(foo: 1, value: static fn (int $foo) => 'foo'); + return value(foo: 1, value: static function (int $foo) { + return 'foo'; + }); } } diff --git a/tests/PHPStan/Rules/UselessConstructs/data/CorrectWithFunctionCall.php b/tests/PHPStan/Rules/UselessConstructs/data/CorrectWithFunctionCall.php index 8d2a98a14f..37c758f4b8 100644 --- a/tests/PHPStan/Rules/UselessConstructs/data/CorrectWithFunctionCall.php +++ b/tests/PHPStan/Rules/UselessConstructs/data/CorrectWithFunctionCall.php @@ -24,8 +24,8 @@ public function unpacked(array $arguments): string return with(...$arguments); } - public function reorderedNamed(): string + public function namedArguments(): string { - return with(callback: static fn (string $bar) => strtoupper($bar), value: 'foo'); + return with(callback: 'strtoupper', value: 'foo'); } } diff --git a/tests/PHPStan/Rules/UselessConstructs/data/UselessValueFunctionCall.php b/tests/PHPStan/Rules/UselessConstructs/data/UselessValueFunctionCall.php index 75842a0cd7..556980b225 100644 --- a/tests/PHPStan/Rules/UselessConstructs/data/UselessValueFunctionCall.php +++ b/tests/PHPStan/Rules/UselessConstructs/data/UselessValueFunctionCall.php @@ -33,6 +33,11 @@ public function evaluatedArgument(): string return value('foo', $this->count()); } + public function interpolatedArgument(): string + { + return value('foo', "{$this->count()}"); + } + public function undefinedConstantArgument(): string { return value('foo', UNDEFINED_CONSTANT); @@ -43,6 +48,11 @@ public function created(): ArrayObject return value(new ArrayObject()); } + public function namedArguments(): string + { + return value(foo: 1, value: 'bar'); + } + private function count(): int { return 1; diff --git a/tests/PHPStan/Rules/UselessConstructs/data/UselessValueFunctionCallFixed.php b/tests/PHPStan/Rules/UselessConstructs/data/UselessValueFunctionCallFixed.php index caf3661c56..cf58ed6687 100644 --- a/tests/PHPStan/Rules/UselessConstructs/data/UselessValueFunctionCallFixed.php +++ b/tests/PHPStan/Rules/UselessConstructs/data/UselessValueFunctionCallFixed.php @@ -33,6 +33,11 @@ public function evaluatedArgument(): string return value('foo', $this->count()); } + public function interpolatedArgument(): string + { + return value('foo', "{$this->count()}"); + } + public function undefinedConstantArgument(): string { return value('foo', UNDEFINED_CONSTANT); @@ -43,6 +48,11 @@ public function created(): ArrayObject return new ArrayObject(); } + public function namedArguments(): string + { + return 'bar'; + } + private function count(): int { return 1; diff --git a/tests/PHPStan/Rules/UselessConstructs/data/UselessWithFunctionCall.php b/tests/PHPStan/Rules/UselessConstructs/data/UselessWithFunctionCall.php index 995f06ced7..c9eef1968a 100644 --- a/tests/PHPStan/Rules/UselessConstructs/data/UselessWithFunctionCall.php +++ b/tests/PHPStan/Rules/UselessConstructs/data/UselessWithFunctionCall.php @@ -25,4 +25,9 @@ public function created(): UselessWithFunctionCall { return with(new UselessWithFunctionCall()); } + + public function namedArguments(): string + { + return with(callback: null, value: 'baz'); + } } diff --git a/tests/PHPStan/Rules/UselessConstructs/data/UselessWithFunctionCallFixed.php b/tests/PHPStan/Rules/UselessConstructs/data/UselessWithFunctionCallFixed.php index bba0ddd48b..236415629f 100644 --- a/tests/PHPStan/Rules/UselessConstructs/data/UselessWithFunctionCallFixed.php +++ b/tests/PHPStan/Rules/UselessConstructs/data/UselessWithFunctionCallFixed.php @@ -25,4 +25,9 @@ public function created(): UselessWithFunctionCall { return new UselessWithFunctionCall(); } + + public function namedArguments(): string + { + return 'baz'; + } } diff --git a/tests/PHPStan/Rules/data/FooController.php b/tests/PHPStan/Rules/data/FooController.php index 04c27b6024..5f0dbfbbfd 100644 --- a/tests/PHPStan/Rules/data/FooController.php +++ b/tests/PHPStan/Rules/data/FooController.php @@ -120,16 +120,32 @@ function someView(): void } } -// Hypervel: views passed as reordered named arguments. +class NamedArgumentsMailable extends Mailable +{ + public function build(): self + { + return $this->view(data: [], view: 'named-arguments.mailable-view'); + } +} + +class NamedArgumentsMailMessage extends MailMessage +{ + public function build(): self + { + return $this->markdown(data: [], view: 'named-arguments.mail-message-markdown'); + } +} + function namedArguments(Factory $factory): void { - view(data: [], view: 'named-arguments.helper'); - $factory->make(data: [], view: 'named-arguments.factory-make'); - \Hypervel\Support\Facades\View::make(data: [], view: 'named-arguments.facade-make'); - Route::view(view: 'named-arguments.route-view', uri: '/named-arguments'); + view(data: [], view: 'named-arguments.view-function'); + $factory->make(data: [], view: 'named-arguments.view-factory-make'); + \Hypervel\Support\Facades\View::make(data: [], view: 'named-arguments.view-static-make'); + Route::view(view: 'named-arguments.route-view', uri: '/named'); } -class NamedArgumentsMailable extends Mailable +// Hypervel: a mailable's text view and a mail message's HTML view are found by name too. +class NamedArgumentsTextMailable extends Mailable { public function build(): self { @@ -137,7 +153,7 @@ public function build(): self } } -class NamedArgumentsMailMessage extends MailMessage +class NamedArgumentsViewMailMessage extends MailMessage { public function build(): self { diff --git a/tests/PHPStan/Rules/data/Translation.php b/tests/PHPStan/Rules/data/Translation.php index 30cca8976a..8ee8ff9295 100644 --- a/tests/PHPStan/Rules/data/Translation.php +++ b/tests/PHPStan/Rules/data/Translation.php @@ -49,4 +49,21 @@ public function translate(Translator $translator): void $translator->GET('messages.test'); Lang::Choice('messages.test', 1); } + + public function namedArguments(Translator $translator): void + { + __(replace: [], key: 'messages.named'); + trans(replace: [], key: 'messages.named'); + trans_choice(number: 1, key: 'messages.named'); + + $translator->get(replace: [], key: 'messages.named'); + $translator->choice(number: 1, key: 'messages.named'); + + Lang::get(replace: [], key: 'messages.named'); + Lang::choice(number: 1, key: 'messages.named'); + + __(replace: [], key: 'messages.foo'); + $translator->get(replace: [], key: 'messages.bar'); + Lang::get(replace: [], key: 'messages.baz'); + } } diff --git a/tests/PHPStan/Rules/data/UnnecessaryCollectionCallsEloquent.php b/tests/PHPStan/Rules/data/UnnecessaryCollectionCallsEloquent.php index 4c53bb1ce0..3e6c110929 100644 --- a/tests/PHPStan/Rules/data/UnnecessaryCollectionCallsEloquent.php +++ b/tests/PHPStan/Rules/data/UnnecessaryCollectionCallsEloquent.php @@ -102,4 +102,9 @@ public function testSum() { return User::pluck('id')->sum(); } + + public function testContainsNamedArguments(): bool + { + return User::query()->get()->contains(value: 1, operator: '=', key: 'id'); + } } diff --git a/tests/PHPStan/Rules/data/config-collection-rule.php b/tests/PHPStan/Rules/data/config-collection-rule.php index 3dd5a08ea3..9821cd0dd5 100644 --- a/tests/PHPStan/Rules/data/config-collection-rule.php +++ b/tests/PHPStan/Rules/data/config-collection-rule.php @@ -29,3 +29,9 @@ public function presence(): void Config::collection('logging.channels.undeclared'); } } + +function namedArguments(): void +{ + Config::collection(default: null, key: 'test.foo'); + Config::collection(default: null, key: 'test.bar'); +} diff --git a/tests/PHPStan/Rules/data/job-dispatch.php b/tests/PHPStan/Rules/data/job-dispatch.php index 5ba73bd486..75d4f6b248 100644 --- a/tests/PHPStan/Rules/data/job-dispatch.php +++ b/tests/PHPStan/Rules/data/job-dispatch.php @@ -31,6 +31,8 @@ HypervelJobWithoutConstructor::dispatchIf(true); HypervelJobWithoutConstructor::dispatchUnless(true, 'foo'); +HypervelJob::dispatchIf(foo: 1, bar: 'foo', boolean: true); + // Hypervel: the constructor also runs before a closure condition, and a named or unpacked argument // is bound as PHP binds it. A class's own dispatch method keeps its signature. HypervelJob::dispatchIf(static fn (HypervelJob $job): bool => true, 1, 'foo'); diff --git a/tests/PHPStan/Rules/data/request-dependent-bindings.php b/tests/PHPStan/Rules/data/request-dependent-bindings.php index 3d4ca130dd..5c27538b23 100644 --- a/tests/PHPStan/Rules/data/request-dependent-bindings.php +++ b/tests/PHPStan/Rules/data/request-dependent-bindings.php @@ -56,6 +56,11 @@ interface ResolvesRequestByName { } +#[BindWhen(Implementation::class, static function (): bool { return ContainerImplementation::getInstance()->makeWith(parameters: [], abstract: 'request')->is('api/*'); })] +interface ResolvesRequestWithMakeWith +{ +} + #[BindWhen(Implementation::class, Conditions::onApi(...))] interface UsesConditionMethod { diff --git a/tests/PHPStan/application/resources/views/named-arguments/facade-make.blade.php b/tests/PHPStan/application/resources/views/named-arguments/facade-make.blade.php deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/tests/PHPStan/application/resources/views/named-arguments/factory-make.blade.php b/tests/PHPStan/application/resources/views/named-arguments/factory-make.blade.php deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/tests/PHPStan/application/resources/views/named-arguments/helper.blade.php b/tests/PHPStan/application/resources/views/named-arguments/helper.blade.php deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/tests/PHPStan/application/resources/views/named-arguments/mail-message-markdown.blade.php b/tests/PHPStan/application/resources/views/named-arguments/mail-message-markdown.blade.php new file mode 100644 index 0000000000..1bf630caf7 --- /dev/null +++ b/tests/PHPStan/application/resources/views/named-arguments/mail-message-markdown.blade.php @@ -0,0 +1 @@ +{{-- Used with named arguments in a different order than the parameters --}} diff --git a/tests/PHPStan/application/resources/views/named-arguments/mailable-view.blade.php b/tests/PHPStan/application/resources/views/named-arguments/mailable-view.blade.php new file mode 100644 index 0000000000..1bf630caf7 --- /dev/null +++ b/tests/PHPStan/application/resources/views/named-arguments/mailable-view.blade.php @@ -0,0 +1 @@ +{{-- Used with named arguments in a different order than the parameters --}} diff --git a/tests/PHPStan/application/resources/views/named-arguments/route-view.blade.php b/tests/PHPStan/application/resources/views/named-arguments/route-view.blade.php index e69de29bb2..1bf630caf7 100644 --- a/tests/PHPStan/application/resources/views/named-arguments/route-view.blade.php +++ b/tests/PHPStan/application/resources/views/named-arguments/route-view.blade.php @@ -0,0 +1 @@ +{{-- Used with named arguments in a different order than the parameters --}} diff --git a/tests/PHPStan/application/resources/views/named-arguments/view-factory-make.blade.php b/tests/PHPStan/application/resources/views/named-arguments/view-factory-make.blade.php new file mode 100644 index 0000000000..1bf630caf7 --- /dev/null +++ b/tests/PHPStan/application/resources/views/named-arguments/view-factory-make.blade.php @@ -0,0 +1 @@ +{{-- Used with named arguments in a different order than the parameters --}} diff --git a/tests/PHPStan/application/resources/views/named-arguments/view-function.blade.php b/tests/PHPStan/application/resources/views/named-arguments/view-function.blade.php new file mode 100644 index 0000000000..1bf630caf7 --- /dev/null +++ b/tests/PHPStan/application/resources/views/named-arguments/view-function.blade.php @@ -0,0 +1 @@ +{{-- Used with named arguments in a different order than the parameters --}} diff --git a/tests/PHPStan/application/resources/views/named-arguments/view-static-make.blade.php b/tests/PHPStan/application/resources/views/named-arguments/view-static-make.blade.php new file mode 100644 index 0000000000..1bf630caf7 --- /dev/null +++ b/tests/PHPStan/application/resources/views/named-arguments/view-static-make.blade.php @@ -0,0 +1 @@ +{{-- Used with named arguments in a different order than the parameters --}} From 967af851f6b35bf2321c6bb57fc6f63403c50d4a Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:00:23 +0000 Subject: [PATCH 09/14] Port Larastan's Collection offset type tests Hypervel's Collection::offsetGet() already declares TKey and TValue, so destructured partition() results and offset reads keep their non-nullable types. Upstream's assertions now run in collection-generic-static-methods.php. Port larastan/larastan #2648 at 3.x 7379a05a. Validation: CollectionDynamicReturnTypeExtensionsTest passes (307 assertions). --- .../PHPStan/Type/data/collection-generic-static-methods.php | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/tests/PHPStan/Type/data/collection-generic-static-methods.php b/tests/PHPStan/Type/data/collection-generic-static-methods.php index dfab2d465f..b109580c28 100644 --- a/tests/PHPStan/Type/data/collection-generic-static-methods.php +++ b/tests/PHPStan/Type/data/collection-generic-static-methods.php @@ -174,6 +174,12 @@ function test( assertType('Hypervel\Support\Collection>', $items->zip(['foo', 'bar'])); assertType('Hypervel\Support\Collection, Hypervel\Support\Collection>', $items->partition('foo')); + [$passed, $failed] = $items->partition('foo'); + assertType('Hypervel\Support\Collection', $passed); + assertType('Hypervel\Support\Collection', $failed); + + assertType('int', $items['foo']); + assertType('int', $items->offsetGet('foo')); assertType('Hypervel\Support\Collection', $collection->pad(10, 10)); assertType('Hypervel\Support\Collection', $customEloquentCollection->pad(10, 'foo')); From b13b6fdbe600281e0f675606f0abf58b5778072e Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:00:23 +0000 Subject: [PATCH 10/14] Port Larastan's getArrayableAttributes() type test HasAttributes::getArrayableAttributes() already declares array. Upstream's assertion now runs in eloquent-getter-types.php. Port larastan/larastan #2649 at 3.x 7379a05a. Validation: GeneralTypeTest passes. --- tests/PHPStan/Type/data/eloquent-getter-types.php | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/tests/PHPStan/Type/data/eloquent-getter-types.php b/tests/PHPStan/Type/data/eloquent-getter-types.php index b24d79813d..e4e5660bc1 100644 --- a/tests/PHPStan/Type/data/eloquent-getter-types.php +++ b/tests/PHPStan/Type/data/eloquent-getter-types.php @@ -14,3 +14,13 @@ function test(User $user): void assertType('array', $user->getAppends()); assertType('list', $user->getMutatedAttributes()); } + +class UserWithArrayableAttributes extends User +{ + protected function getArrayableAttributes(): array + { + assertType('array', parent::getArrayableAttributes()); + + return parent::getArrayableAttributes(); + } +} From cc092f4c02b26a08d3e7db8e4de70b19a469819f Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:00:23 +0000 Subject: [PATCH 11/14] Type application paths as non-empty for a non-empty path join_paths() prefixes every non-empty segment with a directory separator, so a path helper given a non-empty path never returns an empty string. Declaring that removes false positives such as simplexml_load_file(storage_path('feeds/catalog.xml')). Upstream types base_path() in its stub. Hypervel declares helper types in framework PHPDoc, so base_path() and the seven other path helpers that join the same way declare the conditional return type. The application contract's path methods and joinPaths() declare it too, so injected applications get it; the concrete Application inherits it. The App facade keeps string, as the facade documenter flattens string refinements for every facade. Port larastan/larastan #2647 at 3.x 7379a05a. Validation: GeneralTypeTest passes (2,271 assertions); FacadeDocblocksTest, formatting and full static analysis pass. --- src/contracts/src/Foundation/Application.php | 22 ++++++++++++++++++++ src/foundation/src/helpers.php | 16 ++++++++++++++ tests/PHPStan/Type/data/contracts.php | 7 ++++++- tests/PHPStan/Type/data/helpers.php | 13 ++++++++++++ 4 files changed, 57 insertions(+), 1 deletion(-) diff --git a/src/contracts/src/Foundation/Application.php b/src/contracts/src/Foundation/Application.php index d056ffb79d..70306af57c 100644 --- a/src/contracts/src/Foundation/Application.php +++ b/src/contracts/src/Foundation/Application.php @@ -40,41 +40,57 @@ public function setBasePath(string $basePath): static; /** * Get the base path of the Hypervel installation. + * + * @return ($path is non-empty-string ? non-empty-string : string) */ public function basePath(string $path = ''): string; /** * Get the path to the bootstrap directory. + * + * @return ($path is non-empty-string ? non-empty-string : string) */ public function bootstrapPath(string $path = ''): string; /** * Get the path to the application "app" directory. + * + * @return ($path is non-empty-string ? non-empty-string : string) */ public function path(string $path = ''): string; /** * Get the path to the application configuration files. + * + * @return ($path is non-empty-string ? non-empty-string : string) */ public function configPath(string $path = ''): string; /** * Get the path to the database directory. + * + * @return ($path is non-empty-string ? non-empty-string : string) */ public function databasePath(string $path = ''): string; /** * Get the path to the language files. + * + * @return ($path is non-empty-string ? non-empty-string : string) */ public function langPath(string $path = ''): string; /** * Get the path to the public directory. + * + * @return ($path is non-empty-string ? non-empty-string : string) */ public function publicPath(string $path = ''): string; /** * Get the path to the resources directory. + * + * @return ($path is non-empty-string ? non-empty-string : string) */ public function resourcePath(string $path = ''): string; @@ -82,11 +98,15 @@ public function resourcePath(string $path = ''): string; * Get the path to the views directory. * * This method returns the first configured path in the array of view paths. + * + * @return ($path is non-empty-string ? non-empty-string : string) */ public function viewPath(string $path = ''): string; /** * Get the path to the storage directory. + * + * @return ($path is non-empty-string ? non-empty-string : string) */ public function storagePath(string $path = ''): string; @@ -102,6 +122,8 @@ public function getCachedConfigPath(): string; /** * Join the given paths together. + * + * @return ($path is non-empty-string ? non-empty-string : string) */ public function joinPaths(?string $basePath, string $path = ''): string; diff --git a/src/foundation/src/helpers.php b/src/foundation/src/helpers.php index 9d5ba4ee77..f553d89c27 100644 --- a/src/foundation/src/helpers.php +++ b/src/foundation/src/helpers.php @@ -185,6 +185,8 @@ function app_id(): string if (! function_exists('app_path')) { /** * Get the path to the application folder. + * + * @return ($path is non-empty-string ? non-empty-string : string) */ function app_path(string $path = ''): string { @@ -237,6 +239,8 @@ function back(int $status = 302, array $headers = [], mixed $fallback = false): if (! function_exists('base_path')) { /** * Get the path to the base of the install. + * + * @return ($path is non-empty-string ? non-empty-string : string) */ function base_path(string $path = ''): string { @@ -358,6 +362,8 @@ function config(mixed $key = null, mixed $default = null): mixed if (! function_exists('config_path')) { /** * Get the configuration path. + * + * @return ($path is non-empty-string ? non-empty-string : string) */ function config_path(string $path = ''): string { @@ -441,6 +447,8 @@ function csrf_token(): ?string if (! function_exists('database_path')) { /** * Get the path to the database folder. + * + * @return ($path is non-empty-string ? non-empty-string : string) */ function database_path(string $path = ''): string { @@ -555,6 +563,8 @@ function info(Arrayable|Jsonable|Stringable|array|string $message, array $contex if (! function_exists('lang_path')) { /** * Get the path to the language folder. + * + * @return ($path is non-empty-string ? non-empty-string : string) */ function lang_path(string $path = ''): string { @@ -672,6 +682,8 @@ function precognitive(?callable $callable = null): mixed if (! function_exists('public_path')) { /** * Get the path to the public folder. + * + * @return ($path is non-empty-string ? non-empty-string : string) */ function public_path(string $path = ''): string { @@ -827,6 +839,8 @@ function resolve(string $name, array $parameters = []) if (! function_exists('resource_path')) { /** * Get the path to the resources folder. + * + * @return ($path is non-empty-string ? non-empty-string : string) */ function resource_path(string $path = ''): string { @@ -921,6 +935,8 @@ function session(array|UnitEnum|string|null $key = null, mixed $default = null): if (! function_exists('storage_path')) { /** * Get the path to the storage folder. + * + * @return ($path is non-empty-string ? non-empty-string : string) */ function storage_path(string $path = ''): string { diff --git a/tests/PHPStan/Type/data/contracts.php b/tests/PHPStan/Type/data/contracts.php index a46445323a..825b67c069 100644 --- a/tests/PHPStan/Type/data/contracts.php +++ b/tests/PHPStan/Type/data/contracts.php @@ -3,11 +3,16 @@ namespace Contracts; use Hypervel\Contracts\Foundation\Application; +use Hypervel\Foundation\Application as FoundationApplication; use function PHPStan\Testing\assertType; -function test(Application $app): void +function test(Application $app, FoundationApplication $concrete): void { assertType('bool', $app->isLocal()); // REMOVED: $session->ageFlashData(); contracts do not gain methods from their implementations. + + // Hypervel: the application's path methods join a non-empty path, as the path helpers do. + assertType('non-empty-string', $app->storagePath('logs')); + assertType('non-empty-string', $concrete->storagePath('logs')); } diff --git a/tests/PHPStan/Type/data/helpers.php b/tests/PHPStan/Type/data/helpers.php index 990017ad89..feed1b3616 100644 --- a/tests/PHPStan/Type/data/helpers.php +++ b/tests/PHPStan/Type/data/helpers.php @@ -141,6 +141,19 @@ function test(?int $value = 0, int|\Closure $intOrClosure = 0, int|\Closure $int // Hypervel: the booted binding, as for response(). assertType('Hypervel\Routing\UrlGenerator', url()); + assertType('non-empty-string', base_path('composer.json')); + assertType('string', base_path()); + assertType('string', base_path('')); + + // Hypervel: the other path helpers join a non-empty path the same way. + assertType('non-empty-string', app_path('Models')); + assertType('non-empty-string', config_path('app.php')); + assertType('non-empty-string', database_path('migrations')); + assertType('non-empty-string', lang_path('en')); + assertType('non-empty-string', public_path('index.php')); + assertType('non-empty-string', resource_path('views')); + assertType('non-empty-string', storage_path('logs')); + // Hypervel: the booted binding, as for response(). assertType('Hypervel\Validation\Factory', validator()); assertType('Hypervel\Contracts\Validation\Validator', validator(['foo' => 'bar'], ['foo' => 'required'])); From c7a80fb36c64e2b31359560eee63bf62076714f9 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:49:46 +0000 Subject: [PATCH 12/14] Expect upstream's type for a pivot accessor chosen at runtime as($condition ? 'a' : 'b') gives the shape object{a?: Pivot, b?: Pivot}. The fixture's Podcast model has no such columns on its complete schema, so the shape is a supertype of the model and the result is Podcast|null, as upstream asserts. The earlier expectation of optional properties came from an outdated local autoloader that could not load the fixture's models, which left their columns unknown. Models without schema facts still keep the optional properties, as the Laravel types fixture for Relations asserts. Port larastan/larastan #2634 at 3.x 7379a05a. Validation: GeneralTypeTest passes. --- tests/PHPStan/Type/data/belongs-to-many-pivot-accessor.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/tests/PHPStan/Type/data/belongs-to-many-pivot-accessor.php b/tests/PHPStan/Type/data/belongs-to-many-pivot-accessor.php index 683f8f2929..46a3afdfd8 100644 --- a/tests/PHPStan/Type/data/belongs-to-many-pivot-accessor.php +++ b/tests/PHPStan/Type/data/belongs-to-many-pivot-accessor.php @@ -66,8 +66,7 @@ function test(Member $member, string $name, bool $condition): void // Without a single known accessor, no pivot property can be promised. assertType('BelongsToManyPivotAccessor\Podcast|null', $member->belongsToMany(Podcast::class, 'c')->as($name)->first()); - // Unlike upstream, and as Laravel's own types do, each possible accessor is an optional property. - assertType('(BelongsToManyPivotAccessor\Podcast&object{a?: Hypervel\Database\Eloquent\Relations\Pivot, b?: Hypervel\Database\Eloquent\Relations\Pivot})|null', $member->belongsToMany(Podcast::class, 'd')->as($condition ? 'a' : 'b')->first()); + assertType('BelongsToManyPivotAccessor\Podcast|null', $member->belongsToMany(Podcast::class, 'd')->as($condition ? 'a' : 'b')->first()); } /** From 19819beb3bab027e90c63bef4843930067c85536 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:49:46 +0000 Subject: [PATCH 13/14] Fall back to the default terminal size when proc_open is disabled Sizing prompts from the terminal showing their output ran stty through proc_open directly. With proc_open in disable_functions, the call threw an Error that the size query's fallback did not catch, so every spinner, progress bar and prompt failed on its first render. Symfony's query, used before, skipped the query when proc_open was missing. Terminal commands now throw a RuntimeException when proc_open is disabled. The size query falls back to 80x50, and interactive prompts fall back with a clear message. Validation: a PTY test with proc_open disabled fails before and passes after; the Prompts suite, formatting and full static analysis pass. --- src/prompts/src/Terminal.php | 5 +++++ tests/Prompts/TerminalTest.php | 14 ++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/src/prompts/src/Terminal.php b/src/prompts/src/Terminal.php index 8db31b3bac..9a956eab12 100644 --- a/src/prompts/src/Terminal.php +++ b/src/prompts/src/Terminal.php @@ -185,6 +185,11 @@ protected function exec(string $command): string */ protected function execWithInput(string $command, $input = null): string { + // Calling a disabled proc_open throws an Error, which the size query's fallback would not catch. + if (! function_exists('proc_open')) { + throw new RuntimeException('Terminal commands require proc_open, which is disabled.'); + } + $descriptors = [ 1 => ['pipe', 'w'], 2 => ['pipe', 'w'], diff --git a/tests/Prompts/TerminalTest.php b/tests/Prompts/TerminalTest.php index d063cc4268..cb59222cee 100644 --- a/tests/Prompts/TerminalTest.php +++ b/tests/Prompts/TerminalTest.php @@ -94,6 +94,20 @@ public static function redirectedStreams(): array ]; } + public function testUsesTheFallbackSizeWhenProcOpenIsDisabled(): void + { + $process = Process::fromShellCommandline('stty rows 30 cols 70 && "${:PHP}" -d disable_functions=proc_open "${:FIXTURE}"', timeout: 10); + $process->setPty(true); + $process->mustRun(env: [ + 'PHP' => PHP_BINARY, + 'FIXTURE' => __DIR__ . '/Fixtures/terminal-size.php', + 'COLUMNS' => false, + 'LINES' => false, + ]); + + $this->assertSame([80, 50], json_decode($process->getOutput(), true, flags: JSON_THROW_ON_ERROR)); + } + public function testStreamOutputThatIsNotATerminalIsNotATty(): void { $output = new StreamOutput(fopen('php://memory', 'w')); From 5b9d253a9208bc5fe748d7f197077dc7a0d082dc Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:49:46 +0000 Subject: [PATCH 14/14] Add method titles to the queue inspection methods in test fakes The queue fakes in QueueWorkerTest and FailoverQueueTest implement the inspection methods added to the Queue contract. They now use the contract's titles. Validation: QueueWorkerTest and FailoverQueueTest pass. --- tests/Queue/FailoverQueueTest.php | 30 ++++++++++++++++++++++++++++++ tests/Queue/QueueWorkerTest.php | 30 ++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+) diff --git a/tests/Queue/FailoverQueueTest.php b/tests/Queue/FailoverQueueTest.php index 2f09ac5b76..f51d8591bd 100644 --- a/tests/Queue/FailoverQueueTest.php +++ b/tests/Queue/FailoverQueueTest.php @@ -838,21 +838,33 @@ public function reservedSize(UnitEnum|string|null $queue = null): int return 0; } + /** + * Get the number of jobs across every queue. + */ public function totalSize(): int { return 0; } + /** + * Get the number of pending jobs across every queue. + */ public function totalPendingSize(): int { return 0; } + /** + * Get the number of delayed jobs across every queue. + */ public function totalDelayedSize(): int { return 0; } + /** + * Get the number of reserved jobs across every queue. + */ public function totalReservedSize(): int { return 0; @@ -863,31 +875,49 @@ public function creationTimeOfOldestPendingJob(UnitEnum|string|null $queue = nul return null; } + /** + * Get the pending jobs for the given queue. + */ public function pendingJobs(UnitEnum|string|null $queue = null): Collection { return new Collection; } + /** + * Get the delayed jobs for the given queue. + */ public function delayedJobs(UnitEnum|string|null $queue = null): Collection { return new Collection; } + /** + * Get the reserved jobs for the given queue. + */ public function reservedJobs(UnitEnum|string|null $queue = null): Collection { return new Collection; } + /** + * Get all pending jobs across every queue. + */ public function allPendingJobs(): Collection { return new Collection; } + /** + * Get all delayed jobs across every queue. + */ public function allDelayedJobs(): Collection { return new Collection; } + /** + * Get all reserved jobs across every queue. + */ public function allReservedJobs(): Collection { return new Collection; diff --git a/tests/Queue/QueueWorkerTest.php b/tests/Queue/QueueWorkerTest.php index ebc8feb1f6..b29bbb8101 100644 --- a/tests/Queue/QueueWorkerTest.php +++ b/tests/Queue/QueueWorkerTest.php @@ -3976,21 +3976,33 @@ public function reservedSize(UnitEnum|string|null $queue = null): int return 0; } + /** + * Get the number of jobs across every queue. + */ public function totalSize(): int { return 0; } + /** + * Get the number of pending jobs across every queue. + */ public function totalPendingSize(): int { return 0; } + /** + * Get the number of delayed jobs across every queue. + */ public function totalDelayedSize(): int { return 0; } + /** + * Get the number of reserved jobs across every queue. + */ public function totalReservedSize(): int { return 0; @@ -4001,31 +4013,49 @@ public function creationTimeOfOldestPendingJob(UnitEnum|string|null $queue = nul return null; } + /** + * Get the pending jobs for the given queue. + */ public function pendingJobs(UnitEnum|string|null $queue = null): Collection { return new Collection; } + /** + * Get the delayed jobs for the given queue. + */ public function delayedJobs(UnitEnum|string|null $queue = null): Collection { return new Collection; } + /** + * Get the reserved jobs for the given queue. + */ public function reservedJobs(UnitEnum|string|null $queue = null): Collection { return new Collection; } + /** + * Get all pending jobs across every queue. + */ public function allPendingJobs(): Collection { return new Collection; } + /** + * Get all delayed jobs across every queue. + */ public function allDelayedJobs(): Collection { return new Collection; } + /** + * Get all reserved jobs across every queue. + */ public function allReservedJobs(): Collection { return new Collection;