Drupal 10.2 and Drush

Components

If you encounter any of these errors and you are using Drupal 10.2:

[preflight] Class "Drush\Commands\PolicyCommands" does not exist
[warning] Drush command terminated abnormally.

or

PHP Fatal error:  Uncaught Error: Class "Commands\DrushCommands" not found in /drush/Commands/PolicyCommands.php:10

then you need to modify your PolicyCommands file because it probably does not have the correct namespace. This file is usually located at: drush/Commands/PolicyCommands.php

Check if the class has a namespace and if it is correct. The namespace should be: 

namespace Drush\Commands;

so the entire file, with a single policy that forbids overwriting non-local databases, might look like this:

<?php

namespace Drush\Commands;

use Consolidation\AnnotatedCommand\CommandData;
use Consolidation\AnnotatedCommand\Hooks\HookManager;
use Drush\Attributes as CLI;
use Drush\Commands\sql\SqlSyncCommands;

class PolicyCommands extends DrushCommands {

  /**
   * Prevent catastrophic braino. Note that this file has to be local to the
   * machine that initiates the sql:sync command.
   *
   * @throws \Exception
   */
  #[CLI\Hook(type: HookManager::ARGUMENT_VALIDATOR, target: SqlSyncCommands::SYNC)]
  public function sqlSyncValidate(CommandData $commandData)
  {
    if ($commandData->input()->getArgument('target') !== '@self') {
      throw new \Exception(dt('Per !file, you may never overwrite the non-local database.', ['!file' => __FILE__]));
    }
  }

}

Although the official Drush documentation shows that the argument is called destination, it is actually called target.

Another thing I would like to draw attention to is if you see this error:

In ProcessBase.php line 171:
                
  Unable to decode output into JSON: Syntax error                                                                                                                                               
  TypeError: ArrayObject::__construct(): Argument #1 ($array) must be of type array, bool given in ArrayObject->__construct() (line 15 of vendor/consolidation/output-formatters/src/StructuredData/AbstractListData.php)

This probably means that you are using an old version of Drush in combination with Drupal 10.2. The solution is to install at least Drush version 12.4.3.

Please note that the Drush launcher has been archived and does not work with Drush 12. You should use one of the alternative solutions.

About the Author

Goran Nikolovski is a web and AI developer with over 10 years of expertise in PHP, Drupal, Python, JavaScript, React, and React Native. He founded this website and enjoys sharing his knowledge.