You are here

class BlockManagerForm in Gutenberg 8

Same name and namespace in other branches
  1. 8.2 modules/gutenberg_cloud/src/Form/BlockManagerForm.php \Drupal\gutenberg_cloud\Form\BlockManagerForm

Configure Gutenberg Cloud blocks.

Hierarchy

Expanded class hierarchy of BlockManagerForm

1 string reference to 'BlockManagerForm'
gutenberg_cloud.routing.yml in modules/gutenberg_cloud/gutenberg_cloud.routing.yml
modules/gutenberg_cloud/gutenberg_cloud.routing.yml

File

modules/gutenberg_cloud/src/Form/BlockManagerForm.php, line 19

Namespace

Drupal\gutenberg_cloud\Form
View source
class BlockManagerForm extends ConfigFormBase {

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return [
      'gutenberg_cloud.blocks',
    ];
  }

  /**
   * Messenger service.
   *
   * @var \Drupal\Core\Messenger\MessengerInterface
   */
  protected $messenger;

  /**
   * Cloud Block Manager service.
   *
   * @var \Drupal\gutenberg_cloud\CloudBlockManager
   */
  protected $blockManager;

  /**
   * Library Discovery service.
   *
   * @var \Drupal\Core\Asset\LibraryDiscoveryInterface
   */
  protected $libraryDiscovery;

  /**
   * BlockManagerForm constructor.
   *
   * @param \Drupal\Core\Messenger\MessengerInterface $messenger
   *   Messanger service.
   * @param \Drupal\gutenberg_cloud\CloudBlockManager $block_manager
   *   Cloud Block Manager service.
   * @param \Drupal\Core\Asset\LibraryDiscoveryInterface $library_discovery
   *   Library Discovery service.
   */
  public function __construct(MessengerInterface $messenger, CloudBlockManager $block_manager, LibraryDiscoveryInterface $library_discovery) {
    $this->messenger = $messenger;
    $this->blockManager = $block_manager;
    $this->libraryDiscovery = $library_discovery;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('messenger'), $container
      ->get('gutenberg_cloud.block_manager'), $container
      ->get('library.discovery'));
  }

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $cloudBlocks = $this->blockManager
      ->loadAllFromRemote();
    if (!empty($cloudBlocks)) {
      $this
        ->addFilters($form);
      $form['blocks'] = [
        '#type' => 'container',
        '#attributes' => [
          'class' => [
            'gutenberg-cloud__blocks',
          ],
        ],
      ];

      // Loop index - default order of the blocks.
      $weight = 0;
      foreach ($cloudBlocks as $key => $block) {
        $id = Html::cleanCssIdentifier($block
          ->getName());
        $form['blocks'][$key] = [
          '#type' => 'fieldset',
          '#open' => TRUE,
          '#id' => $id,
          '#attributes' => [
            'class' => [
              'gutenberg-cloud__item',
            ],
            'data-popularity' => $block
              ->getRaw()->installs,
            'data-weight' => $weight++,
          ],
        ];
        $form['blocks'][$key]['details_wrapper'] = [
          '#type' => 'container',
          '#attributes' => [
            'class' => [
              'gutenberg-cloud__details',
            ],
          ],
        ];
        $form['blocks'][$key]['details_wrapper']['details'] = [
          '#type' => 'button',
          '#value' => $this
            ->t('More details'),
          '#ajax' => [
            'callback' => '::viewDetails',
            'event' => 'click',
          ],
          '#attributes' => [
            'class' => [
              'details',
            ],
          ],
          '#name' => 'details__' . $block
            ->getName(),
        ];
        $form['blocks'][$key]['details_wrapper']['image'] = [
          '#theme' => 'image',
          '#uri' => $block
            ->getAssetUrl('screenshot', $this->blockManager
            ->getCdnUrl()),
        ];
        $form['blocks'][$key]['title'] = [
          '#type' => 'html_tag',
          '#tag' => 'h2',
          '#value' => $block
            ->getLabel(),
          '#attributes' => [
            'class' => [
              'title',
            ],
          ],
        ];
        $form['blocks'][$key]['install'] = [
          '#type' => 'submit',
          '#value' => $this
            ->t('Install'),
          '#ajax' => [
            'callback' => '::installCallback',
            'event' => 'click',
            'method' => 'replace',
            'effect' => 'fade',
            'wrapper' => $id,
            'progress' => [
              'type' => 'submit',
              'message' => $this
                ->t('Installing...'),
            ],
          ],
          '#button_type' => 'primary',
          '#name' => 'install__' . $block
            ->getName(),
          '#access' => FALSE,
        ];
        $form['blocks'][$key]['update'] = [
          '#type' => 'submit',
          '#value' => $this
            ->t('Update'),
          '#ajax' => [
            'callback' => '::updateCallback',
            'event' => 'click',
            'method' => 'replace',
            'effect' => 'fade',
            'wrapper' => $id,
            'progress' => [
              'type' => 'submit',
              'message' => $this
                ->t('Updating...'),
            ],
          ],
          '#button_type' => 'primary',
          '#name' => 'update__' . $block
            ->getName(),
          '#access' => FALSE,
        ];
        $form['blocks'][$key]['uninstall'] = [
          '#type' => 'submit',
          '#value' => $this
            ->t('Uninstall'),
          '#ajax' => [
            'callback' => '::uninstallCallback',
            'event' => 'click',
            'method' => 'replace',
            'effect' => 'fade',
            'wrapper' => $id,
            'progress' => [
              'type' => 'throbber',
              'message' => $this
                ->t('Uninstalling...'),
            ],
          ],
          '#name' => 'uninstall__' . $block
            ->getName(),
          '#access' => FALSE,
        ];
        if (!$this->blockManager
          ->isBlockEnabled($block)) {
          $form['blocks'][$key]['install']['#access'] = TRUE;
        }
        else {
          if ($this->blockManager
            ->hasUpdates($block)) {
            $form['blocks'][$key]['update']['#access'] = TRUE;
          }
          $form['blocks'][$key]['uninstall']['#access'] = TRUE;
          $form['blocks'][$key]['#attributes']['class'][] = 'enabled';
        }
      }
      $form['#attached']['library'] = [
        'gutenberg_cloud/blocks',
      ];
    }
    $form_state
      ->setCached(FALSE);
    return $form;
  }

  /**
   * Ajax callback to display block details in modal.
   *
   * @param array $form
   *   Form structure.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   Form state.
   *
   * @return \Drupal\Core\Ajax\AjaxResponse
   *   Modal dialog.
   */
  public function viewDetails(array &$form, FormStateInterface $form_state) {
    $element = $form_state
      ->getTriggeringElement();
    $name = str_replace('details__', '', $element['#name']);
    $block = $this->blockManager
      ->loadRemote($name);
    $rawBlock = $block
      ->getRaw();
    $details = [
      '#theme' => 'gutenberg_cloud__details',
      '#name' => $block
        ->getLabel(),
      '#version' => $block
        ->getVersion(),
      '#description' => $block
        ->getDescription(),
      '#author' => $rawBlock->package->author->name,
      '#author_url' => $rawBlock->package->author->url,
      '#picture' => $block
        ->getAssetUrl('screenshot', $this->blockManager
        ->getCdnUrl()),
      '#tags' => $rawBlock->package->keywords,
    ];
    $details['#attached']['library'][] = 'core/drupal.dialog.ajax';
    $details['#attached']['library'][] = 'gutenberg_cloud/details';
    $response = new AjaxResponse();
    $response
      ->addCommand(new OpenModalDialogCommand($block
      ->getLabel(), $details, [
      'width' => '80%',
    ]));
    return $response;
  }

  /**
   * Block installation callback.
   *
   * @param array $form
   *   Form structure.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   Form state.
   *
   * @return array
   *   Form element
   */
  public function installCallback(array &$form, FormStateInterface $form_state) {
    $output = $this
      ->performCallbackAction($form, $form_state, 'install');
    return $output;
  }

  /**
   * Block update callback.
   *
   * @param array $form
   *   Form structure.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   Form state.
   *
   * @return array
   *   Form element
   */
  public function updateCallback(array &$form, FormStateInterface $form_state) {
    $output = $this
      ->performCallbackAction($form, $form_state, 'update');
    return $output;
  }

  /**
   * Block uninstall callback.
   *
   * @param array $form
   *   Form structure.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   Form state.
   *
   * @return array
   *   Form element
   */
  public function uninstallCallback(array &$form, FormStateInterface $form_state) {
    $output = $this
      ->performCallbackAction($form, $form_state, 'uninstall');
    return $output;
  }

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

  /**
   * Save configs and alter the form on ajax callback.
   *
   * @param array $form
   *   Form structure.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   Form state.
   * @param string $type
   *   Action to perform.
   *
   * @return array
   *   Form element
   */
  protected function performCallbackAction(array &$form, FormStateInterface $form_state, $type = '') {
    $config = $this
      ->config('gutenberg_cloud.blocks');
    $element = $form_state
      ->getTriggeringElement();
    $parents = $element['#array_parents'];
    $output = $form[$parents[0]][$parents[1]];
    $name = str_replace($type . '__', '', $element['#name']);
    switch ($type) {
      case 'update':
      case 'install':
        $block = $this->blockManager
          ->loadRemote($name);
        if ($block instanceof CloudBlockInterface) {
          $config
            ->set($name, $block
            ->getConfig())
            ->save();
        }
        $output['install']['#access'] = FALSE;
        $output['update']['#access'] = FALSE;
        $output['uninstall']['#access'] = TRUE;
        $output['#attributes']['class'][] = 'enabled';
        $message = $type == 'install' ? 'Installed' : 'Updated';
        $this->messenger
          ->addStatus($this
          ->t('@message', [
          '@message' => $message,
        ]));
        break;
      case 'uninstall':
        $config
          ->clear($name)
          ->save();
        $output['install']['#access'] = TRUE;
        $output['update']['#access'] = FALSE;
        $output['uninstall']['#access'] = FALSE;
        $classes = $output['#attributes']['class'];
        $output['#attributes']['class'] = array_diff($classes, [
          'enabled',
        ]);
        $this->messenger
          ->addStatus($this
          ->t('Uninstalled'));
        break;
      default:
        break;
    }
    $this->libraryDiscovery
      ->clearCachedDefinitions();
    return $output;
  }

  /**
   * Adds filters to form.
   *
   * @param array $form
   *   Form structure.
   */
  protected function addFilters(array &$form) {
    $form['filters'] = [
      '#type' => 'container',
      '#attributes' => [
        'class' => [
          'gutenberg-cloud__filters',
        ],
      ],
    ];
    $filters = [
      'all' => [
        'label' => $this
          ->t('All'),
        'filter' => 'all',
      ],
      'installed' => [
        'label' => $this
          ->t('Installed'),
        'filter' => 'enabled',
      ],
      'popular' => [
        'label' => $this
          ->t('Popular'),
        'filter' => 'popular',
      ],
    ];
    foreach ($filters as $name => $filter) {
      $form['filters'][$name] = [
        '#type' => 'html_tag',
        '#tag' => 'button',
        '#value' => $filter['label'],
        '#attributes' => [
          'class' => [
            'filter',
          ],
          'type' => 'button',
          'data-filter' => $filter['filter'],
        ],
      ];
    }
    $form['filters']['search'] = [
      '#type' => 'search',
      '#title' => $this
        ->t('Search block'),
      '#title_display' => 'invisible',
      '#size' => 30,
      '#placeholder' => $this
        ->t('Search blocks...'),
      '#attributes' => [
        'class' => [
          'search',
        ],
        'autocomplete' => 'on',
      ],
    ];
  }

}

Members

Namesort descending Modifiers Type Description Overrides
BlockManagerForm::$blockManager protected property Cloud Block Manager service.
BlockManagerForm::$libraryDiscovery protected property Library Discovery service.
BlockManagerForm::$messenger protected property Messenger service. Overrides MessengerTrait::$messenger
BlockManagerForm::addFilters protected function Adds filters to form.
BlockManagerForm::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
BlockManagerForm::create public static function Instantiates a new instance of this class. Overrides ConfigFormBase::create
BlockManagerForm::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
BlockManagerForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
BlockManagerForm::installCallback public function Block installation callback.
BlockManagerForm::performCallbackAction protected function Save configs and alter the form on ajax callback.
BlockManagerForm::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
BlockManagerForm::uninstallCallback public function Block uninstall callback.
BlockManagerForm::updateCallback public function Block update callback.
BlockManagerForm::viewDetails public function Ajax callback to display block details in modal.
BlockManagerForm::__construct public function BlockManagerForm constructor. Overrides ConfigFormBase::__construct
ConfigFormBaseTrait::config protected function Retrieves a configuration object.
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::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
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 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.