<?phpdeclare(strict_types=1);namespaceDrupal\example\Command;useDrupal\Core\StringTranslation\StringTranslationTrait;useGuzzleHttp\ClientInterface;useSymfony\Component\Console\Attribute\Argument;useSymfony\Component\Console\Attribute\AsCommand;useSymfony\Component\Console\Command\Command;useSymfony\Component\Console\Output\OutputInterface;/** * An example console command. * * Drupal discovers classes with #[AsCommand] in a module's src/Command * directory and autowires their constructor arguments. To try this one, copy it * to modules/example/src/Command/XkcdFetchCommand.php in a module named * 'example', enable the module, then run `dr xkcd random`. */#[AsCommand(name:self::NAME,description:'Display a link to an xkcd cartoon.',aliases:['xkcd'],usages:['123','random',],)]finalclassXkcdFetchCommand{useStringTranslationTrait;publicconststringNAME='xkcd:fetch';publicfunction__construct(privatereadonlyClientInterface$httpClient,){}publicfunction__invoke(OutputInterface$output,#[Argument('A cartoon number, or "random". If omitted, the latest cartoon is used.')]string$search='',):int{$url=match(true){$search===''=>'https://xkcd.com',ctype_digit($search)=>'https://xkcd.com/'.$search,$search==='random'=>'https://xkcd.com/'.random_int(1,$this->latestNumber()),default=>thrownew\InvalidArgumentException((string)$this->t('@search is not a cartoon number or "random".',['@search'=>$search])),};$output->writeln($url);returnCommand::SUCCESS;}/** * Returns the number of the most recent cartoon. */privatefunctionlatestNumber():int{$response=$this->httpClient->request('GET','https://xkcd.com/info.0.json');$info=json_decode((string)$response->getBody(),true,flags:JSON_THROW_ON_ERROR);return(int)$info['num'];}}