awareness-1.0.0-alpha5/src/Drush/Generators/AwarenessTraitGenerator.php

src/Drush/Generators/AwarenessTraitGenerator.php
<?php

declare(strict_types=1);

namespace Drupal\awareness\Drush\Generators;

use DrupalCodeGenerator\Asset\AssetCollection as Assets;
use DrupalCodeGenerator\Attribute\Generator;
use DrupalCodeGenerator\Command\BaseGenerator;
use DrupalCodeGenerator\GeneratorType;
use DrupalCodeGenerator\Validator\Required;
use Symfony\Component\Console\Question\ChoiceQuestion;
use Symfony\Component\Console\Question\Question;

/**
 * Generate an awareness trait.
 */
#[Generator(
  name: 'awareness:trait',
  description: 'Generates an awareness trait.',
  aliases: ['aware'],
  templatePath: __DIR__ . '/../../../templates/generator',
  type: GeneratorType::MODULE_COMPONENT,
)]
final class AwarenessTraitGenerator extends BaseGenerator {

  /**
   * {@inheritdoc}
   */
  protected function generate(array &$vars, Assets $assets): void {
    $ir = $this->createInterviewer($vars);

    $vars['machine_name'] = $ir->askMachineName();

    // Provide all service IDs as options.
    $question = new Question('Service ID');
    $question->setValidator(new Required());
    $question->setAutocompleterValues(\Drupal::getContainer()->getServiceIds());
    $vars['service_id'] = $this->io()->askQuestion($question);
    $service = \Drupal::getContainer()->get($vars['service_id']);

    // Provide all implemented interfaces as options.
    $interfaces = array_values(class_implements($service));
    $interfaces[] = get_class($service);
    $question = new ChoiceQuestion('Service interface/class', $interfaces);
    $question->setValidator(new Required());
    $vars['interface'] = $interfaces[$this->io()->askQuestion($question)];

    // Get the trait to be created.
    $vars['class'] = $ir->askClass(default: '{service_id|camelize}AwareTrait');

    // Get the method within the trait to be created.
    $vars['method'] = $ir->ask('Awareness trait method', default: 'get{service_id|camelize}');

    // Figure a few other variables from the service.
    $interface = array_filter(explode('\\', $vars['interface']));
    $vars['interface_short'] = array_pop($interface);
    $vars['service_namespace'] = implode('\\', $interface);
    $interface[1] = $vars['machine_name'];
    $vars['namespace'] = implode('\\', $interface);
    $vars['dir'] = implode('/', array_slice($interface, 2));

    // Add use directive if not in same namespace.
    $vars['use'] = $vars['namespace'] != $vars['service_namespace'];

    $vars['interface'] = '\\' . $vars['interface'];

    $assets->addFile('src/{dir}/{class}.php', 'awareness-trait.twig');
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc