You are here

class HttpServiceApiPreviewForm in HTTP Client Manager 8

Same name and namespace in other branches
  1. 8.2 src/Form/HttpServiceApiPreviewForm.php \Drupal\http_client_manager\Form\HttpServiceApiPreviewForm

Class HttpServiceApiPreviewForm.

@package Drupal\http_client_manager\Form

Hierarchy

Expanded class hierarchy of HttpServiceApiPreviewForm

1 string reference to 'HttpServiceApiPreviewForm'
http_client_manager.routing.yml in ./http_client_manager.routing.yml
http_client_manager.routing.yml

File

src/Form/HttpServiceApiPreviewForm.php, line 21

Namespace

Drupal\http_client_manager\Form
View source
class HttpServiceApiPreviewForm extends FormBase {

  /**
   * Current Request.
   *
   * @var null|\Symfony\Component\HttpFoundation\Request
   */
  protected $request;

  /**
   * Drupal\http_client_manager\HttpServiceApiHandler definition.
   *
   * @var \Drupal\http_client_manager\HttpServiceApiHandler
   */
  protected $httpServicesApi;

  /**
   * Drupal\http_client_manager\HttpClientManagerFactory definition.
   *
   * @var \Drupal\http_client_manager\HttpClientManagerFactory
   */
  protected $httpClientFactory;

