Commit 034aa364 authored by Yas Naoi's avatar Yas Naoi Committed by Yas Naoi
Browse files

Issue #3306321 by yas, baldwinlouie: Add a block to list out VMware hosts

parent 2fdd18eb
Loading
Loading
Loading
Loading
+2 −2
Original line number Diff line number Diff line
<?php

namespace Drupal\VMware\Plugin\Block;
namespace Drupal\vmware\Plugin\Block;

use Drupal\cloud\Plugin\cloud\config\CloudConfigPluginManagerInterface;
use Drupal\cloud\Traits\CloudContentEntityTrait;
@@ -22,7 +22,7 @@ use Symfony\Component\DependencyInjection\ContainerInterface;
 *   category = @Translation("VMware")
 * )
 */
class VMwareResourcesBlock extends BlockBase implements ContainerFactoryPluginInterface {
class VmwareResourcesBlock extends BlockBase implements ContainerFactoryPluginInterface {

  use CloudContentEntityTrait;
  use CloudResourceTrait;
+259 −0
Original line number Diff line number Diff line
<?php

namespace Drupal\vmware\Plugin\Block;

use Drupal\cloud\Plugin\cloud\config\CloudConfigPluginManagerInterface;
use Drupal\cloud\Service\EntityLinkRendererInterface;
use Drupal\cloud\Traits\AccessCheckTrait;
use Drupal\cloud\Traits\CloudContentEntityTrait;
use Drupal\cloud\Traits\CloudResourceTrait;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Datetime\DateFormatterInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Session\AccountInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides a block displaying VMware VMs.
 *
 * @Block(
 *   id = "vmware_vm_block",
 *   admin_label = @Translation("VMware VMs"),
 *   category = @Translation("VMware")
 * )
 */
class VmwareVmBlock extends BlockBase implements ContainerFactoryPluginInterface {

  use CloudContentEntityTrait;
  use CloudResourceTrait;
  use AccessCheckTrait;

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

  /**
   * The current user.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $currentUser;

  /**
   * The cloud config plugin manager.
   *
   * @var \Drupal\cloud\Plugin\cloud\config\CloudConfigPluginManagerInterface
   */
  protected $cloudConfigPluginManager;

  /**
   * The date formatter.
   *
   * @var \Drupal\Core\Datetime\DateFormatterInterface
   */
  protected $dateFormatter;

  /**
   * Entity link renderer object.
   *
   * @var \Drupal\cloud\Service\EntityLinkRendererInterface
   */
  protected $entityLinkRenderer;

  /**
   * Creates a ResourcesBlock instance.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Session\AccountInterface $current_user
   *   The current user.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   An entity type manager instance.
   * @param \Drupal\cloud\Plugin\cloud\config\CloudConfigPluginManagerInterface $cloud_config_plugin_manager
   *   The cloud config plugin manager.
   * @param \Drupal\Core\Datetime\DateFormatterInterface $date_formatter
   *   The date formatter.
   * @param \Drupal\cloud\Service\EntityLinkRendererInterface $entity_link_renderer
   *   The entity link render service.
   */
  public function __construct(
    array $configuration,
          $plugin_id,
          $plugin_definition,
    AccountInterface $current_user,
    EntityTypeManagerInterface $entity_type_manager,
    CloudConfigPluginManagerInterface $cloud_config_plugin_manager,
    DateFormatterInterface $date_formatter,
    EntityLinkRendererInterface $entity_link_renderer
  ) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->currentUser = $current_user;
    $this->entityTypeManager = $entity_type_manager;
    $this->cloudConfigPluginManager = $cloud_config_plugin_manager;
    $this->dateFormatter = $date_formatter;
    $this->entityLinkRenderer = $entity_link_renderer;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('current_user'),
      $container->get('entity_type.manager'),
      $container->get('plugin.manager.cloud_config_plugin'),
      $container->get('date.formatter'),
      $container->get('entity.link_renderer')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration(): array {
    return [
      'cloud_context' => '',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function blockForm($form, FormStateInterface $form_state): array {
    $form = parent::blockForm($form, $form_state);
    $config = $this->getConfiguration();
    $form['cloud_context'] = [
      '#type' => 'select',
      '#title' => $this->t('Cloud service provider'),
      '#description' => $this->t('Select cloud service provider.'),
      '#options' => $this->cloudConfigPluginManager->getCloudConfigs($this->t('All VMware regions'), 'vmware'),
      '#default_value' => $config['cloud_context'] ?? '',
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function blockSubmit($form, FormStateInterface $form_state): void {
    $this->configuration['cloud_context'] = $form_state->getValue('cloud_context');
  }

  /**
   * {@inheritdoc}
   */
  public function build(): array {
    $build = [];

    $build['vms'] = [
      '#type' => 'details',
      '#title' => $this->t('VMs for @region', [
        '@region' => $this->getRegionName(),
      ]),
      '#open' => TRUE,
    ];

    $build['vms']['table'] = $this->buildTable();
    $build['vms']['#attached'] = [
      'library' => [
        'cloud/datatables',
      ],
    ];
    $build['vms']['#attributes']['class'][] = 'simple-datatable';

    return $build;
  }

  /**
   * Build VMware table.
   *
   * @return array
   *   Table array.
   */
  private function buildTable(): array {
    return [
      '#type' => 'table',
      '#header' => [
        $this->t('Name'),
        $this->t('VM ID'),
        $this->t('State'),
        $this->t('Created'),
      ],
      '#empty' => $this->t('No VMs found.'),
      '#attributes' => [
        'class' => [
          'simple-datatable',
        ],
      ],
      '#rows' => $this->getVmRows(),
    ];
  }

  /**
   * Get VMs from database.
   *
   * @return array
   *   Array of VMs
   */
  private function getVmRows(): array {
    $rows = [];
    $entities = $this->runEntityQuery('vmware_vm', []);
    /** @var \Drupal\Vmware\Entity\VmwareVm $entity */
    foreach ($entities ?: [] as $entity) {
      if ($this->allowedIfCanAccessCloudConfigWithOwner(
          $entity,
          $this->currentUser,
          'view own vmware vm',
          'view any vmware vm'
        )->isAllowed() === FALSE) {
        continue;
      }

      $link = $entity->getName();
      try {
        $link = $entity->toLink($entity->getName());
      }
      catch (\Exception $e) {
        $this->messenger()->addError("An error occurred: {$e->getMessage()}");
      }
      $rows[] = [
        'data' => [
          $link,
          $entity->getVmId(),
          $entity->getPowerState(),
          $this->dateFormatter->format($entity->created(), 'short'),
        ],
      ];
    }

    return $rows;
  }

  /**
   * Get region name.
   *
   * @return string|null
   *   Region string or NULL
   */
  private function getRegionName(): ?string {
    if (empty($this->configuration['cloud_context'])) {
      return $this->t('all VMware regions');
    }
    $this->cloudConfigPluginManager->setCloudContext($this->configuration['cloud_context']);
    $region = $this->cloudConfigPluginManager->loadConfigEntity();
    return empty($region) === FALSE ? $region->getName() : NULL;
  }

}