Skip to content

Commit

Permalink
Fix some phpstan level 7 errors
Browse files Browse the repository at this point in the history
  • Loading branch information
pjcdawkins committed Dec 20, 2024
1 parent d8a1a75 commit f5fda09
Show file tree
Hide file tree
Showing 69 changed files with 355 additions and 254 deletions.
6 changes: 2 additions & 4 deletions src/Command/Activity/ActivityCancelCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,20 +81,18 @@ protected function execute(InputInterface $input, OutputInterface $output): int
return 1;
}
$choices = [];
$questionHelper = $this->questionHelper;
$formatter = $this->propertyFormatter;
$byId = [];
$this->api->sortResources($activities, 'created_at');
foreach ($activities as $activity) {
$byId[$activity->id] = $activity;
$choices[$activity->id] = \sprintf(
'%s: %s (%s)',
$formatter->formatDate($activity->created_at),
$this->propertyFormatter->formatDate($activity->created_at),
ActivityMonitor::getFormattedDescription($activity),
ActivityMonitor::formatState($activity->state)
);
}
$id = $questionHelper->choose($choices, 'Enter a number to choose an activity to cancel:', key($choices), true);
$id = $this->questionHelper->choose($choices, 'Enter a number to choose an activity to cancel:', (string) key($choices));
$activity = $byId[$id];
}

Expand Down
4 changes: 0 additions & 4 deletions src/Command/Auth/AuthInfoCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,10 +57,6 @@ protected function execute(InputInterface $input, OutputInterface $output): int
// Exit early if it's the user ID.
if ($property === 'id') {
$userId = $this->api->getMyUserId($input->getOption('refresh'));
if ($userId === false) {
$this->stdErr->writeln('The current session is not associated with a user ID');
return 1;
}
$output->writeln($userId);
return 0;
}
Expand Down
3 changes: 1 addition & 2 deletions src/Command/Auth/BrowserLoginCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -88,8 +88,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int
$account['email']
));

$questionHelper = $this->questionHelper;
if (!$questionHelper->confirm('Log in anyway?', false)) {
if (!$this->questionHelper->confirm('Log in anyway?', false)) {
return 1;
}
$force = true;
Expand Down
2 changes: 1 addition & 1 deletion src/Command/Backup/BackupCreateCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int
$this->stdErr->writeln('The environment is not active.');
} else {
try {
if ($this->isUserAdmin($selection->getProject(), $selectedEnvironment, (string) $this->api->getMyUserId())) {
if ($this->isUserAdmin($selection->getProject(), $selectedEnvironment, $this->api->getMyUserId())) {
$this->stdErr->writeln('You must be an administrator to create a backup.');
}
} catch (\Exception $e) {
Expand Down
3 changes: 1 addition & 2 deletions src/Command/Backup/BackupGetCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int
}
$choices[$id] = sprintf('%s (%s)', $backup->id, $this->propertyFormatter->format($backup->created_at, 'created_at'));
}
$questionHelper = $this->questionHelper;
$choice = $questionHelper->choose($choices, 'Enter a number to choose a backup:', $default);
$choice = $this->questionHelper->choose($choices, 'Enter a number to choose a backup:', $default);
$backup = $byId[$choice];
}

Expand Down
3 changes: 1 addition & 2 deletions src/Command/Db/DbSqlCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -105,8 +105,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int
$choices[$schema] .= ' (default)';
}
}
$questionHelper = $this->questionHelper;
$schema = $questionHelper->choose($choices, 'Enter a number to choose a schema:', $default, true);
$schema = $this->questionHelper->choose($choices, 'Enter a number to choose a schema:', $default, true);
$schema = $schema === '(none)' ? '' : $schema;
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/Command/Domain/DomainCommandBase.php
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ protected function validateDomainInput(InputInterface $input, Selection $selecti
. "\nA non-production domain must be attached to an existing production domain."
. "\nIt will inherit the same routing behavior."
. "\nChoose a production domain:";
$this->attach = (string) $this->questionHelper->choose($choices, $questionText, $default);
$this->attach = $this->questionHelper->choose($choices, $questionText, $default);
}
} elseif ($this->attach !== null) {
try {
Expand Down
3 changes: 1 addition & 2 deletions src/Command/Domain/DomainGetCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int
$options[$domain->name] = $domain->name;
$byName[$domain->name] = $domain;
}
$questionHelper = $this->questionHelper;
$domainName = $questionHelper->choose($options, 'Enter a number to choose a domain:');
$domainName = $this->questionHelper->choose($options, 'Enter a number to choose a domain:');
$domain = $byName[$domainName];
}

