Writing Drush commands with PHP attributes

<?php declare(strict_types=1);

namespace App\Drush\Commands;

use Drush\Attributes as CLI;
use Drush\Commands\DrushCommands;

final class AppDrushCommands extends DrushCommands {

/*
* @command app:hello-world
* @aliases hello-world
*/
public function helloWorld(): void {
$this->io()->writeln('<info>Hello world!</info>');
}

}
<?php declare(strict_types=1);

namespace App\Drush\Commands;

use Drush\Commands\DrushCommands;

final class AppDrushCommands extends DrushCommands {

#[Drush\Attributes\Command(name: 'app:hello-world', aliases: ['hello-world'])]
public function helloWorld(): void {
$this->io()->writeln('<info>Hello world!</info>');
}

}
#[Drush\Attributes\Command(
name: 'app:hello-world',
aliases: ['hello-world']
)]
<?php

namespace Drush\Attributes;

use Attribute;

#[Attribute(Attribute::TARGET_METHOD)]
class Command extends \Consolidation\AnnotatedCommand\Attributes\Command
{
}
<?php

namespace Consolidation\AnnotatedCommand\Attributes;

use Attribute;
use Consolidation\AnnotatedCommand\Parser\CommandInfo;

#[Attribute(Attribute::TARGET_METHOD)]
class Command
{
/**
* @param $name
* The name of the command or hook.
* @param string[] $aliases
* An array of alternative names for this item.
*/
public function __construct(
public string $name,
public array $aliases = [],
) {
}

public static function handle(\ReflectionAttribute $attribute, CommandInfo $commandInfo)
{
$args = $attribute->getArguments();
$commandInfo->setName($args['name']);
$commandInfo->addAnnotation('command', $args['name']);
$commandInfo->setAliases($args['aliases'] ?? []);
}
}
public function parse()
{
$attributes = $this->reflection->getAttributes();
foreach ($attributes as $attribute) {
if (method_exists($attribute->getName(), 'handle')) {
call_user_func([$attribute->getName(), 'handle'], $attribute, $this->commandInfo);
}
}
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Matt Glaman

Matt Glaman

178 Followers

Open source developer, working with Drupal and building Drupal Commerce.