  /**
   * Drupal\Core\Entity\EntityTypeManagerInterface definition.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * HttpConfigRequestForm constructor.
   *
   * @param \Symfony\Component\HttpFoundation\RequestStack $requestStack
   *   The Request Stack Service.
   * @param \Drupal\http_client_manager\HttpServiceApiHandlerInterface $http_services_api
   *   The Http Service Api Handler service.
   * @param \Drupal\http_client_manager\HttpClientManagerFactoryInterface $http_client_manager_factory
   *   The Http Client Factory service.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The Entity Type Manager service.
   */
  public function __construct(RequestStack $requestStack, HttpServiceApiHandlerInterface $http_services_api, HttpClientManagerFactoryInterface $http_client_manager_factory, EntityTypeManagerInterface $entity_type_manager) {
    $this->request = $requestStack
      ->getCurrentRequest();
    $this->httpServicesApi = $http_services_api;
    $this->httpClientFactory = $http_client_manager_factory;
    $this->entityTypeManager = $entity_type_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('request_stack'), $container
      ->get('http_client_manager.http_services_api'), $container
      ->get('http_client_manager.factory'), $container
      ->get('entity_type.manager'));
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'http_service_api_preview_form';
  }

  /**
   * Route title callback.
   *
   * @param string $serviceApi
   *   The service api name.
   *
   * @return string
   *   The service api title.
   */
  public function title($serviceApi) {
    try {
      $api = $this->httpServicesApi
        ->load($serviceApi);
    } catch (\InvalidArgumentException $e) {
      $api['title'] = $this
        ->t('Http Service Api not found');
    }
    return $api['title'];
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $serviceApi = $this->request
      ->get('serviceApi');
    $client = $this->httpClientFactory
      ->get($serviceApi);
    $commands = $client
      ->getCommands();
    ksort($commands);
    $form['search'] = [
      '#type' => 'select',
      '#options' => array_combine(array_keys($commands), array_keys($commands)),
      '#empty_option' => $this
        ->t('- All Commands -'),
      '#title' => $this
        ->t('Filter commands'),
      '#title_display' => 'invisible',
      '#ajax' => [
        'callback' => '::filterCommandsAjaxCallback',
        'wrapper' => 'service-commands-wrapper',
      ],
      '#required' => TRUE,
    ];
    $form['service_commands'] = [
      '#type' => 'vertical_tabs',
      '#prefix' => '<div id="service-commands-wrapper">',
      '#suffix' => '</div>',
    ];
    $header = [
      'name' => $this
        ->t('Name'),
      'type' => $this
        ->t('Type'),
      'default' => $this
        ->t('Default'),
      'description' => $this
        ->t('Description'),
      'required' => $this
        ->t('Required'),
      'location' => $this
        ->t('Location'),
    ];

    /** @var Operation $command */
    foreach ($commands as $commandName => $command) {
      $rows = [];

      /** @var Parameter $param */
      foreach ($command
        ->getParams() as $param) {
        $row = [
          'name' => $param
            ->getName(),
          'type' => $this
            ->getParameterType($param),
          'default' => $param
            ->getDefault(),
          'description' => $param
            ->getDescription(),
          'required' => $param
            ->getRequired() ? $this
            ->t('Yes') : $this
            ->t('No'),
          'location' => $param
            ->getLocation(),
        ];
        $rows[] = $row;
      }
      $form[$commandName] = [
        '#type' => 'details',
        '#title' => $this
          ->t($command
          ->getName()),
        '#description' => $this
          ->t($command
          ->getSummary()),
        '#group' => 'service_commands',
        '#access' => !$this
          ->isHiddenCommand($commandName, $form_state),
      ];
      $form[$commandName]['info'] = [
        '#type' => 'table',
        '#header' => [
          'method' => $this
            ->t('HTTP Method'),
          'uri' => $this
            ->t('URI'),
          'operations' => $this
            ->t('Operations'),
        ],
        '#rows' => [
          [
            $command
              ->getHttpMethod(),
            $command
              ->getUri(),
            [
              'data' => $this
                ->buildOperations($serviceApi, $commandName),
            ],
          ],
        ],
      ];
      $form[$commandName]['parameters'] = [
        '#type' => 'table',
        '#caption' => $this
          ->t('Parameters'),
        '#header' => $header,
        '#rows' => $rows,
        '#empty' => $this
          ->t('There are no parameters for this command.'),
      ];
    }
    $form['#attached']['library'][] = 'http_client_manager/service.preview';
    return $form;
  }

  /**
   * Filter commands Ajax Callback.
   *
   * @param array $form
   *   The form array.
   *
   * @return array
   *   The form element to be processed.
   */
  public function filterCommandsAjaxCallback(array $form) {
    return $form['service_commands'];
  }

  /**
   * Is hidden command.
   *
   * Check if the given command has to be filtered out.
   *
   * @param string $commandName
   *   The command name.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   *
   * @return bool
   *   Whether or not the command has to be hidden.
   */
  protected function isHiddenCommand($commandName, FormStateInterface $form_state) {
    $search = trim($form_state
      ->getValue('search', FALSE));
    if (empty($search)) {
      return FALSE;
    }
    return $search != $commandName;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

    // No action has to be performed.
  }

  /**
   * Get parameter type.
   *
   * @param \Guzzle\Service\Description\Parameter $param
   *   A Parameter instance.
   *
   * @return string
   *   A formatted Parameter type.
   */
  protected function getParameterType(Parameter $param) {
    $type = $param
      ->getType();
    if ($type != 'array') {
      return ucfirst($type);
    }
    $childType = $param
      ->getItems()
      ->getType();
    return '<List>' . ucfirst($childType);
  }

  /**
   * Build operations.
   *
   * @param string $serviceApi
   *   The service api name.
   * @param string $commandName
   *   The command name.
   *
   * @return array
   *   An array of operations.
   */
  protected function buildOperations($serviceApi, $commandName) {
    return [
      '#type' => 'operations',
      '#links' => [
        'config_requests' => [
          'title' => $this
            ->t('Configured Requests (@count)', [
            '@count' => $this
              ->getConfigEntitiesCount('http_config_request', $serviceApi, $commandName),
          ]),
          'url' => Url::fromRoute('entity.http_config_request.collection', [
            'serviceApi' => $serviceApi,
            'commandName' => $commandName,
          ]),
          'attributes' => [
            'class' => 'http-client-manager-service-summary',
          ],
        ],
      ],
    ];
  }

  /**
   * Get total number of available Http Config Requests for a specific command.
   *
   * @param string $serviceApi
   *   The service api name.
   * @param string $commandName
   *   The command name.
   *
   * @return int
   *   Total number of available config requests.
   */
  protected function getConfigEntitiesCount($entity, $serviceApi, $commandName) {
    $storage = $this->entityTypeManager
      ->getStorage($entity);
    return $storage
      ->getQuery()
      ->condition('service_api', $serviceApi)
      ->condition('command_name', $commandName)
      ->count()
      ->execute();
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 62
HttpServiceApiPreviewForm::$entityTypeManager protected property Drupal\Core\Entity\EntityTypeManagerInterface definition.
HttpServiceApiPreviewForm::$httpClientFactory protected property Drupal\http_client_manager\HttpClientManagerFactory definition.
HttpServiceApiPreviewForm::$httpServicesApi protected property Drupal\http_client_manager\HttpServiceApiHandler definition.
HttpServiceApiPreviewForm::$request protected property Current Request.
HttpServiceApiPreviewForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
HttpServiceApiPreviewForm::buildOperations protected function Build operations.
HttpServiceApiPreviewForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
HttpServiceApiPreviewForm::filterCommandsAjaxCallback public function Filter commands Ajax Callback.
HttpServiceApiPreviewForm::getConfigEntitiesCount protected function Get total number of available Http Config Requests for a specific command.
HttpServiceApiPreviewForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
HttpServiceApiPreviewForm::getParameterType protected function Get parameter type.
HttpServiceApiPreviewForm::isHiddenCommand protected function Is hidden command.
HttpServiceApiPreviewForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
HttpServiceApiPreviewForm::title public function Route title callback.
HttpServiceApiPreviewForm::__construct public function HttpConfigRequestForm constructor.
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.