Expand Down
3 changes: 1 addition & 2 deletions src/Command/Environment/EnvironmentBranchCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -103,8 +103,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int

return 1;
}
$questionHelper = $this->questionHelper;
$checkout = $questionHelper->confirm(
$checkout = $this->questionHelper->confirm(
"The environment <comment>$branchName</comment> already exists. Check out?"
);
if ($checkout) {
Expand Down
2 changes: 1 addition & 1 deletion src/Command/Environment/EnvironmentCheckoutCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ protected function offerBranchChoice(Project $project, string $projectRoot): str
// The environment ID will be an integer if it was numeric
// (because PHP does that with array keys), so it's cast back to
// a string here.
return (string) $this->questionHelper->choose($environmentList, $chooseEnvironmentText);
return $this->questionHelper->choose($environmentList, $chooseEnvironmentText);
}

// If there's only one choice, QuestionHelper::choose() does not
Expand Down
3 changes: 1 addition & 2 deletions src/Command/Environment/EnvironmentLogCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,6 @@ protected function execute(InputInterface $input, OutputInterface $output): int
$this->stdErr->writeln('No log type specified.');
return 1;
} else {
$questionHelper = $this->questionHelper;

// Read the list of files from the environment.
$cacheKey = sprintf('log-files:%s', $host->getCacheKey());
Expand All @@ -102,7 +101,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int

// Ask the user to choose a file.
$files = array_combine($files, array_map(fn($file): string => str_replace('.log', '', basename(trim((string) $file))), $files));
$logFilename = $questionHelper->choose($files, 'Enter a number to choose a log: ');
$logFilename = $this->questionHelper->choose($files, 'Enter a number to choose a log: ');
}

$command = sprintf('tail -n %1$d %2$s', $input->getOption('lines'), $logFilename);
Expand Down
3 changes: 1 addition & 2 deletions src/Command/Environment/EnvironmentUrlCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -120,8 +120,7 @@ private function displayOrOpenUrls(array $urls, InputInterface $input, OutputInt
if (count($urls) === 1) {
$url = $urls[0];
} else {
$questionHelper = $this->questionHelper;
$url = (string) $questionHelper->choose(array_combine($urls, $urls), 'Enter a number to open a URL', $urls[0]);
$url = $this->questionHelper->choose(array_combine($urls, $urls), 'Enter a number to open a URL', $urls[0]);
}

$this->url->openUrl($url);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
use Platformsh\Cli\Service\ActivityMonitor;
use Platformsh\Cli\Service\PropertyFormatter;
use Platformsh\Cli\Service\Table;
use Platformsh\Client\Model\Activity;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
Expand Down
16 changes: 11 additions & 5 deletions src/Command/Integration/IntegrationCommandBase.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ abstract class IntegrationCommandBase extends CommandBase

private ?Form $form = null;

/** @var array<string, string> */
private array $bitbucketAccessTokens = [];

protected ?Selection $selection = null;
Expand Down Expand Up @@ -63,12 +64,11 @@ protected function selectIntegration(Project $project, ?string $id, bool $intera

return false;
}
$questionHelper = $this->questionHelper;
$choices = [];
foreach ($integrations as $integration) {
$choices[$integration->id] = sprintf('%s (%s)', $integration->id, $integration->type);
}
$id = $questionHelper->choose($choices, 'Enter a number to choose an integration:');
$id = $this->questionHelper->choose($choices, 'Enter a number to choose an integration:');
}

