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/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/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..6c7562194e 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. @@ -522,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`. - -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. +Use `hypervel/phpstan` and start with the configuration in the [Static Analysis guide](/docs/{{version}}/static-analysis). -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/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/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/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/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/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/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/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 +169,7 @@ public function start(): void try { $this->hideCursor(); - if (static::output()->isDecorated()) { + if (! $this->static) { $this->render(); } @@ -172,7 +190,8 @@ public function advance(int $step = 1): void $this->progress = $this->total; } - if (static::output()->isDecorated()) { + // 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(); } } @@ -222,6 +241,8 @@ private function settleOperation(?Throwable $failure = null): ?Throwable public function render(): void { parent::render(); + + $this->renderedAt = hrtime(true); } /** @@ -229,7 +250,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..9a956eab12 100644 --- a/src/prompts/src/Terminal.php +++ b/src/prompts/src/Terminal.php @@ -4,8 +4,12 @@ namespace Hypervel\Prompts; -use ReflectionClass; +use Hypervel\Prompts\Output\BufferedConsoleOutput; +use ReflectionProperty; 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 @@ -39,6 +43,11 @@ class Terminal */ protected SymfonyTerminal $terminal; + /** + * Whether the terminal dimensions have been read. + */ + protected bool $dimensionsRead = false; + /** * Create a new Terminal instance. */ @@ -92,6 +101,10 @@ public function restoreTty(): void */ public function cols(): int { + if (! $this->dimensionsRead) { + $this->initDimensions(); + } + return $this->terminal->getWidth(); } @@ -100,6 +113,10 @@ public function cols(): int */ public function lines(): int { + if (! $this->dimensionsRead) { + $this->initDimensions(); + } + return $this->terminal->getHeight(); } @@ -108,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); + } + } } /** @@ -136,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'], @@ -164,6 +218,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/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/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 @@ +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/Type/GeneralTypeTest.php b/tests/PHPStan/Type/GeneralTypeTest.php index 0470be1be7..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,10 +111,13 @@ 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. 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'); @@ -121,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..46a3afdfd8 --- /dev/null +++ b/tests/PHPStan/Type/data/belongs-to-many-pivot-accessor.php @@ -0,0 +1,82 @@ + */ + 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()); + assertType('BelongsToManyPivotAccessor\Podcast|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/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')); 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/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(); + } +} 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'])); 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()); +} diff --git a/tests/PHPStan/Unit/SchemaAggregatorTest.php b/tests/PHPStan/Unit/SchemaAggregatorTest.php index e5f4c34b82..fb723c43f1 100644 --- a/tests/PHPStan/Unit/SchemaAggregatorTest.php +++ b/tests/PHPStan/Unit/SchemaAggregatorTest.php @@ -321,6 +321,44 @@ public function itReadsColumnsFromMorphMethods(): void ], $this->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. */ 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 --}} 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/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/ProgressTest.php b/tests/Prompts/ProgressTest.php index 50a8c93c7e..848370bf12 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; @@ -22,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(); @@ -88,6 +94,40 @@ 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 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(); @@ -336,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' @@ -427,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)); } @@ -491,6 +532,7 @@ public function testCanUpdateLabelAndHintInManualMode(): void $progress->start(); foreach ($states as $state) { + usleep(self::STEP_MICROSECONDS); $progress ->label(strtoupper($state)) ->hint(strtolower($state)) 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..cb59222cee 100644 --- a/tests/Prompts/TerminalTest.php +++ b/tests/Prompts/TerminalTest.php @@ -6,6 +6,9 @@ use Hypervel\Prompts\Terminal; use Hypervel\Tests\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use Symfony\Component\Console\Output\StreamOutput; +use Symfony\Component\Process\Process; class TerminalTest extends TestCase { @@ -66,6 +69,68 @@ public function testUnavailableTtyUsesFallbackColorsWithoutQueryingTerminal(): v $this->assertSame([0, 0, 0], $terminal->backgroundColor()); $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 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')); + + $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()); + } } diff --git a/tests/Queue/FailoverQueueTest.php b/tests/Queue/FailoverQueueTest.php index 5bc689a211..f51d8591bd 100644 --- a/tests/Queue/FailoverQueueTest.php +++ b/tests/Queue/FailoverQueueTest.php @@ -838,11 +838,91 @@ 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; + } + public function creationTimeOfOldestPendingJob(UnitEnum|string|null $queue = null): ?int { 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; + } + 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..b29bbb8101 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,91 @@ 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; + } + public function creationTimeOfOldestPendingJob(UnitEnum|string|null $queue = null): ?int { 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; + } + 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. */