diff --git a/.github/workflows/coding-standards.yml b/.github/workflows/coding-standards.yml new file mode 100644 index 00000000..46d8e832 --- /dev/null +++ b/.github/workflows/coding-standards.yml @@ -0,0 +1,10 @@ +name: fix code styling + +on: [push] + +permissions: + contents: write + +jobs: + lint: + uses: laravel/.github/.github/workflows/coding-standards.yml@main diff --git a/.github/workflows/issues.yml b/.github/workflows/issues.yml new file mode 100644 index 00000000..9634a0ed --- /dev/null +++ b/.github/workflows/issues.yml @@ -0,0 +1,12 @@ +name: issues + +on: + issues: + types: [labeled] + +permissions: + issues: write + +jobs: + help-wanted: + uses: laravel/.github/.github/workflows/issues.yml@main diff --git a/.github/workflows/pull-requests.yml b/.github/workflows/pull-requests.yml new file mode 100644 index 00000000..18b32b32 --- /dev/null +++ b/.github/workflows/pull-requests.yml @@ -0,0 +1,12 @@ +name: pull requests + +on: + pull_request_target: + types: [opened] + +permissions: + pull-requests: write + +jobs: + uneditable: + uses: laravel/.github/.github/workflows/pull-requests.yml@main diff --git a/.github/workflows/static-analysis.yml b/.github/workflows/static-analysis.yml new file mode 100644 index 00000000..f7630779 --- /dev/null +++ b/.github/workflows/static-analysis.yml @@ -0,0 +1,14 @@ +name: static analysis + +on: + push: + branches: + - main + pull_request: + +permissions: + contents: read + +jobs: + tests: + uses: laravel/.github/.github/workflows/static-analysis.yml@main diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 00000000..85a31a21 --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,37 @@ +name: tests + +on: + push: + branches: + - main + pull_request: + +permissions: + contents: read + +jobs: + tests: + runs-on: ubuntu-latest + + name: Tests + + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: 8.4 + tools: composer:v2 + coverage: none + + - name: Install dependencies + uses: nick-fields/retry@v3 + with: + timeout_minutes: 5 + max_attempts: 5 + command: composer install --prefer-dist --no-interaction --no-progress + + - name: Run tests + run: vendor/bin/pest diff --git a/.github/workflows/update-changelog.yml b/.github/workflows/update-changelog.yml new file mode 100644 index 00000000..ebda6206 --- /dev/null +++ b/.github/workflows/update-changelog.yml @@ -0,0 +1,13 @@ +name: update changelog + +on: + release: + types: [released] + +permissions: {} + +jobs: + update: + permissions: + contents: write + uses: laravel/.github/.github/workflows/update-changelog.yml@main diff --git a/app/Client/JsonApiPaginator.php b/app/Client/JsonApiPaginator.php index 71017da3..fe210eb3 100644 --- a/app/Client/JsonApiPaginator.php +++ b/app/Client/JsonApiPaginator.php @@ -22,7 +22,7 @@ protected function isLastPage(Response $response): bool { $links = $response->json('links', []); - return ! isset($links['next']) || is_null($links['next']); + return ! isset($links['next']); } protected function getPageItems(Response $response, Request $request): array @@ -49,7 +49,7 @@ protected function applyPagination(Request $request): Request if ($this->currentResponse instanceof Response) { $links = $this->currentResponse->json('links', []); - if (isset($links['next']) && ! is_null($links['next'])) { + if (isset($links['next'])) { $nextUrl = parse_url($links['next']); parse_str($nextUrl['query'] ?? '', $queryParams); diff --git a/app/Client/Requests/UpdateDatabaseClusterRequestData.php b/app/Client/Requests/UpdateDatabaseClusterRequestData.php index aee3c1f1..a4fcc134 100644 --- a/app/Client/Requests/UpdateDatabaseClusterRequestData.php +++ b/app/Client/Requests/UpdateDatabaseClusterRequestData.php @@ -5,7 +5,7 @@ class UpdateDatabaseClusterRequestData extends RequestData { /** - * @param array|null $config + * @param array $config */ public function __construct( public readonly string $clusterId, diff --git a/app/Client/Resources/MetaResource.php b/app/Client/Resources/MetaResource.php index e138a000..9f91f0b9 100644 --- a/app/Client/Resources/MetaResource.php +++ b/app/Client/Resources/MetaResource.php @@ -29,6 +29,6 @@ public function ipAddresses(): array { $response = $this->send(new ListIpAddressesRequest); - return $response->json() ?? []; + return $response->json(); } } diff --git a/app/Commands/ApplicationCreate.php b/app/Commands/ApplicationCreate.php index f229f2df..e72f5d84 100644 --- a/app/Commands/ApplicationCreate.php +++ b/app/Commands/ApplicationCreate.php @@ -82,7 +82,7 @@ protected function createApplication() label: 'Region', options: collect($regions)->mapWithKeys(fn (Region $region) => [ $region->value => $region->label, - ]), + ])->toArray(), default: $value ?? $this->getDefaultRegion(), required: true, ), diff --git a/app/Commands/ApplicationUpdate.php b/app/Commands/ApplicationUpdate.php index 9ebbb03d..b97684c8 100644 --- a/app/Commands/ApplicationUpdate.php +++ b/app/Commands/ApplicationUpdate.php @@ -150,7 +150,7 @@ protected function defineFields(Application $application): void $this->form()->define( 'slack_channel', fn ($resolver) => $resolver->fromInput( - fn ($value) => $this->getNewSlackChannel($value ?? $application->slackChannel), + fn ($value) => $value ?? $application->slackChannel, ), )->setPreviousValue($application->slackChannel); } diff --git a/app/Commands/Auth.php b/app/Commands/Auth.php index 9ba72efe..250ac934 100644 --- a/app/Commands/Auth.php +++ b/app/Commands/Auth.php @@ -57,7 +57,7 @@ public function handle() 'Creating auth session...', ); } catch (SaloonRequestException $e) { - if ($e->getResponse()?->status() === 422) { + if ($e->getResponse()->status() === 422) { $errors = $e->getResponse()->json('errors', []); foreach ($errors as $field => $messages) { @@ -90,7 +90,7 @@ public function handle() 'Exchanging code for tokens...', ); } catch (SaloonRequestException $e) { - if ($e->getResponse()?->status() === 422) { + if ($e->getResponse()->status() === 422) { $message = $e->getResponse()->json('message', 'Invalid exchange code.'); error($message); @@ -141,14 +141,16 @@ protected function findAvailablePort(int $startPort = 49513, int $maxAttempts = protected function startServer(): void { - $this->serverSocket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); + $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); - if ($this->serverSocket === false) { + if ($socket === false) { error('Failed to create server socket.'); return; } + $this->serverSocket = $socket; + socket_set_option($this->serverSocket, SOL_SOCKET, SO_REUSEADDR, 1); if (! socket_bind($this->serverSocket, '127.0.0.1', $this->port)) { diff --git a/app/Commands/AuthToken.php b/app/Commands/AuthToken.php index b552cae0..c71b6187 100644 --- a/app/Commands/AuthToken.php +++ b/app/Commands/AuthToken.php @@ -76,6 +76,7 @@ public function handle() 'add' => $this->addToken($tokens), 'remove' => $this->removeToken($tokens), 'list' => $this->listTokens($tokens), + default => null, }; } diff --git a/app/Commands/BackgroundProcessCreate.php b/app/Commands/BackgroundProcessCreate.php index acfe9aa5..bca593d1 100644 --- a/app/Commands/BackgroundProcessCreate.php +++ b/app/Commands/BackgroundProcessCreate.php @@ -228,7 +228,7 @@ protected function addWorkerParams(): void fn ($resolver) => $resolver ->fromInput(fn (?string $value) => confirm( label: 'Run in maintenance mode?', - default: $value ?? $this->getWorkerDefult('force'), + default: (bool) ($value ?? $this->getWorkerDefult('force')), hint: 'Force the worker to run even in maintenance mode', )) ->nonInteractively(fn () => $this->getWorkerDefult('force')) diff --git a/app/Commands/BaseCommand.php b/app/Commands/BaseCommand.php index 21285562..a0ae20ee 100644 --- a/app/Commands/BaseCommand.php +++ b/app/Commands/BaseCommand.php @@ -175,6 +175,7 @@ protected function outputJsonIfWanted(mixed $data): void protected function resolve(string $argument): ValueResolver { return new ValueResolver( + $argument, $argument, $this->isInteractive(), match (true) { diff --git a/app/Commands/CacheCreate.php b/app/Commands/CacheCreate.php index 46d89529..af9f5d5d 100644 --- a/app/Commands/CacheCreate.php +++ b/app/Commands/CacheCreate.php @@ -97,7 +97,7 @@ protected function createCache() ->filter(fn (Region $region) => in_array($region->value, $type->regions)) ->mapWithKeys(fn (Region $region) => [ $region->value => $region->label, - ]), + ])->toArray(), default: $value ?? $this->getDefaultRegion(), required: true, )) diff --git a/app/Commands/DatabaseRestoreCreate.php b/app/Commands/DatabaseRestoreCreate.php index e3ba3e5f..f24ce556 100644 --- a/app/Commands/DatabaseRestoreCreate.php +++ b/app/Commands/DatabaseRestoreCreate.php @@ -14,6 +14,7 @@ class DatabaseRestoreCreate extends BaseCommand { protected $signature = 'database-restore:create {cluster? : The database cluster ID or name} + {name? : The name of the restore} {--snapshot= : Snapshot ID to restore from} {--point-in-time= : Point-in-time (ISO 8601) to restore to} {--json : Output as JSON}'; @@ -31,6 +32,16 @@ public function handle() $snapshotId = $this->option('snapshot'); $pointInTime = $this->option('point-in-time'); + $this->form()->prompt( + 'name', + fn ($resolver) => $resolver->fromInput( + fn (?string $value) => text( + label: 'Name', + default: $value ?? '', + ), + ), + ); + if (! $snapshotId && ! $pointInTime && $this->isInteractive()) { $snapshots = spin( fn () => $this->client->databaseSnapshots()->list($cluster->id)->collect(), @@ -77,9 +88,10 @@ public function handle() $restored = spin( fn () => $this->client->databaseRestores()->create( new CreateDatabaseRestoreRequestData( + name: $this->form()->get('name'), clusterId: $cluster->id, - snapshotId: $snapshotId, - pointInTime: $pointInTime, + databaseSnapshotId: $snapshotId, + restoreTime: $pointInTime, ), ), 'Creating restore...', diff --git a/app/Commands/InstanceDelete.php b/app/Commands/InstanceDelete.php index 816ccc7d..d7f44ef5 100644 --- a/app/Commands/InstanceDelete.php +++ b/app/Commands/InstanceDelete.php @@ -21,7 +21,7 @@ public function handle() intro('Deleting Instance'); - $instance = $this->resolvers()->instance()->resolve($this->argument('instance')); + $instance = $this->resolvers()->instance()->from($this->argument('instance')); if (! $this->option('force')) { if (! confirm("Delete instance '{$instance->name}'?")) { diff --git a/app/Commands/InstanceUpdate.php b/app/Commands/InstanceUpdate.php index 2b33caea..9ac81e90 100644 --- a/app/Commands/InstanceUpdate.php +++ b/app/Commands/InstanceUpdate.php @@ -209,11 +209,11 @@ protected function defineFields(EnvironmentInstance $instance): void fn ($resolver) => $resolver->fromInput( fn ($value) => confirm( label: 'Use sleep mode?', - default: $value ?? $instance->environment?->usesHibernation ?? true, + default: $value ?? $instance->environment->usesHibernation ?? true, ), ), 'hibernation', - )->setPreviousValue($instance->environment?->usesHibernation)->setLabel('Hibernation'); + )->setPreviousValue($instance->environment->usesHibernation)->setLabel('Hibernation'); $this->form()->define( 'sleep_timeout', diff --git a/app/Commands/RepoConfig.php b/app/Commands/RepoConfig.php index 1c2bcc4c..99add169 100644 --- a/app/Commands/RepoConfig.php +++ b/app/Commands/RepoConfig.php @@ -42,12 +42,6 @@ public function handle(Git $git, LocalConfig $localConfig) $organization = $this->resolveOrganization(); - if (! $organization) { - error('No organization selected'); - - return self::FAILURE; - } - $application = $this->selectApplication($localConfig->get('application_id')); if ($application === null) { diff --git a/app/Commands/Ship.php b/app/Commands/Ship.php index 983e8290..b1c2d296 100644 --- a/app/Commands/Ship.php +++ b/app/Commands/Ship.php @@ -264,7 +264,7 @@ protected function createApplication(string $defaultRegion, string $repository): fn (Region $region) => [ $region->value => $region->label, ], - ), + )->toArray(), default: $value ?? $defaultRegion, ); }), @@ -645,7 +645,7 @@ protected function getWebsocketCluster(): ?WebsocketCluster $cluster = select( label: 'Websocket cluster', options: $options->toArray(), - default: $clusters->first()?->id ?? null, + default: $clusters->first()->id ?? null, required: true, ); @@ -673,8 +673,8 @@ protected function getDatabase(DatabaseCluster $database): ?Database $schema = select( label: 'Database', - options: $options, - default: $database->schemas[0]?->id ?? null, + options: $options->toArray(), + default: $database->schemas[0]->id ?? null, required: true, ); @@ -712,7 +712,7 @@ protected function getDatabaseCluster(): ?DatabaseCluster $database = select( label: 'Database cluster', options: $options->toArray(), - default: $databases->first()?->id ?? null, + default: $databases->first()->id ?? null, required: true, ); @@ -759,7 +759,7 @@ protected function pushCustomEnvironmentVariables(Application $application): voi $varsToAdd = multiselect( label: 'Add local environment variables to Cloud environment?', - options: $varOptions, + options: $varOptions->toArray(), ); if (count($varsToAdd) === 0) { diff --git a/app/Concerns/HandlesAvatars.php b/app/Concerns/HandlesAvatars.php index f6fcab33..7168a280 100644 --- a/app/Concerns/HandlesAvatars.php +++ b/app/Concerns/HandlesAvatars.php @@ -67,7 +67,7 @@ protected function normalizeSvg(string $content): string } /** - * @return list + * @return list */ protected function getAvatarFromPath(string $path): array { diff --git a/app/Concerns/RequiresDatabaseCluster.php b/app/Concerns/RequiresDatabaseCluster.php deleted file mode 100644 index 61be467f..00000000 --- a/app/Concerns/RequiresDatabaseCluster.php +++ /dev/null @@ -1,89 +0,0 @@ - $databases - */ - protected function getDatabaseCluster(?Collection $databases = null, $showPrompt = true): DatabaseCluster - { - if ($this->argument('database')) { - $identifier = $this->argument('database'); - - if ($databases) { - $database = $this->getByNameOrId($identifier, $databases); - } else { - if (str_starts_with($identifier, 'db-')) { - try { - $database = spin( - fn () => $this->client->databaseClusters()->include('schemas')->get($identifier), - 'Fetching database...', - ); - } catch (Exception $e) { - $database = $this->getByNameOrId($identifier); - } - } else { - $database = $this->getByNameOrId($identifier); - } - } - - if (! $database) { - throw new RuntimeException("Database '{$identifier}' not found."); - } - - $this->displayDatabase($database, $showPrompt); - - return $database; - } - - $databases ??= $this->fetchDatabases(); - - if ($databases->hasSole()) { - $database = $databases->first(); - - $this->displayDatabase($database, $showPrompt); - - return $database; - } - - $selectedDatabase = select( - label: 'Database', - options: $databases->mapWithKeys(fn ($database) => [$database->id => $database->name]), - ); - - return $databases->firstWhere('id', $selectedDatabase); - } - - protected function getByNameOrId(string $identifier, ?Collection $databases = null): ?DatabaseCluster - { - $databases ??= $this->fetchDatabases(); - - return $databases->firstWhere('id', $identifier) - ?? $databases->firstWhere('name', $identifier); - } - - protected function displayDatabase(DatabaseCluster $database, $showPrompt = true): void - { - if ($showPrompt) { - answered(label: 'Database', answer: "{$database->name}"); - } - } - - protected function fetchDatabases(): Collection - { - return collect(spin( - fn () => $this->client->databaseClusters()->include('schemas')->list()->items(), - 'Fetching databases...', - )); - } -} diff --git a/app/Concerns/RequiresEnvironment.php b/app/Concerns/RequiresEnvironment.php deleted file mode 100644 index 63925634..00000000 --- a/app/Concerns/RequiresEnvironment.php +++ /dev/null @@ -1,41 +0,0 @@ - $environments - */ - protected function getEnvironment(Collection|LazyCollection $environments): Environment - { - $environmentArg = $this->hasArgument('environment') ? $this->argument('environment') : null; - - if ($environmentArg) { - $environment = $environments->firstWhere('name', $environmentArg); - answered(label: 'Environment', answer: "{$environment->name}"); - - return $environment; - } - - if ($environments->hasSole()) { - $environment = $environments->first(); - answered(label: 'Environment', answer: "{$environment->name}"); - - return $environment; - } - - $selection = select( - label: 'Environment', - options: $environments->mapWithKeys(fn ($env) => [$env->id => $env->name])->toArray(), - ); - - return $environments->firstWhere('id', $selection); - } -} diff --git a/app/Concerns/Validates.php b/app/Concerns/Validates.php index 84bbde1f..a3fb7fee 100644 --- a/app/Concerns/Validates.php +++ b/app/Concerns/Validates.php @@ -23,12 +23,11 @@ trait Validates */ protected function loopUntilValid(callable $callback, int $maxAttempts = 20, bool|callable $suppressOutput = false, ?callable $handleNonInteractiveErrors = null): mixed { - $result = null; $this->errors ??= new ValidationErrors; $attempts = 0; $this->form()->errors($this->errors); - while (! $result) { + while (true) { // @phpstan-ignore while.alwaysTrue if ($attempts >= $maxAttempts) { throw new RuntimeException('Maximum attempts reached'); } @@ -38,13 +37,11 @@ protected function loopUntilValid(callable $callback, int $maxAttempts = 20, boo $attempts++; try { - $result = $callback($this->errors); - - return $result; + return $callback($this->errors); } catch (RequestException $e) { $this->errors->clear(); - if ($e->getResponse()?->status() === 422) { + if ($e->getResponse()->status() === 422) { $responseErrors = $e->getResponse()->json('errors', []); if (count($responseErrors) > 0) { @@ -63,11 +60,6 @@ protected function loopUntilValid(callable $callback, int $maxAttempts = 20, boo } } } - - $this->errors->clear(); - $this->form()->clear(); - - return $result; } protected function displayValidationError(string $message, bool|callable $suppressOutput): void diff --git a/app/Middleware/CommandMiddlewareManager.php b/app/Middleware/CommandMiddlewareManager.php index fa2ba06e..5312c844 100644 --- a/app/Middleware/CommandMiddlewareManager.php +++ b/app/Middleware/CommandMiddlewareManager.php @@ -46,7 +46,7 @@ public function handleConsoleCommand(ConsoleCommandEvent $event): void return; } - $shouldContinue = true; + $shouldContinue = false; $this->executeMiddleware($command, function () use (&$shouldContinue) { $shouldContinue = true; diff --git a/app/Prompts/DataTableRenderer.php b/app/Prompts/DataTableRenderer.php index beb1cc51..f35470bb 100644 --- a/app/Prompts/DataTableRenderer.php +++ b/app/Prompts/DataTableRenderer.php @@ -125,11 +125,7 @@ protected function renderSearch(DataTable $prompt): void return; } - if ($prompt->query !== '') { - $this->withPageCount($prompt, ' Search: '.$prompt->query); - - return; - } + $this->withPageCount($prompt, ' Search: '.$prompt->query); } protected function withPageCount(DataTable $prompt, string $content): void diff --git a/app/Prompts/DynamicSpinner.php b/app/Prompts/DynamicSpinner.php index 83c8d953..59fb7e4f 100644 --- a/app/Prompts/DynamicSpinner.php +++ b/app/Prompts/DynamicSpinner.php @@ -80,14 +80,14 @@ public function spin(Closure $callback): mixed pcntl_signal(SIGINT, fn () => exit()); - $this->sockets = stream_socket_pair(STREAM_PF_UNIX, STREAM_SOCK_STREAM, STREAM_IPPROTO_IP); - - if ($this->sockets === false) { - $this->sockets = null; + $sockets = stream_socket_pair(STREAM_PF_UNIX, STREAM_SOCK_STREAM, STREAM_IPPROTO_IP); + if ($sockets === false) { return $this->renderStatically($callback); } + $this->sockets = $sockets; + try { $this->hideCursor(); $this->render(); @@ -98,7 +98,7 @@ public function spin(Closure $callback): mixed fclose($this->sockets[0]); stream_set_blocking($this->sockets[1], false); - while (true) { + while (true) { // @phpstan-ignore while.alwaysTrue $this->checkForMessageUpdate(); $this->render(); diff --git a/app/Prompts/EnvironmentLogsPrompt.php b/app/Prompts/EnvironmentLogsPrompt.php index 246d5ae9..1e50d7e7 100644 --- a/app/Prompts/EnvironmentLogsPrompt.php +++ b/app/Prompts/EnvironmentLogsPrompt.php @@ -74,7 +74,7 @@ public function display(): void $this->from = $this->to; $this->to = CarbonImmutable::now()->toIso8601String(); - while (true) { + while (true) { // @phpstan-ignore while.alwaysTrue $this->count++; $now = CarbonImmutable::now(); diff --git a/app/Prompts/EnvironmentLogsPromptRenderer.php b/app/Prompts/EnvironmentLogsPromptRenderer.php index 8ef2a712..a68b0b88 100644 --- a/app/Prompts/EnvironmentLogsPromptRenderer.php +++ b/app/Prompts/EnvironmentLogsPromptRenderer.php @@ -85,7 +85,7 @@ public function writeLog(EnvironmentLog $log): void } /** - * @return array{title: string, body: ?string, info: string, footer: string} + * @return array{title?: string, body?: string, info?: string, footer?: string} */ protected function getBoxParams(EnvironmentLog $log): array { @@ -119,7 +119,7 @@ protected function getBoxParams(EnvironmentLog $log): array if ($log->isApplicationLog()) { $json = $this->tryToDecodeJson($log->message); - if ($json !== null && is_array($json)) { + if ($json !== null) { $body = $this->getBody($json['message'] ?? ''); $footer = []; @@ -164,7 +164,7 @@ protected function getPotentialJsonMessage(string $message): string { $decoded = $this->tryToDecodeJson($message); - if ($decoded !== null && is_array($decoded)) { + if ($decoded !== null) { return json_encode($decoded, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); } diff --git a/app/Prompts/Hyb.php b/app/Prompts/Hyb.php deleted file mode 100644 index 1ad9c771..00000000 --- a/app/Prompts/Hyb.php +++ /dev/null @@ -1,143 +0,0 @@ -minWidth = min($this->minWidth, $this->terminal()->cols() - 6); - - $font = Font::load('computer'); - - $this->capturePreviousNewLines(); - $this->hideCursor(); - - $characterWidth = $font->characterWidth(); - $terminalWidth = $this->terminal()->cols(); - $message = str('HYB*')->repeat(floor($terminalWidth / ($characterWidth * 3)) - 1)->toString(); - - $this->letters = collect($font->message($message)) - ->map(function ($lines, $index) { - if ($lines === null) { - $this->bold = ! $this->bold; - - return null; - } - - $animation = new Animatable(0, 0, count($lines)); - $animation->delay($index); - $animation->pauseAfter(35); - $animation->toggle(); - $this->animations[] = $animation; - - $longest = collect($lines)->max(fn ($line) => mb_strwidth($line)) + 1; - - return collect($lines)->map(function ($line) use ($longest) { - while (mb_strwidth($line) < $longest) { - $line .= ' '; - } - - $tag = $this->bold ? 'info' : 'comment'; - - return "<{$tag}>{$line}"; - }); - }) - ->filter(fn ($line) => $line !== null) - ->values(); - - while (count($this->animationsCompleted) < count($this->animations)) { - $currentLetters = []; - - foreach ($this->animations as $index => $animation) { - $letter = $this->letters[$index]; - $newLetter = $letter->toArray(); - - $newLetter = array_slice($newLetter, 0, $animation->current()); - - while (count($newLetter) < count($letter)) { - array_unshift($newLetter, str_repeat(' ', mb_strwidth($this->stripEscapeSequences($letter[0])))); - } - - $currentLetters[] = $newLetter; - - $animation->whenDoneAnimating(fn () => $animation->toggle()); - - $animation->animate(); - } - - $this->lines = collect(array_shift($currentLetters))->zip(...$currentLetters)->map(fn ($l) => $l->implode('')); - $this->render(); - Sleep::for(CarbonInterval::milliseconds(25)); - } - } - - /** - * Render the prompt. - */ - protected function render(): void - { - $this->terminal()->initDimensions(); - - $frame = $this->renderTheme(); - - if ($frame === $this->prevFrame) { - return; - } - - if ($this->state === 'initial') { - static::output()->write($frame); - - $this->state = 'active'; - $this->prevFrame = $frame; - - return; - } - - $terminalHeight = $this->terminal()->lines(); - $previousFrameHeight = count(explode(PHP_EOL, $this->prevFrame)); - $renderableLines = array_slice(explode(PHP_EOL, $frame), abs(min(0, $terminalHeight - $previousFrameHeight))); - - $this->moveCursorToColumn(1); - $this->moveCursorUp(min($terminalHeight, $previousFrameHeight) - 1); - // $this->eraseDown(); - $this->output()->write(implode(PHP_EOL, $renderableLines)); - - $this->prevFrame = $frame; - } - - public function value(): mixed - { - return null; - } -} diff --git a/app/Prompts/HybRenderer.php b/app/Prompts/HybRenderer.php deleted file mode 100644 index d7657942..00000000 --- a/app/Prompts/HybRenderer.php +++ /dev/null @@ -1,11 +0,0 @@ -lines->implode(PHP_EOL).PHP_EOL.PHP_EOL.PHP_EOL; - } -} diff --git a/app/Prompts/MultiSelectPromptRenderer.php b/app/Prompts/MultiSelectPromptRenderer.php index b2617ca9..164ee9ae 100644 --- a/app/Prompts/MultiSelectPromptRenderer.php +++ b/app/Prompts/MultiSelectPromptRenderer.php @@ -66,7 +66,7 @@ public function __invoke(MultiSelectPrompt $prompt): string protected function renderOptions(MultiSelectPrompt $prompt): string { return implode(PHP_EOL, $this->scrollbar( - array_values(array_map(function ($label, $key) use ($prompt) { + array_map(function ($label, $key) use ($prompt) { $label = $this->truncate($label, $prompt->terminal()->cols() - 12); $index = array_search($key, array_keys($prompt->options)); @@ -94,7 +94,7 @@ protected function renderOptions(MultiSelectPrompt $prompt): string $selected => " {$this->cyan('◼')} {$this->dim($label)} ", default => " {$this->dim('◻')} {$this->dim($label)} ", }; - }, $visible = $prompt->visible(), array_keys($visible))), + }, $visible = $prompt->visible(), array_keys($visible)), $prompt->firstVisible, $prompt->scroll, count($prompt->options), diff --git a/app/Prompts/Renderer.php b/app/Prompts/Renderer.php index a42abc5e..f045cb39 100644 --- a/app/Prompts/Renderer.php +++ b/app/Prompts/Renderer.php @@ -28,41 +28,49 @@ public static function resetOutroFlag(): void self::$commandAlreadyShowedOutro = false; } - protected function lineWithBorder(string $message): self + protected function lineWithBorder(string $message): static { - return $this->line(TimelineSymbol::LINE->value.' '.$message); + $this->line(TimelineSymbol::LINE->value.' '.$message); + + return $this; } /** * Render a warning message. */ - protected function bullet(string $message, TimelineSymbol $symbol = TimelineSymbol::DOT): self + protected function bullet(string $message, TimelineSymbol $symbol = TimelineSymbol::DOT): static { $color = $symbol->color(); - return $this->line($this->{$color}($symbol->value).' '.$message); + $this->line($this->{$color}($symbol->value).' '.$message); + + return $this; } /** * Render a warning message. */ - protected function warning(string $message): self + protected function warning(string $message): static { - return $this->line(TimelineSymbol::LINE->value.$this->yellow(" {$message}")); + $this->line(TimelineSymbol::LINE->value.$this->yellow(" {$message}")); + + return $this; } /** * Render an error message. */ - protected function error(string $message): self + protected function error(string $message): static { - return $this->line(TimelineSymbol::LINE->value.$this->red(" {$message}")); + $this->line(TimelineSymbol::LINE->value.$this->red(" {$message}")); + + return $this; } /** * Render an hint message. */ - protected function hint(string $message): self + protected function hint(string $message): static { if ($message === '') { return $this; @@ -70,7 +78,9 @@ protected function hint(string $message): self $message = $this->truncate($message, $this->prompt->terminal()->cols() - 6); - return $this->line(TimelineSymbol::LINE->value.$this->gray(" {$message}")); + $this->line(TimelineSymbol::LINE->value.$this->gray(" {$message}")); + + return $this; } /** diff --git a/app/Prompts/SearchPromptRenderer.php b/app/Prompts/SearchPromptRenderer.php index cd29cc7a..0e2924a9 100644 --- a/app/Prompts/SearchPromptRenderer.php +++ b/app/Prompts/SearchPromptRenderer.php @@ -109,7 +109,7 @@ protected function renderOptions(SearchPrompt $prompt): string } return implode(PHP_EOL, $this->scrollbar( - array_values(array_map(function ($label, $key) use ($prompt) { + array_map(function ($label, $key) use ($prompt) { $label = $this->truncate($label, $prompt->terminal()->cols() - 10); $index = array_search($key, array_keys($prompt->matches())); @@ -117,7 +117,7 @@ protected function renderOptions(SearchPrompt $prompt): string return $prompt->highlighted === $index ? "{$this->cyan('›')} {$label} " : " {$this->dim($label)} "; - }, $visible = $prompt->visible(), array_keys($visible))), + }, $visible = $prompt->visible(), array_keys($visible)), $prompt->firstVisible, $prompt->scroll, count($prompt->matches()), diff --git a/app/Prompts/SelectPromptRenderer.php b/app/Prompts/SelectPromptRenderer.php index 9b415f08..72d88860 100644 --- a/app/Prompts/SelectPromptRenderer.php +++ b/app/Prompts/SelectPromptRenderer.php @@ -66,7 +66,7 @@ public function __invoke(SelectPrompt $prompt): string protected function renderOptions(SelectPrompt $prompt): string { return implode(PHP_EOL, $this->scrollbar( - array_values(array_map(function ($label, $key) use ($prompt) { + array_map(function ($label, $key) use ($prompt) { $label = $this->truncate($label, $prompt->terminal()->cols() - 12); $index = array_search($key, array_keys($prompt->options)); @@ -82,7 +82,7 @@ protected function renderOptions(SelectPrompt $prompt): string return $prompt->highlighted === $index ? "{$this->cyan('›')} {$this->cyan('●')} {$label} " : " {$this->dim('○')} {$this->dim($label)} "; - }, $visible = $prompt->visible(), array_keys($visible))), + }, $visible = $prompt->visible(), array_keys($visible)), $prompt->firstVisible, $prompt->scroll, count($prompt->options), diff --git a/app/Prompts/SelectWithContextPrompt.php b/app/Prompts/SelectWithContextPrompt.php index 6ae92722..05afa1a2 100644 --- a/app/Prompts/SelectWithContextPrompt.php +++ b/app/Prompts/SelectWithContextPrompt.php @@ -10,6 +10,9 @@ class SelectWithContextPrompt extends SelectPrompt { public array $context = []; + /** + * @param array|Collection $options + */ public function __construct( string $label, array|Collection $options, diff --git a/app/Prompts/SelectWithContextPromptRenderer.php b/app/Prompts/SelectWithContextPromptRenderer.php index c680bb57..6a1e7308 100644 --- a/app/Prompts/SelectWithContextPromptRenderer.php +++ b/app/Prompts/SelectWithContextPromptRenderer.php @@ -67,7 +67,7 @@ public function __invoke(SelectWithContextPrompt $prompt): string protected function renderOptions(SelectWithContextPrompt $prompt): string { return implode(PHP_EOL, $this->scrollbar( - array_values(array_map(function ($label, $key) use ($prompt) { + array_map(function ($label, $key) use ($prompt) { $label = $this->truncate($label, $prompt->terminal()->cols() - 12); $index = array_search($key, array_keys($prompt->options)); @@ -83,7 +83,7 @@ protected function renderOptions(SelectWithContextPrompt $prompt): string return $prompt->highlighted === $index ? "{$this->cyan('›')} {$this->cyan('●')} {$label} " : " {$this->dim('○')} {$this->dim($label)} "; - }, $visible = $prompt->visible(), array_keys($visible))), + }, $visible = $prompt->visible(), array_keys($visible)), $prompt->firstVisible, $prompt->scroll, count($prompt->options), diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index 390c94fc..eee3e558 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -33,7 +33,6 @@ public function boot(): void 'DataListRenderer', 'DataTableRenderer', 'EnvironmentLogsPromptRenderer', - 'HybRenderer', 'MonitorCommandRenderer', 'MonitorDeploymentsRenderer', 'MultiSelectPromptRenderer', diff --git a/app/Resolvers/DatabaseSnapshotResolver.php b/app/Resolvers/DatabaseSnapshotResolver.php index 3a9ea3aa..271563e5 100644 --- a/app/Resolvers/DatabaseSnapshotResolver.php +++ b/app/Resolvers/DatabaseSnapshotResolver.php @@ -5,6 +5,7 @@ use App\Dto\DatabaseCluster; use App\Dto\DatabaseSnapshot; use Illuminate\Support\Collection; +use Illuminate\Support\LazyCollection; use function Laravel\Prompts\spin; @@ -56,7 +57,7 @@ public function fromInput(DatabaseCluster $cluster): ?DatabaseSnapshot return $snapshots->firstWhere('id', $selected); } - protected function fetchAll(DatabaseCluster $cluster): Collection + protected function fetchAll(DatabaseCluster $cluster): Collection|LazyCollection { return spin( fn () => $this->client->databaseSnapshots()->list($cluster->id)->collect(), diff --git a/app/Resolvers/DeploymentResolver.php b/app/Resolvers/DeploymentResolver.php index aaa14d4c..2ecd4464 100644 --- a/app/Resolvers/DeploymentResolver.php +++ b/app/Resolvers/DeploymentResolver.php @@ -4,6 +4,7 @@ use App\Dto\Deployment; use App\Resolvers\Concerns\HasAnEnvironment; +use Illuminate\Support\Collection; use function Laravel\Prompts\spin; @@ -35,6 +36,7 @@ public function from(?string $id = null): ?Deployment public function fromIdentifier(string $identifier): ?Deployment { + /** @var Deployment|null */ return $this->resolveFromIdentifier( $identifier, fn () => spin( @@ -47,6 +49,7 @@ public function fromIdentifier(string $identifier): ?Deployment public function fromInput(): ?Deployment { $environment = $this->environment(); + /** @var Collection $deployments */ $deployments = collect( spin( fn () => $this->client->deployments()->include('environment')->list($environment->id)->items(), @@ -73,6 +76,7 @@ public function fromInput(): ?Deployment $this->displayResolved = false; + /** @var Deployment|null */ return $deployments->firstWhere('id', $selection); } diff --git a/app/Resolvers/InstanceResolver.php b/app/Resolvers/InstanceResolver.php index 8c227352..4b990f27 100644 --- a/app/Resolvers/InstanceResolver.php +++ b/app/Resolvers/InstanceResolver.php @@ -56,7 +56,7 @@ public function fromInput(): ?EnvironmentInstance } if ($instances->hasSole()) { - answered(label: 'Instance', answer: $instances->first()); + answered(label: 'Instance', answer: $instances->first()->name); return $instances->first(); } diff --git a/app/Resolvers/Resolvers.php b/app/Resolvers/Resolvers.php index ab9a5491..1c71fef0 100644 --- a/app/Resolvers/Resolvers.php +++ b/app/Resolvers/Resolvers.php @@ -90,6 +90,12 @@ public function websocketApplication(): WebSocketApplicationResolver return $this->make(WebSocketApplicationResolver::class); } + /** + * @template T of Resolver + * + * @param class-string $resolver + * @return T + */ protected function make(string $resolver): Resolver { return new $resolver($this->client, $this->localConfig, $this->isInteractive); diff --git a/app/Support/ContextDetector.php b/app/Support/ContextDetector.php index d6499b3b..35a6374f 100644 --- a/app/Support/ContextDetector.php +++ b/app/Support/ContextDetector.php @@ -30,7 +30,7 @@ public static function agent(): ?string $result = AgentDetector::detect(); static::$resolvedAgent = $result->isAgent - ? ($result->knownAgent()?->value ?? $result->name) + ? ($result->knownAgent()->value ?? $result->name) : null; static::$agentResolved = true; diff --git a/app/Support/KeyPressListener.php b/app/Support/KeyPressListener.php index 10089a8e..25d13e27 100644 --- a/app/Support/KeyPressListener.php +++ b/app/Support/KeyPressListener.php @@ -47,7 +47,7 @@ public function afterEveryKey(callable $callback): static public function listenNow() { - while (($key = $this->prompt->terminal()->read()) !== null) { + while (($key = $this->prompt->terminal()->read()) !== '') { if ($this->handleKey($key) === false) { break; } diff --git a/phpstan.neon.dist b/phpstan.neon.dist new file mode 100644 index 00000000..f9db5db8 --- /dev/null +++ b/phpstan.neon.dist @@ -0,0 +1,5 @@ +parameters: + paths: + - app + + level: 5 diff --git a/tests/Feature/ApplicationCommandsTest.php b/tests/Feature/ApplicationCommandsTest.php index a9351df8..a661f52d 100644 --- a/tests/Feature/ApplicationCommandsTest.php +++ b/tests/Feature/ApplicationCommandsTest.php @@ -33,7 +33,7 @@ // ---- application:list ---- it('lists applications successfully in interactive mode', function () { - Prompt::fake(["\n"]); + Prompt::fake(); setupApplicationListMocks(); diff --git a/tests/Feature/DeployTest.php b/tests/Feature/DeployTest.php index c2f573bb..a26fff7a 100644 --- a/tests/Feature/DeployTest.php +++ b/tests/Feature/DeployTest.php @@ -18,6 +18,7 @@ $this->mockGit = Mockery::mock(Git::class); $this->mockGit->shouldReceive('isRepo')->andReturn(true)->byDefault(); $this->mockGit->shouldReceive('getRoot')->andReturn('/tmp/test-repo')->byDefault(); + $this->mockGit->shouldReceive('currentBranch')->andReturn('main')->byDefault(); $this->app->instance(Git::class, $this->mockGit); $this->mockConfig = Mockery::mock(ConfigRepository::class);