Пример команды, выводящей возраст по дате рождения:
src/Drush/Commands/AgeCommand.php:
<?php
declare(strict_types=1);
namespace Drupal\MODULENAME\Drush\Commands;
use Drupal\Component\Datetime\TimeInterface;
use Drush\Commands\AutowireTrait;
use Symfony\Component\Console\Attribute\Argument;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Style\SymfonyStyle;
#[AsCommand(
name: 'age',
description: 'Display age by birth date.',
)]
class AgeCommand extends Command {
use AutowireTrait;
/**
* {@inheritdoc}
*/
public function __construct(
protected TimeInterface $time,
) {
parent::__construct();
}
/**
* {@selfdoc}
*/
public function __invoke(
SymfonyStyle $io,
#[Argument('Birth date (Y-m-d)')]
string $birth_date,
): int {
try {
$birth_date_object = new \DateTime($birth_date);
}
catch (\DateMalformedStringException $exception) {
$io->getErrorStyle()->error($exception->getMessage());
return self::FAILURE;
}
$current_date_object = new \DateTime('@' . $this->time->getCurrentTime());
$age = $birth_date_object->diff($current_date_object)->y;
$io->writeln((string) $age);
return self::SUCCESS;
}
}Использование:
vendor/bin/drush age 1997-05-01
Условия, чтобы drush нашёл вашу команду:
1. Класс должен находится в директории src/Drush/Commands.
2. Название класса должно быть с суффиксом Command или Commands.
3. Класс должен расширять \Symfony\Component\Console\Command\Command.
4. Класс должен иметь php-атрибут \Symfony\Component\Console\Attribute\AsCommand.
5. Корректно внедрены зависимости (через AutowireTrait или #[Autowire(...)]).
Написанное актуально для
Drush 13.7+
Добавить комментарий