diff --git a/composer.json b/composer.json index 454114684e..1633fc2544 100644 --- a/composer.json +++ b/composer.json @@ -61,7 +61,7 @@ "jetbrains/phpstorm-attributes": "^1.0", "mglaman/phpstan-drupal": "^1.2", "phpunit/phpunit": "^9", - "rector/rector": "^0.12", + "rector/rector": "^1", "squizlabs/php_codesniffer": "^3.7" }, "conflict": { diff --git a/composer.lock b/composer.lock index 0c38307f77..cb3c6cd1aa 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "43711a790c14f136cd6b9210d56a15de", + "content-hash": "e6d308380d24037b96d657f63233c02b", "packages": [ { "name": "chi-teck/drupal-code-generator", @@ -5903,42 +5903,32 @@ }, { "name": "rector/rector", - "version": "0.12.23", + "version": "1.0.3", "source": { "type": "git", "url": "https://github.com/rectorphp/rector.git", - "reference": "690b31768b322db886b35845f8452025eba2cacb" + "reference": "c59507a9090b465d65e1aceed91e5b81986e375b" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/rectorphp/rector/zipball/690b31768b322db886b35845f8452025eba2cacb", - "reference": "690b31768b322db886b35845f8452025eba2cacb", + "url": "https://api.github.com/repos/rectorphp/rector/zipball/c59507a9090b465d65e1aceed91e5b81986e375b", + "reference": "c59507a9090b465d65e1aceed91e5b81986e375b", "shasum": "" }, "require": { "php": "^7.2|^8.0", - "phpstan/phpstan": "^1.6" + "phpstan/phpstan": "^1.10.57" }, "conflict": { - "phpstan/phpdoc-parser": "<1.2", - "rector/rector-cakephp": "*", "rector/rector-doctrine": "*", - "rector/rector-laravel": "*", - "rector/rector-nette": "*", - "rector/rector-phpoffice": "*", + "rector/rector-downgrade-php": "*", "rector/rector-phpunit": "*", - "rector/rector-prefixed": "*", "rector/rector-symfony": "*" }, "bin": [ "bin/rector" ], "type": "library", - "extra": { - "branch-alias": { - "dev-main": "0.12-dev" - } - }, "autoload": { "files": [ "bootstrap.php" @@ -5949,9 +5939,15 @@ "MIT" ], "description": "Instant Upgrade and Automated Refactoring of any PHP code", + "keywords": [ + "automation", + "dev", + "migration", + "refactoring" + ], "support": { "issues": "https://github.com/rectorphp/rector/issues", - "source": "https://github.com/rectorphp/rector/tree/0.12.23" + "source": "https://github.com/rectorphp/rector/tree/1.0.3" }, "funding": [ { @@ -5959,7 +5955,7 @@ "type": "github" } ], - "time": "2022-05-01T15:50:16+00:00" + "time": "2024-03-14T15:04:18+00:00" }, { "name": "sebastian/cli-parser", diff --git a/rector.php b/rector.php index e76cb8cf96..1a5ee7759f 100644 --- a/rector.php +++ b/rector.php @@ -16,7 +16,7 @@ return static function (RectorConfig $config): void { $config->importNames(); - $config->disableImportShortClasses(); + $config->importShortClasses(false); $config->paths([ __DIR__ . '/src', @@ -37,5 +37,7 @@ SimplifyIfElseToTernaryRector::class, FinalizePublicClassConstantRector::class, NullToStrictStringFuncCallArgRector::class, + \Rector\Php81\Rector\Array_\FirstClassCallableRector::class, + \Rector\Strict\Rector\Empty_\DisallowedEmptyRuleFixerRector::class ]); }; diff --git a/src/Boot/BootstrapManager.php b/src/Boot/BootstrapManager.php index 8ca27f6f67..8c13c6227c 100644 --- a/src/Boot/BootstrapManager.php +++ b/src/Boot/BootstrapManager.php @@ -326,7 +326,7 @@ protected function maxPhaseLimit($bootstrap_str) { $bootstrap_words = explode(' ', $bootstrap_str); array_shift($bootstrap_words); - if (empty($bootstrap_words)) { + if ($bootstrap_words === []) { return null; } $stop_phase_name = array_shift($bootstrap_words); diff --git a/src/Commands/AutowireTrait.php b/src/Commands/AutowireTrait.php index faabc4197c..d4d77ef095 100644 --- a/src/Commands/AutowireTrait.php +++ b/src/Commands/AutowireTrait.php @@ -2,6 +2,7 @@ namespace Drush\Commands; +use Psr\Container\ContainerInterface; use Symfony\Component\DependencyInjection\Attribute\Autowire; use Symfony\Component\DependencyInjection\Exception\AutowiringFailedException; @@ -16,14 +17,14 @@ trait AutowireTrait { /** - * Instantiates a new instance of the implementing class using autowiring. - * - * @param \Psr\Container\ContainerInterface $container - * The service container this instance should use. - * - * @return static - */ - public static function create(\Psr\Container\ContainerInterface $container) + * Instantiates a new instance of the implementing class using autowiring. + * + * @param ContainerInterface $container + * The service container this instance should use. + * + * @return static + */ + public static function create(ContainerInterface $container) { $args = []; diff --git a/src/Commands/ConfiguresPrompts.php b/src/Commands/ConfiguresPrompts.php index 5359bc896a..dff20c7050 100644 --- a/src/Commands/ConfiguresPrompts.php +++ b/src/Commands/ConfiguresPrompts.php @@ -25,21 +25,21 @@ trait ConfiguresPrompts /** * Configure the prompt fallbacks. * - * @param \Symfony\Component\Console\Input\InputInterface $input + * @param InputInterface $input * @return void */ protected function configurePrompts(InputInterface $input) { Prompt::setOutput($this->output); - Prompt::cancelUsing(function () { + Prompt::cancelUsing(function (): never { Runtime::setCompleted(); exit(1); }); Prompt::interactive(($input->isInteractive() && defined('STDIN') && stream_isatty(STDIN)) || $this->runningUnitTests()); - Prompt::fallbackWhen(!$input->isInteractive() || strtoupper(substr(PHP_OS, 0, 3)) == "WIN" || $this->runningUnitTests()); + Prompt::fallbackWhen(!$input->isInteractive() || strtoupper(substr(PHP_OS, 0, 3)) === "WIN" || $this->runningUnitTests()); TextPrompt::fallbackUsing(fn (TextPrompt $prompt) => $this->promptUntilValid( fn () => (new SymfonyStyle($this->input, $this->output))->ask($prompt->label, $prompt->default ?: null) ?? '', @@ -180,10 +180,7 @@ protected function restorePrompts() protected function runningUnitTests(): bool { - if (! defined('PHPUNIT_COMPOSER_INSTALL') && ! defined('__PHPUNIT_PHAR__')) { - // is not PHPUnit run - return false; - } - return true; + // is not PHPUnit run + return !(! defined('PHPUNIT_COMPOSER_INSTALL') && ! defined('__PHPUNIT_PHAR__')); } } diff --git a/src/Commands/config/ConfigCommands.php b/src/Commands/config/ConfigCommands.php index 3fac7734b3..36575aaf0b 100644 --- a/src/Commands/config/ConfigCommands.php +++ b/src/Commands/config/ConfigCommands.php @@ -140,7 +140,7 @@ public function set($config_name, $key, $value, $options = ['input-format' => 's } // Special handling for null. - if (strtolower($data) == 'null') { + if (strtolower($data) === 'null') { $data = null; } diff --git a/src/Commands/config/ConfigExportCommands.php b/src/Commands/config/ConfigExportCommands.php index 48cfefb84f..0b68e40fd3 100644 --- a/src/Commands/config/ConfigExportCommands.php +++ b/src/Commands/config/ConfigExportCommands.php @@ -65,7 +65,7 @@ public function __construct(protected ConfigManagerInterface $configManager, pro public static function create(ContainerInterface $container): self { - $commandHandler = new static( + $commandHandler = new self( $container->get('config.manager'), $container->get('config.storage') ); diff --git a/src/Commands/core/BrowseCommands.php b/src/Commands/core/BrowseCommands.php index 5a7fd23f74..68f91d007a 100644 --- a/src/Commands/core/BrowseCommands.php +++ b/src/Commands/core/BrowseCommands.php @@ -21,7 +21,7 @@ final class BrowseCommands extends DrushCommands const BROWSE = 'browse'; public function __construct( - private SiteAliasManagerInterface $siteAliasManager + private readonly SiteAliasManagerInterface $siteAliasManager ) { parent::__construct(); } diff --git a/src/Commands/core/CacheCommands.php b/src/Commands/core/CacheCommands.php index 5508e3b6a4..77dfe45c80 100644 --- a/src/Commands/core/CacheCommands.php +++ b/src/Commands/core/CacheCommands.php @@ -175,14 +175,11 @@ protected function setPrepareData($data, $options) $data = $this->stdin()->contents(); } - // Now, we parse the object. - switch ($options['input-format']) { - case 'json': - $data = json_decode($data, true); - if ($data === false) { - throw new \Exception('Unable to parse JSON.'); - } - break; + if ($options['input-format'] === 'json') { + $data = json_decode($data, true); + if ($data === false) { + throw new \Exception('Unable to parse JSON.'); + } } if ($options['cache-get']) { diff --git a/src/Commands/core/CacheRebuildCommands.php b/src/Commands/core/CacheRebuildCommands.php index 9286cde6bf..7fefe420ae 100644 --- a/src/Commands/core/CacheRebuildCommands.php +++ b/src/Commands/core/CacheRebuildCommands.php @@ -21,8 +21,8 @@ final class CacheRebuildCommands extends DrushCommands const REBUILD = 'cache:rebuild'; public function __construct( - private BootstrapManager $bootstrapManager, - private ClassLoader $autoloader + private readonly BootstrapManager $bootstrapManager, + private readonly ClassLoader $autoloader ) { parent::__construct(); } diff --git a/src/Commands/core/CliCommands.php b/src/Commands/core/CliCommands.php index 122f32213b..c1c85a8527 100644 --- a/src/Commands/core/CliCommands.php +++ b/src/Commands/core/CliCommands.php @@ -4,6 +4,14 @@ namespace Drush\Commands\core; +use Drupal\Core\Entity\ContentEntityInterface; +use Drush\Psysh\Caster; +use Drupal\Core\Field\FieldItemListInterface; +use Drupal\Core\Field\FieldItemInterface; +use Drupal\Core\Config\Entity\ConfigEntityInterface; +use Drupal\Core\Config\ConfigBase; +use Drupal\Component\DependencyInjection\Container; +use Drupal\Component\Render\MarkupInterface; use Drupal\Core\Entity\EntityTypeManagerInterface; use Drush\Attributes as CLI; use Drush\Boot\DrupalBootLevels; @@ -169,13 +177,13 @@ protected function getDrushCommands(): array protected function getCasters(): array { return [ - \Drupal\Core\Entity\ContentEntityInterface::class => \Drush\Psysh\Caster::castContentEntity(...), - \Drupal\Core\Field\FieldItemListInterface::class => \Drush\Psysh\Caster::castFieldItemList(...), - \Drupal\Core\Field\FieldItemInterface::class => \Drush\Psysh\Caster::castFieldItem(...), - \Drupal\Core\Config\Entity\ConfigEntityInterface::class => \Drush\Psysh\Caster::castConfigEntity(...), - \Drupal\Core\Config\ConfigBase::class => \Drush\Psysh\Caster::castConfig(...), - \Drupal\Component\DependencyInjection\Container::class => \Drush\Psysh\Caster::castContainer(...), - \Drupal\Component\Render\MarkupInterface::class => \Drush\Psysh\Caster::castMarkup(...), + ContentEntityInterface::class => Caster::castContentEntity(...), + FieldItemListInterface::class => Caster::castFieldItemList(...), + FieldItemInterface::class => Caster::castFieldItem(...), + ConfigEntityInterface::class => Caster::castConfigEntity(...), + ConfigBase::class => Caster::castConfig(...), + Container::class => Caster::castContainer(...), + MarkupInterface::class => Caster::castMarkup(...), ]; } diff --git a/src/Commands/core/DeployHookCommands.php b/src/Commands/core/DeployHookCommands.php index 7e144dd013..11fb45df8a 100644 --- a/src/Commands/core/DeployHookCommands.php +++ b/src/Commands/core/DeployHookCommands.php @@ -40,7 +40,7 @@ public function __construct( */ public static function getRegistry(): UpdateRegistry { - $registry = new class ( + return new class ( \Drupal::getContainer()->getParameter('app.root'), \Drupal::getContainer()->getParameter('site.path'), \Drupal::service('module_handler')->getModuleList(), @@ -63,8 +63,6 @@ public function __construct( $this->updateType = 'deploy'; } }; - - return $registry; } /** @@ -219,7 +217,7 @@ public static function updateDoOneDeployHook(string $function, array $context): $variables = Error::decodeException($e); $variables = array_filter($variables, function ($key) { - return $key[0] == '@' || $key[0] == '%'; + return $key[0] === '@' || $key[0] === '%'; }, ARRAY_FILTER_USE_KEY); // On windows there is a problem with json encoding a string with backslashes. $variables['%file'] = strtr($variables['%file'], [DIRECTORY_SEPARATOR => '/']); diff --git a/src/Commands/core/DrupalCommands.php b/src/Commands/core/DrupalCommands.php index 1a98484bbe..348b101bd2 100644 --- a/src/Commands/core/DrupalCommands.php +++ b/src/Commands/core/DrupalCommands.php @@ -108,11 +108,11 @@ public function requirements($options = ['format' => 'table', 'severity' => -1, foreach ($requirements as $key => $info) { $severity = array_key_exists('severity', $info) ? $info['severity'] : -1; $rows[$key] = [ - 'title' => self::styleRow((string) $info['title'], $options['format'], $severity), - 'value' => self::styleRow(DrupalUtil::drushRender($info['value'] ?? ''), $options['format'], $severity), - 'description' => self::styleRow(DrupalUtil::drushRender($info['description'] ?? ''), $options['format'], $severity), + 'title' => $this->styleRow((string) $info['title'], $options['format'], $severity), + 'value' => $this->styleRow(DrupalUtil::drushRender($info['value'] ?? ''), $options['format'], $severity), + 'description' => $this->styleRow(DrupalUtil::drushRender($info['description'] ?? ''), $options['format'], $severity), 'sid' => $severity, - 'severity' => self::styleRow(@$severities[$severity], $options['format'], $severity) + 'severity' => $this->styleRow(@$severities[$severity], $options['format'], $severity) ]; if ($severity < $min_severity) { unset($rows[$key]); @@ -171,7 +171,7 @@ public function route($options = ['name' => self::REQ, 'path' => self::REQ, 'for return $items; } - private static function styleRow($content, $format, $severity): ?string + private function styleRow($content, $format, $severity): ?string { if ( !in_array($format, [ diff --git a/src/Commands/core/EditCommands.php b/src/Commands/core/EditCommands.php index 42cbcb26b4..765b8ce7a6 100644 --- a/src/Commands/core/EditCommands.php +++ b/src/Commands/core/EditCommands.php @@ -31,11 +31,9 @@ public function __construct( */ public static function create(ContainerInterface $container, DrushContainer $drush_container): self { - $commandHandler = new static( + return new self( $drush_container->get('site.alias.manager'), ); - - return $commandHandler; } /** @@ -87,14 +85,14 @@ public function load($headers = true): array { $php_header = $rcs_header = $aliases_header = $drupal_header = $bash_header = $drupal = []; $php = $this->phpIniFiles(); - if (!empty($php)) { + if ($php !== []) { if ($headers) { $php_header = ['phpini' => '-- PHP ini files --']; } } $bash = $this->bashFiles(); - if (!empty($bash)) { + if ($bash !== []) { if ($headers) { $bash_header = ['bash' => '-- Bash files --']; } diff --git a/src/Commands/core/EntityCommands.php b/src/Commands/core/EntityCommands.php index 3a35d8f107..cf0c9c54be 100644 --- a/src/Commands/core/EntityCommands.php +++ b/src/Commands/core/EntityCommands.php @@ -49,7 +49,7 @@ public function delete(string $entity_type, $ids = null, array $options = ['bund $result = $query->execute(); // Don't delete uid=1, uid=0. - if ($entity_type == 'user') { + if ($entity_type === 'user') { unset($result[0], $result[1]); } diff --git a/src/Commands/core/EntityCreateCommands.php b/src/Commands/core/EntityCreateCommands.php index 4cf29d8c6d..a8ebbd2991 100644 --- a/src/Commands/core/EntityCreateCommands.php +++ b/src/Commands/core/EntityCreateCommands.php @@ -4,6 +4,7 @@ namespace Drush\Commands\core; +use Drupal\Core\Entity\EntityInterface; use Consolidation\AnnotatedCommand\CommandData; use Consolidation\AnnotatedCommand\Hooks\HookManager; use Consolidation\SiteProcess\Util\Escape; @@ -121,7 +122,7 @@ private function edit($editor, string $path): string /** * Build initial YAML including comments with authoring hints. * - * @param \Drupal\Core\Field\FieldDefinitionInterface[] $instances + * @param FieldDefinitionInterface[] $instances */ private function getInitialYaml(array $instances, ContentEntityInterface $entity, array $options): string { @@ -211,7 +212,7 @@ private function filterViolations(EntityConstraintViolationListInterface &$viola } } - protected function setValue(\Drupal\Core\Entity\EntityInterface $entity, int|string $name, mixed $value): void + protected function setValue(EntityInterface $entity, int|string $name, mixed $value): void { switch ($entity->get($name)->getFieldDefinition()->getType()) { case 'timestamp': diff --git a/src/Commands/core/LanguageCommands.php b/src/Commands/core/LanguageCommands.php index ec044d1cb2..451096b09e 100644 --- a/src/Commands/core/LanguageCommands.php +++ b/src/Commands/core/LanguageCommands.php @@ -50,7 +50,7 @@ public function add($langcode, $options = ['skip-translations' => false]): void $langcodes = array_unique($langcodes); $langcodes = $this->filterValidLangcode($langcodes); $langcodes = $this->filterNewLangcode($langcodes); - if (empty($langcodes)) { + if ($langcodes === []) { return; } diff --git a/src/Commands/core/LocaleCommands.php b/src/Commands/core/LocaleCommands.php index 0a04dbf7b8..b5c16d8627 100644 --- a/src/Commands/core/LocaleCommands.php +++ b/src/Commands/core/LocaleCommands.php @@ -452,7 +452,7 @@ private function convertTypesToPoDbReaderOptions(array $types = []): array 'not_translated' => 'not-translated', ]; - if (empty($types)) { + if ($types === []) { return array_fill_keys(array_keys($valid_convertions), true); } diff --git a/src/Commands/core/MigrateRunnerCommands.php b/src/Commands/core/MigrateRunnerCommands.php index 5df7ccde19..2c9a002084 100644 --- a/src/Commands/core/MigrateRunnerCommands.php +++ b/src/Commands/core/MigrateRunnerCommands.php @@ -4,6 +4,7 @@ namespace Drush\Commands\core; +use Drush\Drupal\Migrate\ValidateMigrationId; use Consolidation\AnnotatedCommand\CommandData; use Consolidation\AnnotatedCommand\CommandError; use Consolidation\AnnotatedCommand\Hooks\HookManager; @@ -472,7 +473,7 @@ public function rollback(?string $migrationIds = null, array $options = ['all' = #[CLI\Argument(name: 'migrationId', description: 'The ID of migration to stop.')] #[CLI\Topics(topics: [DocsCommands::MIGRATE])] #[CLI\ValidateModulesEnabled(modules: ['migrate'])] - #[Migrate\ValidateMigrationId()] + #[ValidateMigrationId()] #[CLI\Version(version: '10.4')] public function stop(string $migrationId): void { @@ -504,7 +505,7 @@ public function stop(string $migrationId): void #[CLI\Argument(name: 'migrationId', description: 'The ID of migration to reset.')] #[CLI\Topics(topics: [DocsCommands::MIGRATE])] #[CLI\ValidateModulesEnabled(modules: ['migrate'])] - #[Migrate\ValidateMigrationId()] + #[ValidateMigrationId()] #[CLI\Version(version: '10.4')] public function resetStatus(string $migrationId): void { @@ -532,7 +533,7 @@ public function resetStatus(string $migrationId): void #[CLI\Usage(name: 'migrate:messages custom_node_revision --idlist=1:"r:1",2:"r:3"', description: 'Show messages related to node revision records with source IDs [1,"r:1"], and [2,"r:3"].')] #[CLI\Topics(topics: [DocsCommands::MIGRATE])] #[CLI\ValidateModulesEnabled(modules: ['migrate'])] - #[Migrate\ValidateMigrationId()] + #[ValidateMigrationId()] #[CLI\FieldLabels(labels: [ 'level' => 'Level', 'source_ids' => 'Source ID(s)', @@ -555,7 +556,7 @@ public function messages(string $migrationId, array $options = ['idlist' => self $idMap = $migration->getIdMap(); $sourceIdKeys = $this->getSourceIdKeys($idMap); $table = []; - if (empty($sourceIdKeys)) { + if ($sourceIdKeys === []) { // Cannot find one item to extract keys from, no need to process // messages on an empty ID map. return new RowsOfFields($table); @@ -631,7 +632,7 @@ protected function preprocessMessageRow(\StdClass $row, array $sourceIdKeys): ar #[CLI\Usage(name: 'migrate:fields-source article', description: 'List fields for the source in the article migration.')] #[CLI\Topics(topics: ['docs:migrate'])] #[CLI\ValidateModulesEnabled(modules: ['migrate'])] - #[Migrate\ValidateMigrationId()] + #[ValidateMigrationId()] #[CLI\FieldLabels(labels: [ 'machine_name' => 'Field name', 'description' => 'Description', diff --git a/src/Commands/core/MkCommands.php b/src/Commands/core/MkCommands.php index 318ea2fcc2..54ce603202 100644 --- a/src/Commands/core/MkCommands.php +++ b/src/Commands/core/MkCommands.php @@ -76,7 +76,7 @@ public function createAnnotatedCommands(Application $application_generate, Appli $annotated->setTopics([DocsCommands::GENERATORS]); $annotated->setHidden($command->isHidden()); $values = []; - if (in_array($command->getName(), ['entity:bundle-class'])) { + if ($command->getName() == 'entity:bundle-class') { $values['version'] = '11.0'; } $annotated->setAnnotationData(new AnnotationData($values)); @@ -167,8 +167,7 @@ protected static function appendOptionsGlobal($application): string $body .= '- ** ' . HelpCLIFormatter::formatOptionKeys(self::optionToArray($value)) . '**. ' . self::cliTextToMarkdown($value->getDescription()) . "\n"; } $body .= '- To see all global options, run drush topic and pick the first choice.' . "\n"; - $body = "#### Global Options\n\n$body\n"; - return $body; + return "#### Global Options\n\n$body\n"; } return ''; } @@ -331,7 +330,7 @@ public function writeContentFilesAndBuildNavAndBuildRedirectMap(array $namespace foreach ($namespaced as $category => $commands) { foreach ($commands as $command) { // Special case a single page - if (empty($pages_all)) { + if ($pages_all === []) { $pages['all'] = $destination . '/all.md'; } @@ -344,14 +343,14 @@ public function writeContentFilesAndBuildNavAndBuildRedirectMap(array $namespace } $body .= self::appendArguments($command); $body .= self::appendOptions($command); - if ($destination == 'commands') { + if ($destination === 'commands') { $body .= self::appendOptionsGlobal($command->getApplication()); } if ($command instanceof AnnotatedCommand) { $body .= self::appendTopics($command, $destination_path); } $body .= self::appendAliases($command); - if ($destination == 'commands') { + if ($destination === 'commands') { $body .= self::appendPostAmble(); } $filename = $this->getFilename($command->getName()); @@ -376,7 +375,7 @@ protected function getRedirectMap(Command $command, string $destination): array $map = []; foreach ($command->getAliases() as $alias) { // Skip trivial aliases that differ by a dash. - if (str_replace([':', '-'], '', $command->getName()) == str_replace([':', '-'], '', $alias)) { + if (str_replace([':', '-'], '', $command->getName()) === str_replace([':', '-'], '', $alias)) { continue; } $map[Path::join($destination, $this->getFilename($alias))] = Path::join($destination, $this->getFilename($command->getName())); diff --git a/src/Commands/core/RunserverCommands.php b/src/Commands/core/RunserverCommands.php index aaeeeec70d..5b455795ab 100644 --- a/src/Commands/core/RunserverCommands.php +++ b/src/Commands/core/RunserverCommands.php @@ -95,7 +95,7 @@ public function uri($uri, $options): array // Populate defaults. $uri = $uri + $user_default + $site_default + $drush_default; - if (ltrim($uri['path'], '/') == '-') { + if (ltrim($uri['path'], '/') === '-') { // Allow a path of a single hyphen to clear a default path. $uri['path'] = ''; } @@ -124,7 +124,7 @@ public function parseUri(?string $uri): array if (empty($uri)) { return []; } - if ($uri[0] == ':') { + if ($uri[0] === ':') { // ':port/path' shorthand, insert a placeholder hostname to allow parsing. $uri = 'placeholder-hostname' . $uri; } @@ -147,7 +147,7 @@ public function parseUri(?string $uri): array unset($uri['path']); } } - if (isset($uri['host']) && $uri['host'] == 'placeholder-hostname') { + if (isset($uri['host']) && $uri['host'] === 'placeholder-hostname') { unset($uri['host']); } return $uri; diff --git a/src/Commands/core/SiteCommands.php b/src/Commands/core/SiteCommands.php index d67b290b38..d129815e24 100644 --- a/src/Commands/core/SiteCommands.php +++ b/src/Commands/core/SiteCommands.php @@ -4,6 +4,7 @@ namespace Drush\Commands\core; +use Symfony\Component\Filesystem\Filesystem; use Consolidation\OutputFormatters\StructuredData\UnstructuredListData; use Consolidation\SiteAlias\SiteAliasManagerInterface; use Drush\Attributes as CLI; @@ -44,7 +45,7 @@ public function siteSet(string $site = '@none'): void $filename = $this->getConfig()->get('runtime.site-file-current'); if ($filename) { $last_site_filename = $this->getConfig()->get('runtime.site-file-previous'); - if ($site == '-') { + if ($site === '-') { if (file_exists($last_site_filename)) { $site = file_get_contents($last_site_filename); } else { @@ -64,7 +65,7 @@ public function siteSet(string $site = '@none'): void } // Using 'site:set @self' is quiet if there is no change. $current = is_file($filename) ? trim(file_get_contents($filename)) : "@none"; - if ($current == $site) { + if ($current === $site) { return; } } @@ -76,7 +77,7 @@ public function siteSet(string $site = '@none'): void @rename($filename, $last_site_filename); } $success_message = dt('Site set to @site', ['@site' => $site]); - $fs = new \Symfony\Component\Filesystem\Filesystem(); + $fs = new Filesystem(); if ($site == '@none' || $site == '') { $fs->remove($filename); $this->logger()->success(dt('Site unset.')); @@ -107,7 +108,7 @@ public function siteAlias($site = null, array $options = ['format' => 'yaml']): // First check to see if the user provided a specification that matches // multiple sites. $aliasList = $this->siteAliasManager->getMultiple($site); - if (is_array($aliasList) && !empty($aliasList)) { + if (is_array($aliasList) && $aliasList !== []) { return new UnstructuredListData($this->siteAliasExportList($aliasList, $options)); } @@ -127,12 +128,11 @@ public function siteAlias($site = null, array $options = ['format' => 'yaml']): protected function siteAliasExportList(array $aliasList, $options): array { - $result = array_map( + return array_map( function ($aliasRecord) { return $aliasRecord->export(); }, $aliasList ); - return $result; } } diff --git a/src/Commands/core/SiteInstallCommands.php b/src/Commands/core/SiteInstallCommands.php index 941b19402c..ac1f5fa8eb 100644 --- a/src/Commands/core/SiteInstallCommands.php +++ b/src/Commands/core/SiteInstallCommands.php @@ -27,6 +27,7 @@ use Drush\Utils\StringUtils; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; +use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\Filesystem\Path; #[CLI\Bootstrap(DrupalBootLevels::NONE)] @@ -38,9 +39,9 @@ final class SiteInstallCommands extends DrushCommands const INSTALL = 'site:install'; public function __construct( - private BootstrapManager $bootstrapManager, - private SiteAliasManagerInterface $siteAliasManager, - private ClassLoader $autoloader + private readonly BootstrapManager $bootstrapManager, + private readonly SiteAliasManagerInterface $siteAliasManager, + private readonly ClassLoader $autoloader ) { parent::__construct(); } @@ -81,8 +82,8 @@ public function install(array $profile, $options = ['db-url' => self::REQ, 'db-p // Allow for numeric and NULL values to be passed in. if (is_numeric($value)) { - $value = intval($value); - } elseif ($value == 'NULL') { + $value = (int) $value; + } elseif ($value === 'NULL') { $value = null; } @@ -164,7 +165,7 @@ public function install(array $profile, $options = ['db-url' => self::REQ, 'db-p throw new InstallerException(MailFormatHelper::htmlToText($e->getMessage()), $e->getTitle(), $e->getCode(), ($this->output()->getVerbosity() > OutputInterface::VERBOSITY_NORMAL) ? $e : null); } catch (AlreadyInstalledException $e) { if ($sql && !$this->programExists($sql->command())) { - throw new \Exception(dt('Drush was unable to drop all tables because `@program` was not found, and therefore Drupal threw an AlreadyInstalledException. Ensure `@program` is available in your PATH.', ['@program' => $sql->command()])); + throw new \Exception(dt('Drush was unable to drop all tables because `@program` was not found, and therefore Drupal threw an AlreadyInstalledException. Ensure `@program` is available in your PATH.', ['@program' => $sql->command()]), $e->getCode(), $e); } throw $e; } @@ -349,7 +350,7 @@ public function validate(CommandData $commandData): void // provided credential values. SqlBase::create($commandData->input()->getOptions()); } catch (\Exception $e) { - throw new \Exception(dt('Could not determine database connection parameters. Pass --db-url option.')); + throw new \Exception(dt('Could not determine database connection parameters. Pass --db-url option.'), $e->getCode(), $e); } } } @@ -389,7 +390,7 @@ public function pre(CommandData $commandData): void $settingsfile = Path::join($confPath, 'settings.php'); $sitesfile = "sites/sites.php"; $default = realpath(Path::join($root, 'sites/default')); - $sitesfile_write = realpath($confPath) != $default && !file_exists($sitesfile); + $sitesfile_write = realpath($confPath) !== $default && !file_exists($sitesfile); $msg = []; if (!file_exists($settingsfile)) { @@ -421,7 +422,7 @@ public function pre(CommandData $commandData): void // Can't install without sites subdirectory and settings.php. if (!file_exists($confPath)) { - if ((new \Symfony\Component\Filesystem\Filesystem())->mkdir($confPath) && !$this->config->simulate()) { + if ((new Filesystem())->mkdir($confPath) && !$this->config->simulate()) { throw new \Exception(dt('Failed to create directory @confPath', ['@confPath' => $confPath])); } } else { @@ -472,8 +473,7 @@ protected function getSitesSubdirFromUri($root, $uri) if (file_exists($sites_file)) { $sites = []; include $sites_file; - // @phpstan-ignore-next-line - if (!empty($sites) && array_key_exists($uri, $sites)) { + if ($sites !== [] && array_key_exists($uri, $sites)) { return $sites[$uri]; } } diff --git a/src/Commands/core/SshCommands.php b/src/Commands/core/SshCommands.php index 628f33810f..de7a92c3ca 100644 --- a/src/Commands/core/SshCommands.php +++ b/src/Commands/core/SshCommands.php @@ -42,7 +42,7 @@ public function ssh(array $code, $options = ['cd' => self::REQ]): void { $alias = $this->siteAliasManager->getSelf(); - if (empty($code)) { + if ($code === []) { $code[] = 'bash'; $code[] = '-l'; diff --git a/src/Commands/core/StateCommands.php b/src/Commands/core/StateCommands.php index 011bbc5df5..30da7504a3 100644 --- a/src/Commands/core/StateCommands.php +++ b/src/Commands/core/StateCommands.php @@ -102,7 +102,7 @@ public function delete(string $key): void */ public static function format(mixed $value, string $format): mixed { - if ($format == 'auto') { + if ($format === 'auto') { if (is_numeric($value)) { $value += 0; // http://php.net/manual/en/function.is-numeric.php#107326 $format = gettype($value); diff --git a/src/Commands/core/StatusCommands.php b/src/Commands/core/StatusCommands.php index 8e2897f01f..4c7f8aee28 100644 --- a/src/Commands/core/StatusCommands.php +++ b/src/Commands/core/StatusCommands.php @@ -39,11 +39,9 @@ public function __construct( */ public static function createEarly(DrushContainer $drush_container): self { - $commandHandler = new static( + return new self( $drush_container->get('site.alias.manager'), ); - - return $commandHandler; } /** @@ -168,7 +166,7 @@ public function getPropertyList($options): array $status_table['alias-searchpaths'] = array_map([Path::class, 'canonicalize'], $alias_searchpaths); $paths = self::pathAliases($options, $boot_manager, $boot_object); - if (!empty($paths)) { + if ($paths !== []) { foreach ($paths as $target => $one_path) { $name = $target; if (str_starts_with($name, '%')) { diff --git a/src/Commands/core/TopicCommands.php b/src/Commands/core/TopicCommands.php index 290a671766..ad2de0278a 100644 --- a/src/Commands/core/TopicCommands.php +++ b/src/Commands/core/TopicCommands.php @@ -69,7 +69,7 @@ public function interact(InputInterface $input, OutputInterface $output): void public function validate(CommandData $commandData): void { $topic_name = $commandData->input()->getArgument('topic_name'); - if (!in_array($topic_name, array_keys(self::getAllTopics()))) { + if (!array_key_exists($topic_name, self::getAllTopics())) { throw new \Exception(dt("!topic topic not found.", ['!topic' => $topic_name])); } } diff --git a/src/Commands/core/TwigCommands.php b/src/Commands/core/TwigCommands.php index cd91812c4f..daa2a61790 100644 --- a/src/Commands/core/TwigCommands.php +++ b/src/Commands/core/TwigCommands.php @@ -30,9 +30,9 @@ final class TwigCommands extends DrushCommands public function __construct( protected TwigEnvironment $twig, protected ModuleHandlerInterface $moduleHandler, - private ModuleExtensionList $extensionList, - private StateInterface $state, - private DrupalKernelInterface $kernel + private readonly ModuleExtensionList $extensionList, + private readonly StateInterface $state, + private readonly DrupalKernelInterface $kernel ) { } diff --git a/src/Commands/core/UpdateDBCommands.php b/src/Commands/core/UpdateDBCommands.php index fc050a1e87..1d0d635047 100644 --- a/src/Commands/core/UpdateDBCommands.php +++ b/src/Commands/core/UpdateDBCommands.php @@ -4,6 +4,7 @@ namespace Drush\Commands\core; +use Drupal\Core\Update\UpdateRegistry; use Consolidation\OutputFormatters\StructuredData\RowsOfFields; use Consolidation\OutputFormatters\StructuredData\UnstructuredListData; use Consolidation\SiteAlias\SiteAliasManagerInterface; @@ -361,7 +362,7 @@ public function updateBatch(): bool // potentially very large.) $dependency_map = []; foreach ($updates as $function => $update) { - $dependency_map[$function] = !empty($update['reverse_paths']) ? array_keys($update['reverse_paths']) : []; + $dependency_map[$function] = empty($update['reverse_paths']) ? [] : array_keys($update['reverse_paths']); } $operations = []; @@ -516,7 +517,7 @@ public function getUpdatedbStatus(array $options): array } // Pending hook_post_update_X() implementations. - /** @var \Drupal\Core\Update\UpdateRegistry $post_update_registry */ + /** @var UpdateRegistry $post_update_registry */ $post_update_registry = \Drupal::service('update.post_update_registry'); $post_updates = $post_update_registry->getPendingUpdateInformation(); foreach ($post_updates as $module => $post_update) { diff --git a/src/Commands/core/UserCommands.php b/src/Commands/core/UserCommands.php index c6fdf45c21..bf9fbddaea 100644 --- a/src/Commands/core/UserCommands.php +++ b/src/Commands/core/UserCommands.php @@ -97,7 +97,7 @@ public function information(string $names = '', $options = ['format' => 'table', } } } - if (empty($accounts)) { + if ($accounts === []) { throw new \Exception(dt('Unable to find a matching user')); } @@ -376,7 +376,7 @@ protected function getAccounts(string $names = '', array $options = []): array } } } - if (empty($accounts)) { + if ($accounts === []) { throw new \Exception(dt('Unable to find any matching user')); } diff --git a/src/Commands/core/ViewsCommands.php b/src/Commands/core/ViewsCommands.php index 79b10b8a85..4545bc91c0 100644 --- a/src/Commands/core/ViewsCommands.php +++ b/src/Commands/core/ViewsCommands.php @@ -127,11 +127,11 @@ public function vlist($options = ['name' => self::REQ, 'tags' => self::REQ, 'sta // Get the --name option. $name = StringUtils::csvToArray($options['name']); - $with_name = !empty($name); + $with_name = $name !== []; // Get the --tags option. $tags = StringUtils::csvToArray($options['tags']); - $with_tags = !empty($tags); + $with_tags = $tags !== []; // Get the --status option. Store user input apart to reuse it after. $status = $options['status']; diff --git a/src/Commands/field/FieldCreateCommands.php b/src/Commands/field/FieldCreateCommands.php index 598eea19c3..c0816128f6 100644 --- a/src/Commands/field/FieldCreateCommands.php +++ b/src/Commands/field/FieldCreateCommands.php @@ -260,7 +260,7 @@ protected function askExistingFieldName(): ?string $showMachineNames = (bool) $this->input->getOption('show-machine-names'); $choices = $this->getExistingFieldStorageOptions($entityType, $bundle, $showMachineNames); - if (empty($choices)) { + if ($choices === []) { return null; } diff --git a/src/Commands/field/FieldDefinitionCommands.php b/src/Commands/field/FieldDefinitionCommands.php index 733bd2b652..7860922f18 100644 --- a/src/Commands/field/FieldDefinitionCommands.php +++ b/src/Commands/field/FieldDefinitionCommands.php @@ -97,7 +97,7 @@ public function widgets(array $options = ['format' => 'yaml', 'field-type' => se ]; $definitions = \array_map($processor, $this->widgetPluginManager->getDefinitions()); if ($options['field-type']) { - $definitions = self::filterByFieldType($definitions, $options['field-type']); + $definitions = $this->filterByFieldType($definitions, $options['field-type']); } return new UnstructuredListData($definitions); } @@ -136,7 +136,7 @@ public function formatters(array $options = ['format' => 'yaml', 'field-type' => ]; $definitions = \array_map($processor, $this->formatterPluginManager->getDefinitions()); if ($options['field-type']) { - $definitions = self::filterByFieldType($definitions, $options['field-type']); + $definitions = $this->filterByFieldType($definitions, $options['field-type']); } return new UnstructuredListData($definitions); } @@ -154,7 +154,7 @@ public function complete(CompletionInput $input, CompletionSuggestions $suggesti /** * Filters definitions by applicable field types. */ - private static function filterByFieldType(array $definitions, string $search): array + private function filterByFieldType(array $definitions, string $search): array { $match = static fn(string $field_type): bool => \str_contains($field_type, $search); $total_matches = static fn(array $field_types): int => \count(\array_filter($field_types, $match)); diff --git a/src/Commands/generate/ApplicationFactory.php b/src/Commands/generate/ApplicationFactory.php index c98faa0348..0649da1b11 100644 --- a/src/Commands/generate/ApplicationFactory.php +++ b/src/Commands/generate/ApplicationFactory.php @@ -15,12 +15,12 @@ class ApplicationFactory { - private ServiceManager $serviceManager; - private \Symfony\Component\DependencyInjection\ContainerInterface $container; + private readonly ServiceManager $serviceManager; + private readonly \Symfony\Component\DependencyInjection\ContainerInterface $container; public function __construct( - private DrushContainer $drush_container, - private LoggerInterface $logger + private readonly DrushContainer $drush_container, + private readonly LoggerInterface $logger ) { $this->serviceManager = $this->drush_container->get('service.manager'); $this->container = $this->drush_container->get('service_container'); @@ -60,15 +60,13 @@ public function discover(): array $global_generator_classes = $this->serviceManager->discoverPsr4Generators(); $global_generator_classes = $this->filterClassExists($global_generator_classes); $global_generators = $this->serviceManager->instantiateServices($global_generator_classes, $this->drush_container, $this->container); - - $generators = [ + return [ new DrushCommandFile(), new DrushAliasFile(), new DrushGeneratorFile(), ...$global_generators, ...$module_generators, ]; - return $generators; } /** diff --git a/src/Commands/generate/GenerateCommands.php b/src/Commands/generate/GenerateCommands.php index ecd38b4543..a4ec90fae0 100644 --- a/src/Commands/generate/GenerateCommands.php +++ b/src/Commands/generate/GenerateCommands.php @@ -20,19 +20,17 @@ final class GenerateCommands extends DrushCommands const GENERATE = 'generate'; protected function __construct( - private ContainerInterface $container, - private DrushContainer $drush_container, + private readonly DrushContainer $container, + private readonly DrushContainer $drush_container, ) { } - public static function create(ContainerInterface $container): self + public static function create(DrushContainer $container): self { - $commandHandler = new static( + return new self( $container->get('service_container'), $container, ); - - return $commandHandler; } /** @@ -59,7 +57,7 @@ public function generate(string $generator = '', $options = ['replace' => false, { $application = (new ApplicationFactory($this->drush_container, $this->logger()))->create(); - if (!$generator || $generator == 'list') { + if (!$generator || $generator === 'list') { $all = $application->all(); unset($all['help'], $all['list'], $all['completion']); $namespaced = ListCommands::categorize($all); diff --git a/src/Commands/pm/PmCommands.php b/src/Commands/pm/PmCommands.php index 4a5730af00..4831930d96 100644 --- a/src/Commands/pm/PmCommands.php +++ b/src/Commands/pm/PmCommands.php @@ -74,7 +74,7 @@ public function install(array $modules): void $modules = StringUtils::csvToArray($modules); $todo = $this->addInstallDependencies($modules); $todo_str = ['!list' => implode(', ', $todo)]; - if (empty($todo)) { + if ($todo === []) { $this->logger()->notice(dt('Already enabled: !list', ['!list' => implode(', ', $modules)])); return; } elseif (Drush::simulate()) { @@ -106,7 +106,7 @@ public function validateEnableModules(CommandData $commandData): void $modules = $commandData->input()->getArgument('modules'); $modules = StringUtils::csvToArray($modules); $modules = $this->addInstallDependencies($modules); - if (empty($modules)) { + if ($modules === []) { return; } @@ -267,7 +267,7 @@ public function pmList($options = ['format' => 'table', 'type' => 'module,theme' } // Filter by package. - if (!empty($package_filter)) { + if ($package_filter !== []) { if (!in_array(strtolower($extension->info['package']), $package_filter)) { unset($modules[$key]); continue; diff --git a/src/Commands/sql/sanitize/SanitizeUserFieldsCommands.php b/src/Commands/sql/sanitize/SanitizeUserFieldsCommands.php index 7945db3e72..b858e62154 100644 --- a/src/Commands/sql/sanitize/SanitizeUserFieldsCommands.php +++ b/src/Commands/sql/sanitize/SanitizeUserFieldsCommands.php @@ -4,6 +4,7 @@ namespace Drush\Commands\sql\sanitize; +use Drupal\Core\Database\Connection; use Consolidation\AnnotatedCommand\CommandData; use Consolidation\AnnotatedCommand\Hooks\HookManager; use Drupal\Core\Entity\EntityFieldManagerInterface; @@ -21,7 +22,7 @@ final class SanitizeUserFieldsCommands extends DrushCommands implements Sanitize use AutowireTrait; public function __construct( - protected \Drupal\Core\Database\Connection $database, + protected Connection $database, protected EntityFieldManagerInterface $entityFieldManager, protected EntityTypeManagerInterface $entityTypeManager ) { diff --git a/src/Commands/sql/sanitize/SanitizeUserTableCommands.php b/src/Commands/sql/sanitize/SanitizeUserTableCommands.php index 87f84ce992..bd2a18fef4 100644 --- a/src/Commands/sql/sanitize/SanitizeUserTableCommands.php +++ b/src/Commands/sql/sanitize/SanitizeUserTableCommands.php @@ -4,6 +4,8 @@ namespace Drush\Commands\sql\sanitize; +use Drupal\Core\Database\Connection; +use Drupal\Core\Database\Query\SelectInterface; use Consolidation\AnnotatedCommand\CommandData; use Consolidation\AnnotatedCommand\Hooks\HookManager; use Drupal\Core\Entity\EntityTypeManagerInterface; @@ -23,7 +25,7 @@ final class SanitizeUserTableCommands extends DrushCommands implements SanitizeP use AutowireTrait; public function __construct( - protected \Drupal\Core\Database\Connection $database, + protected Connection $database, protected PasswordInterface $passwordHasher, protected EntityTypeManagerInterface $entityTypeManager ) { @@ -60,10 +62,10 @@ public function sanitize($result, CommandData $commandData): void // We need a different sanitization query for MSSQL, Postgres and Mysql. $sql = SqlBase::create($commandData->input()->getOptions()); $db_driver = $sql->scheme(); - if ($db_driver == 'pgsql') { + if ($db_driver === 'pgsql') { $email_map = ['%uid' => "' || uid || '", '%mail' => "' || replace(mail, '@', '_') || '", '%name' => "' || replace(name, ' ', '_') || '"]; $new_mail = "'" . str_replace(array_keys($email_map), array_values($email_map), $options['sanitize-email']) . "'"; - } elseif ($db_driver == 'mssql') { + } elseif ($db_driver === 'mssql') { $email_map = ['%uid' => "' + uid + '", '%mail' => "' + replace(mail, '@', '_') + '", '%name' => "' + replace(name, ' ', '_') + '"]; $new_mail = "'" . str_replace(array_keys($email_map), array_values($email_map), $options['sanitize-email']) . "'"; } else { @@ -80,7 +82,7 @@ public function sanitize($result, CommandData $commandData): void if (!empty($options['ignored-roles'])) { $roles = explode(',', $options['ignored-roles']); - /** @var \Drupal\Core\Database\Query\SelectInterface $roles_query */ + /** @var SelectInterface $roles_query */ $roles_query = $this->database->select('user__roles', 'ur'); $roles_query ->condition('roles_target_id', $roles, 'IN') diff --git a/src/Config/Environment.php b/src/Config/Environment.php index 378aa0d685..4dfb3b749e 100644 --- a/src/Config/Environment.php +++ b/src/Config/Environment.php @@ -17,8 +17,8 @@ class Environment { protected string $homeDir; protected string $originalCwd; - protected string $etcPrefix; - protected string $sharePrefix; + protected string $etcPrefix = ''; + protected string $sharePrefix = ''; protected string $drushBasePath; protected string $vendorDir; @@ -38,8 +38,6 @@ public function __construct(string $homeDir, string $cwd, string $autoloadFile) { $this->homeDir = $homeDir; $this->originalCwd = Path::canonicalize(FsUtils::realpath($cwd)); - $this->etcPrefix = ''; - $this->sharePrefix = ''; $this->drushBasePath = Path::canonicalize(dirname(__DIR__, 2)); $this->vendorDir = FsUtils::realpath(dirname($autoloadFile)); } diff --git a/src/Drupal/Migrate/MigrateExecutable.php b/src/Drupal/Migrate/MigrateExecutable.php index 616a39a669..4ab5c53048 100644 --- a/src/Drupal/Migrate/MigrateExecutable.php +++ b/src/Drupal/Migrate/MigrateExecutable.php @@ -145,7 +145,7 @@ public function __construct(MigrationInterface $migration, MigrateMessageInterfa // - `--idlist` option is used, // - `--limit` option is used, // - The migration source plugin has high_water_property set. - $this->deleteMissingSourceRows = $options['delete'] && !($this->limit || !empty($this->idlist) || !empty($migration->getSourceConfiguration()['high_water_property'])); + $this->deleteMissingSourceRows = $options['delete'] && !($this->limit || $this->idlist !== [] || !empty($migration->getSourceConfiguration()['high_water_property'])); // Cannot use the progress bar when: // - `--no-progress` option is used, // - `--feedback` option is used, @@ -464,7 +464,7 @@ public function onPrepareRow(MigratePrepareRowEvent $event): void $row = $event->getRow(); $sourceId = $row->getSourceIdValues(); - if (!empty($this->idlist)) { + if ($this->idlist !== []) { $skip = true; foreach ($this->idlist as $id) { if (array_values($sourceId) == $id) { diff --git a/src/DrupalFinder/DrushDrupalFinder.php b/src/DrupalFinder/DrushDrupalFinder.php index f67544e935..80d119e7c5 100644 --- a/src/DrupalFinder/DrushDrupalFinder.php +++ b/src/DrupalFinder/DrushDrupalFinder.php @@ -11,7 +11,7 @@ */ class DrushDrupalFinder { - public function __construct(private Environment $environment) + public function __construct(private readonly Environment $environment) { } diff --git a/src/Drush.php b/src/Drush.php index 14a4938c0e..ec1a425c6f 100644 --- a/src/Drush.php +++ b/src/Drush.php @@ -4,6 +4,7 @@ namespace Drush; +use Psr\Container\ContainerInterface; use Composer\InstalledVersions; use Consolidation\AnnotatedCommand\AnnotatedCommandFactory; use Consolidation\SiteAlias\SiteAliasInterface; @@ -140,7 +141,7 @@ public static function unsetContainer(): void * * @throws RuntimeException */ - public static function getContainer(): \Psr\Container\ContainerInterface + public static function getContainer(): ContainerInterface { if (!Robo::hasContainer()) { throw new RuntimeException('Drush::$container is not initialized yet. \Drush::setContainer() must be called with a real container.'); @@ -342,9 +343,6 @@ public static function siteProcess(SiteAliasInterface $siteAlias, array $args = * @param array|null $env The environment variables or null to use the same environment as the current PHP process * @param mixed|null $input The input as stream resource, scalar or \Traversable, or null for no input * @param int|float|null $timeout The timeout in seconds or null to disable - * - * @return - * A wrapper around Symfony Process. */ public static function process($commandline, $cwd = null, $env = null, $input = null, $timeout = 60): ProcessBase { diff --git a/src/Log/DrushLog.php b/src/Log/DrushLog.php index 322af94ddc..cf7dc87f15 100644 --- a/src/Log/DrushLog.php +++ b/src/Log/DrushLog.php @@ -75,7 +75,7 @@ public function log($level, $message, array $context = []): void return is_scalar($element) || is_callable([$element, '__toString']); }); - $message = empty($message_placeholders) ? $message : strtr($message, $message_placeholders); + $message = $message_placeholders === [] ? $message : strtr($message, $message_placeholders); Drush::logger()->log($error_type, $message, $context); } diff --git a/src/Preflight/ArgsPreprocessor.php b/src/Preflight/ArgsPreprocessor.php index 15831719d0..e71fd346fc 100644 --- a/src/Preflight/ArgsPreprocessor.php +++ b/src/Preflight/ArgsPreprocessor.php @@ -131,7 +131,7 @@ protected function isAliasOrSiteSpec(string $arg): bool protected function findMethodForOptionWithValues(array $optionsTable, string $opt): array { // Skip $opt if it is empty, or if it is not an option. - if (empty($opt) || ($opt[0] != '-')) { + if (empty($opt) || ($opt[0] !== '-')) { return [false, false, false]; } @@ -163,8 +163,8 @@ protected function checkMatchingOption(string $opt, string $keyParam, string $me // Test to see if $key ends in '='; remove the character if present. // If the char is removed, it means the option accepts a value. $key = rtrim($keyParam, '=~'); - $acceptsValue = $key != $keyParam; - $acceptsValueFromNextArg = $keyParam[strlen($keyParam) - 1] != '~'; + $acceptsValue = $key !== $keyParam; + $acceptsValueFromNextArg = $keyParam[strlen($keyParam) - 1] !== '~'; // If $opt does not begin with $key, then it cannot be a match. if (!str_starts_with($opt, $key)) { @@ -183,7 +183,7 @@ protected function checkMatchingOption(string $opt, string $keyParam, string $me // If the option is not an exact match for the key, then the next // character in the option after the key name must be an '='. Otherwise, // we might confuse `--locale` for `--local`, etc. - if ($opt[strlen($key)] != '=') { + if ($opt[strlen($key)] !== '=') { return [false, false, false]; } @@ -198,7 +198,7 @@ protected function checkMatchingOption(string $opt, string $keyParam, string $me // If $opt is a double-dash option, and it contains an '=', then // the option value is everything after the '='. - if ((strlen($key) < strlen($opt)) && ($opt[1] == '-') && ($opt[strlen($key)] == '=')) { + if ((strlen($key) < strlen($opt)) && ($opt[1] === '-') && ($opt[strlen($key)] === '=')) { $value = substr($opt, strlen($key) + 1); return [$methodName, $value, false]; } diff --git a/src/Preflight/ArgsRemapper.php b/src/Preflight/ArgsRemapper.php index 41fd60980b..16b5db04e8 100644 --- a/src/Preflight/ArgsRemapper.php +++ b/src/Preflight/ArgsRemapper.php @@ -90,6 +90,6 @@ protected function matches(string $arg, string $candidate): bool return true; } - return $arg[strlen($candidate)] == '='; + return $arg[strlen($candidate)] === '='; } } diff --git a/src/Preflight/PreflightVerify.php b/src/Preflight/PreflightVerify.php index 8591e7b164..6ca77396c3 100644 --- a/src/Preflight/PreflightVerify.php +++ b/src/Preflight/PreflightVerify.php @@ -77,7 +77,7 @@ protected function checkPhpIni(): void $prohibited_list[] = $prohibited_mode; } } - if (!empty($prohibited_list)) { + if ($prohibited_list !== []) { throw new \Exception(StringUtils::interpolate('The following restricted PHP modes have non-empty values: {prohibited_list}. This configuration is incompatible with drush. {php_ini_msg}', ['prohibited_list' => implode(' and ', $prohibited_list), 'php_ini_msg' => $this->loadedPhpIniMessage()])); } } diff --git a/src/Psysh/DrushCommand.php b/src/Psysh/DrushCommand.php index 7248094f54..ca189ada9f 100644 --- a/src/Psysh/DrushCommand.php +++ b/src/Psysh/DrushCommand.php @@ -117,7 +117,7 @@ protected function buildHelpFromCommand(): string } } - if (!empty($examples)) { + if ($examples !== []) { $help .= "\n\ne.g."; foreach ($examples as $ex => $def) { diff --git a/src/Psysh/DrushHelpCommand.php b/src/Psysh/DrushHelpCommand.php index 3c4251356e..ab0a9e8fd9 100644 --- a/src/Psysh/DrushHelpCommand.php +++ b/src/Psysh/DrushHelpCommand.php @@ -77,7 +77,7 @@ protected function execute(InputInterface $input, OutputInterface $output): void // Find the alignment width. $width = 0; foreach ($commands as $command) { - $width = strlen($command->getName()) > $width ? strlen($command->getName()) : $width; + $width = max(strlen($command->getName()), $width); } $width += 2; diff --git a/src/Runtime/LegacyServiceInstantiator.php b/src/Runtime/LegacyServiceInstantiator.php index b3aa6eacba..b62817fc03 100644 --- a/src/Runtime/LegacyServiceInstantiator.php +++ b/src/Runtime/LegacyServiceInstantiator.php @@ -80,14 +80,9 @@ protected function isValidServiceData(string $serviceFile, array $serviceFileDat $this->logger->info(dt('Autowire not supported; skipping @file', ['@file' => $serviceFile])); return false; } - // Every entry in services must have a 'class' entry - if (!$this->allServicesHaveClassElement($serviceFile, $serviceFileData['services'])) { - return false; - } - // If we didn't find anything wrong, then assume it's probably okay - return true; + return $this->allServicesHaveClassElement($serviceFile, $serviceFileData['services']); } /** @@ -241,7 +236,7 @@ protected function resolveArgument($arg) // Instantiate references to services, either in the // Drupal container, or other services created earlier by // some drush.services.yml file. - if ($arg[0] == '@') { + if ($arg[0] === '@') { // Check to see if a previous drush.services.yml instantiated // this service; return any service found. $drushServiceName = ltrim(substr($arg, 1), '?'); @@ -301,7 +296,7 @@ protected function resolveFromContainer($container, string $arg) */ protected function isRequired(string $arg) { - if ($arg[0] == '?') { + if ($arg[0] === '?') { return [false, substr($arg, 1)]; } diff --git a/src/Sql/SqlPgsql.php b/src/Sql/SqlPgsql.php index da1f91d356..7b57d27ea4 100644 --- a/src/Sql/SqlPgsql.php +++ b/src/Sql/SqlPgsql.php @@ -129,7 +129,7 @@ public function dbExists(): bool public function queryFormat($query) { - if (strtolower($query) == 'show tables;') { + if (strtolower($query) === 'show tables;') { return PSQL_SHOW_TABLES; } return $query; diff --git a/src/Sql/SqlTableSelectionTrait.php b/src/Sql/SqlTableSelectionTrait.php index 3db10291fb..d14c9eca24 100644 --- a/src/Sql/SqlTableSelectionTrait.php +++ b/src/Sql/SqlTableSelectionTrait.php @@ -18,7 +18,7 @@ trait SqlTableSelectionTrait * @param array $options An options array as passed to an Annotated Command. * @param array $all_tables A list of all eligible tables. * - * @return + * @return array * An array of tables with each table name in the appropriate * element of the array. */ @@ -48,8 +48,8 @@ public function getExpandedTableSelection(array $options, array $all_tables): ar * `*` wildcard character. * @param $db_tables * The list of tables present in a database. - * @return - * An array of tables with non-existant tables removed. + * @return array + * An array of tables with non-existent tables removed. */ public function expandAndFilterTables(array $tables, array $db_tables): array { @@ -67,7 +67,7 @@ public function expandAndFilterTables(array $tables, array $db_tables): array * An array of table names, some of which may contain wildcards (`*`). * @param array $db_tables * An array with all the existing table names in the current database. - * @return + * @return array * $tables array with wildcards resolved to real table names. */ public function expandWildcardTables(array $tables, array $db_tables): array @@ -93,7 +93,7 @@ public function expandWildcardTables(array $tables, array $db_tables): array * An array of table names to filter. * @param $db_tables * An array with all the existing table names in the current database. - * @return + * @return array * An array with only valid table names (i.e. all of which actually exist in * the database). */ @@ -118,7 +118,7 @@ public function filterTables(array $tables, array $db_tables): array * - structure: tables to only have their structure i.e. DDL dumped * - tables: tables to have structure and data dumped * - * @return + * @return array * An array of table names with each table name in the appropriate * element of the array. */ @@ -137,11 +137,11 @@ public function getTableSelection(array $options): array /** * Consult the specified options and return the list of tables specified. * - * @param option_name + * @param $option_name * The option name to check: skip-tables, structure-tables * or tables. This function will check both *-key and *-list. * @param $options An options array as passed to an Annotated Command. - * @return + * @return array * Returns an array of tables based on the first option * found, or an empty array if there were no matches. */ @@ -153,7 +153,7 @@ public function getRawTableList(string $option_name, array $options): array if (array_key_exists($key, $all_tables)) { return $all_tables[$key]; } - if ($option_name != 'tables') { + if ($option_name !== 'tables') { $all_tables = $this->getConfig()->get('sql.tables', []); if (array_key_exists($key, $all_tables)) { return $all_tables[$key]; diff --git a/src/Utils/StringUtils.php b/src/Utils/StringUtils.php index d40638b151..5a5a4a7438 100644 --- a/src/Utils/StringUtils.php +++ b/src/Utils/StringUtils.php @@ -44,7 +44,7 @@ public static function csvToArray($args): array public static function interpolate(string $message, array $context = []): string { // Take no action if there is no context - if (empty($context)) { + if ($context === []) { return $message; }