$integration = $project->getIntegration($id);
Expand Down Expand Up @@ -118,10 +118,10 @@ protected function handleConditionalFieldException(ConditionalFieldException $e)
/**
* Performs extra logic on values after the form is complete.
*
* @param array $values
* @param array<string, mixed> $values
* @param Integration|null $integration
*
* @return array
* @return array<string, mixed>
*/
protected function postProcessValues(array $values, ?Integration $integration = null): array
{
Expand Down Expand Up @@ -170,7 +170,7 @@ protected function postProcessValues(array $values, ?Integration $integration =
/**
* Returns a list of integration capability information on the selected project, if any.
*
* @return array
* @return array{enabled: bool, config?: array<string, array{enabled: bool}>}
*/
private function selectedProjectIntegrations(): array
{
Expand Down Expand Up @@ -658,6 +658,8 @@ protected function displayIntegration(Integration $integration): void

/**
* Obtains an OAuth2 token for Bitbucket from the given app credentials.
*
* @param array{key: string, secret: string} $credentials
*/
protected function getBitbucketAccessToken(array $credentials): string
{
Expand Down Expand Up @@ -685,6 +687,8 @@ protected function getBitbucketAccessToken(array $credentials): string

/**
* Validates Bitbucket credentials.
*
* @param array{key: string, secret: string} $credentials
*/
protected function validateBitbucketCredentials(array $credentials): true|string
{
Expand All @@ -705,6 +709,8 @@ protected function validateBitbucketCredentials(array $credentials): true|string

/**
* Lists validation errors found in an integration.
*
* @param array<int|string, string> $errors
*/
protected function listValidationErrors(array $errors, OutputInterface $output): void
{
Expand Down
2 changes: 1 addition & 1 deletion src/Command/Integration/IntegrationListCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ protected function getIntegrationSummary(Integration $integration): string
break;

default:
$summary = json_encode($details);
$summary = json_encode($details, JSON_THROW_ON_ERROR);
}

if (strlen($summary) > 240) {
Expand Down
5 changes: 2 additions & 3 deletions src/Command/LegacyMigrateCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,6 @@ protected function execute(InputInterface $input, OutputInterface $output): int
throw new RootNotFoundException();
}

$cwd = getcwd();

$repositoryDir = $legacyRoot . '/repository';
if (!is_dir($repositoryDir)) {
$this->stdErr->writeln('Directory not found: <error>' . $repositoryDir . '</error>');
Expand Down Expand Up @@ -158,7 +156,8 @@ protected function execute(InputInterface $input, OutputInterface $output): int

$this->stdErr->writeln("\n<info>Migration complete</info>\n");

if (str_starts_with($cwd, $repositoryDir)) {
$cwd = getcwd();
if ($cwd !== false && str_starts_with($cwd, $repositoryDir)) {
$this->stdErr->writeln('Type this to refresh your shell:');
$this->stdErr->writeln(' <comment>cd ' . $legacyRoot . '</comment>');
}
Expand Down
2 changes: 1 addition & 1 deletion src/Command/Local/LocalBuildCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int

if ($sourceDirOption) {
$sourceDir = realpath($sourceDirOption);
if (!is_dir($sourceDir)) {
if ($sourceDir === false || !is_dir($sourceDir)) {
throw new InvalidArgumentException('Source directory not found: ' . $sourceDirOption);
}

Expand Down
6 changes: 3 additions & 3 deletions src/Command/Local/LocalDrushAliasesCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int
}

if ($input->isInteractive()) {
$this->migrateAliasFiles($this->drush);
$this->migrateAliasFiles();
}

$aliases = $this->drush->getAliases($current_group);
Expand Down Expand Up @@ -210,7 +210,7 @@ protected function ensureDrushConfig(): void
$drushYml = $this->drush->getDrushDir() . '/drush.yml';
$drushConfig = [];
if (file_exists($drushYml)) {
$drushConfig = (array) Yaml::parse(file_get_contents($drushYml));
$drushConfig = (array) Yaml::parse((string) file_get_contents($drushYml));
}
$aliasPath = $this->drush->getSiteAliasDir();
if (getenv('HOME')) {
Expand All @@ -233,7 +233,7 @@ protected function ensureDrushConfig(): void
/**
* Migrates old alias file(s) from ~/.drush to ~/.drush/site-aliases.
*/
protected function migrateAliasFiles(Drush $drush): void
protected function migrateAliasFiles(): void
{
$newDrushDir = $this->drush->getHomeDir() . '/.drush/site-aliases';
$oldFilenames = $this->drush->getLegacyAliasFiles();
Expand Down
2 changes: 2 additions & 0 deletions src/Command/Metrics/DiskUsageCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,9 @@ class DiskUsageCommand extends MetricsCommandBase
];
/** @var string[] */
private array $defaultColumns = ['timestamp', 'service', 'used', 'limit', 'percent', 'ipercent', 'tmp_percent'];
/** @var string[] */
private array $tmpReportColumns = ['timestamp', 'service', 'tmp_used', 'tmp_limit', 'tmp_percent', 'tmp_ipercent'];

public function __construct(private readonly PropertyFormatter $propertyFormatter, private readonly Selector $selector, private readonly Table $table)
{
parent::__construct();
Expand Down
13 changes: 7 additions & 6 deletions src/Command/Metrics/MetricsCommandBase.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ abstract class MetricsCommandBase extends CommandBase
*/
private bool $foundHighMemoryServices = false;

/** @var array<string, array<string, string>> */
private array $fields = [
// Grid.
'local' => [
Expand Down Expand Up @@ -189,7 +190,7 @@ private function dimensionFields(string $dimension): array
* @param string[] $fieldNames
* An array of field names, which map to queries in $this->fields.
*
* @return false|array
* @return false|array<string, array<string, array<string, array<string, mixed>>>>
* False on failure, or an array of sketch values, keyed by: time, service, dimension, and name.
*/
protected function fetchMetrics(InputInterface $input, TimeSpec $timeSpec, Environment $environment, array $fieldNames): array|false
Expand Down Expand Up @@ -275,7 +276,7 @@ protected function fetchMetrics(InputInterface $input, TimeSpec $timeSpec, Envir
$client = $this->api->getHttpClient();
$request = new Request('POST', $metricsQueryUrl, [
'Content-Type' => 'application/json',
], json_encode($query->asArray()));
], json_encode($query->asArray(), JSON_THROW_ON_ERROR));
try {
$result = $client->send($request);
} catch (BadResponseException $e) {
Expand Down Expand Up @@ -458,12 +459,12 @@ private function getDeploymentType(Environment $environment): string
/**
* Builds metrics table rows.
*
* @param array $values
* @param array<string, array<string, array<string, array<string, mixed>>>> $values
* An array of values from fetchMetrics().
* @param array<string, Field> $fields
* An array of fields keyed by column name.
*
* @return array
* @return array<array<string, string|\Stringable>|TableSeparator>
* Table rows.
*/
protected function buildRows(array $values, array $fields, Environment $environment): array
Expand Down Expand Up @@ -542,8 +543,8 @@ protected function buildRows(array $values, array $fields, Environment $environm
/**
* Merges table rows per service to reduce unnecessary empty cells.
*
* @param array $rows
* @return array
* @param array<array<string, string|\Stringable>|TableSeparator> $rows
* @return array<array<string, string|\Stringable>|TableSeparator>
*/
private function mergeRows(array $rows): array
{
Expand Down
1 change: 1 addition & 0 deletions src/Command/Mount/MountDownloadCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
#[AsCommand(name: 'mount:download', description: 'Download files from a mount, using rsync')]
class MountDownloadCommand extends CommandBase
{
/** @var LocalApplication[]|null */
private ?array $localApps = null;

public function __construct(private readonly ApplicationFinder $applicationFinder, private readonly Config $config, private readonly Filesystem $filesystem, private readonly Mount $mount, private readonly QuestionHelper $questionHelper, private readonly Rsync $rsync, private readonly Selector $selector)
Expand Down
2 changes: 1 addition & 1 deletion src/Command/Mount/MountListCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int
if (($applicationEnv = getenv($this->config->getStr('service.env_prefix') . 'APPLICATION'))
&& !LocalHost::conflictsWithCommandLineOptions($input, $this->config->getStr('service.env_prefix'))) {
$this->io->debug('Selected host: localhost');
$config = json_decode(base64_decode($applicationEnv), true) ?: [];
$config = json_decode((string) base64_decode($applicationEnv), true) ?: [];
$mounts = $this->mount->mountsFromConfig(new AppConfig($config));
$appName = $config['name'];
$appType = str_contains((string) $appName, '--') ? 'worker' : 'app';
Expand Down
Loading

0 comments on commit f5fda09

Please sign in to comment.