You are here

class WebformEditorialController in Webform 8.5

Provides route responses for webform editorial.

Hierarchy

Expanded class hierarchy of WebformEditorialController

File

modules/webform_editorial/src/Controller/WebformEditorialController.php, line 24

Namespace

Drupal\webform_editorial\Controller
View source
class WebformEditorialController extends ControllerBase implements ContainerInjectionInterface {

  /**
   * Active database connection.
   *
   * @var \Drupal\Core\Database\Connection
   */
  protected $database;

  /**
   * The renderer.
   *
   * @var \Drupal\Core\Render\RendererInterface
   */
  protected $renderer;

  /**
   * The entity field manager.
   *
   * @var \Drupal\Core\Entity\EntityFieldManagerInterface
   */
  protected $entityFieldManager;

  /**
   * The webform help manager.
   *
   * @var \Drupal\Component\Plugin\PluginManagerInterface
   */
  protected $helpManager;

  /**
   * The webform element manager.
   *
   * @var \Drupal\webform\Plugin\WebformElementManagerInterface
   */
  protected $elementManager;

  /**
   * The webform libraries manager.
   *
   * @var \Drupal\webform\WebformLibrariesManagerInterface
   */
  protected $librariesManager;

  /**
   * Constructs a WebformEditorialController object.
   *
   * @param \Drupal\Core\Database\Connection $database
   *   The database connection to be used.
   * @param \Drupal\Core\Render\RendererInterface $renderer
   *   The renderer.
   * @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager
   *   The entity field manager.
   * @param \Drupal\webform\WebformHelpManagerInterface $help_manager
   *   The webform help manager.
   * @param \Drupal\webform\Plugin\WebformElementManagerInterface $element_manager
   *   The webform element manager.
   * @param \Drupal\webform\WebformLibrariesManagerInterface $libraries_manager
   *   The webform libraries manager.
   */
  public function __construct(Connection $database, RendererInterface $renderer, EntityFieldManagerInterface $entity_field_manager, WebformHelpManagerInterface $help_manager, WebformElementManagerInterface $element_manager, WebformLibrariesManagerInterface $libraries_manager) {
    $this->database = $database;
    $this->renderer = $renderer;
    $this->entityFieldManager = $entity_field_manager;
    $this->helpManager = $help_manager;
    $this->elementManager = $element_manager;
    $this->librariesManager = $libraries_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('database'), $container
      ->get('renderer'), $container
      ->get('entity_field.manager'), $container
      ->get('webform.help_manager'), $container
      ->get('plugin.manager.webform.element'), $container
      ->get('webform.libraries_manager'));
  }

  /**
   * Returns webform help index page.
   *
   * @return array
   *   A renderable array containing webform help index page.
   */
  public function index() {
    $path = drupal_get_path('module', 'webform_editorial') . '/webform_editorial.links.task.yml';
    $tasks = Yaml::decode(file_get_contents($path));
    $content = [];
    foreach ($tasks as $id => $task) {
      if (isset($task['parent_id'])) {
        $content[$id] = [
          'title' => $task['title'],
          'description' => $task['description'],
          'url' => Url::fromRoute($task['route_name']),
        ];
      }
    }
    return [
      '#theme' => 'admin_block_content',
      '#content' => $content,
    ];
  }

  /****************************************************************************/

  // Help.

  /****************************************************************************/

  /**
   * Returns webform help editorial.
   *
   * @return array
   *   A renderable array containing webform help editorial.
   */
  public function help() {
    $help = $this->helpManager
      ->getHelp();
    $groups = $this->helpManager
      ->getGroup();
    foreach ($groups as $group_name => $group) {
      $groups[$group_name] = [];
    }
    foreach ($help as $name => $info) {
      $group_name = isset($info['group']) ? $info['group'] : (string) $this
        ->t('General');
      $groups[$group_name][$name] = $info;
    }
    $groups = array_filter($groups);
    $build = [];
    $build['title'] = [
      '#prefix' => '<h1>',
      '#suffix' => '</h1>',
      '#markup' => $this
        ->t('Webform: Help editorial'),
    ];
    $group_index = 1;
    foreach ($groups as $group_name => $help) {

      // Header.
      $header = [
        [
          'data' => $this
            ->t('Name'),
          'width' => '20%',
        ],
        [
          'data' => $this
            ->t('Title'),
          'width' => '20%',
        ],
        [
          'data' => $this
            ->t('Content'),
          'width' => '50%',
        ],
        [
          'data' => $this
            ->t('Links'),
          'width' => '10%',
        ],
      ];

      // Rows.
      $rows = [];
      foreach ($help as $name => $info) {

        // Paths.
        $paths = [];
        if (!empty($info['paths'])) {
          $paths = array_merge($paths, $info['paths']);
        }
        if (!empty($info['routes'])) {
          $paths = array_merge($paths, $this->database
            ->query("SELECT path FROM {router} WHERE name IN (:name[])", [
            ':name[]' => $info['routes'],
          ])
            ->fetchCol() ?: []);
        }
        asort($paths);
        foreach ($paths as $index => $path) {
          $path = str_replace('/admin/structure/webform/', '../', $path);
          $path = str_replace('/admin/structure/', '../', $path);
          $path = preg_replace('/\\{[^}]+\\}/', '*', $path);
          $paths[$index] = $path;
        }
        $name = '<b>' . $name . '</b><br/><small><small><em>' . implode('<br />', $paths) . '</em></small></small>';

        // Links.
        $links = [];
        if (!empty($info['video_id'])) {
          $video = $this->helpManager
            ->getVideo($info['video_id']);
          $links[] = Link::fromTextAndUrl('Video', Url::fromUri('https://www.youtube.com/watch', [
            'query' => [
              'v' => $video['youtube_id'],
            ],
          ]))
            ->toString();
        }
        if (is_array($info['content'])) {
          $info['content'] = $this->renderer
            ->renderPlain($info['content']);
        }
        $rows[] = [
          'data' => [
            [
              'data' => $name,
            ],
            [
              'data' => $info['title'],
            ],
            [
              'data' => $info['content'],
            ],
            [
              'data' => implode(' | ', $links),
            ],
          ],
        ];
      }
      $title = ($this->helpManager
        ->getGroup($group_name) ?: $group_name) . ' [' . str_pad($group_index++, 2, '0', STR_PAD_LEFT) . ' - ' . $group_name . ']';
      $build[$group_name] = $this
        ->buildTable($title, $header, $rows, 'h2');
    }

    // Add videos.
    $presentations = $this->helpManager
      ->getVideo();
    foreach ($presentations as $presentation_name => $presentation) {
      $build[$presentation_name]['description']['title'] = [
        '#markup' => $presentation['title'],
        '#prefix' => '<strong>',
        '#suffix' => '</strong><br/>',
      ];
      $build[$presentation_name]['description']['content'] = [
        '#markup' => $presentation['content'],
        '#suffix' => '<br/><br/>',
      ];
    }
    return $this
      ->response($build);
  }

  /****************************************************************************/

  // Videos.

  /****************************************************************************/

  /**
   * Returns webform videos editorial.
   *
   * @return array
   *   A renderable array containing webform elements videos.
   */
  public function videos() {

    // Header.
    $header = [
      [
        'data' => $this
          ->t('Name'),
        'width' => '10%',
      ],
      [
        'data' => $this
          ->t('Title'),
        'width' => '20%',
      ],
      [
        'data' => $this
          ->t('Content'),
        'width' => '50%',
      ],
      [
        'data' => $this
          ->t('Video/Slides'),
        'width' => '20%',
      ],
    ];

    // Rows.
    $rows = [];
    $videos = $this->helpManager
      ->getVideo();
    foreach ($videos as $name => $info) {

      // @see https://stackoverflow.com/questions/2068344/how-do-i-get-a-youtube-video-thumbnail-from-the-youtube-api
      $image = Markup::create('<img width="180" src="https://img.youtube.com/vi/' . $info['youtube_id'] . '/0.jpg" />');
      $video = Link::fromTextAndUrl($image, Url::fromUri('https://www.youtube.com/watch', [
        'query' => [
          'v' => $info['youtube_id'],
        ],
      ]))
        ->toString();
      $slides = Link::fromTextAndUrl($this
        ->t('Slides'), Url::fromUri('https://docs.google.com/presentation/d/' . $info['presentation_id']))
        ->toString();
      $rows[] = [
        'data' => [
          [
            'data' => '<b>' . $name . '</b>' . (!empty($info['hidden']) ? '<br/>[' . $this
              ->t('hidden') . ']' : ''),
          ],
          [
            'data' => $info['title'],
          ],
          [
            'data' => $info['content'],
          ],
          [
            'data' => $video . '<br/>' . $slides,
          ],
        ],
      ];
    }
    $build = $this
      ->buildTable('Webform: Videos editorial', $header, $rows);
    return $this
      ->response($build);
  }

  /****************************************************************************/

  // Elements.

  /****************************************************************************/

  /**
   * Returns webform elements editorial.
   *
   * @return array
   *   A renderable array containing webform elements editorial.
   */
  public function elements() {
    $definitions = $this->elementManager
      ->getDefinitions();
    $definitions = $this->elementManager
      ->getSortedDefinitions($definitions, 'category');
    $grouped_definitions = $this->elementManager
      ->getGroupedDefinitions($definitions);
    unset($grouped_definitions['Other elements']);
    $build = [];
    $build['title'] = [
      '#prefix' => '<h1>',
      '#suffix' => '</h1>',
      '#markup' => $this
        ->t('Webform: Elements editorial'),
    ];
    foreach ($grouped_definitions as $category_name => $elements) {

      // Header.
      $header = [
        [
          'data' => $this
            ->t('Name'),
          'width' => '25%',
        ],
        [
          'data' => $this
            ->t('Label'),
          'width' => '25%',
        ],
        [
          'data' => $this
            ->t('Description'),
          'width' => '50%',
        ],
      ];

      // Rows.
      $rows = [];
      foreach ($elements as $name => $element) {
        $rows[] = [
          'data' => [
            [
              'data' => '<b>' . $name . '</b>',
            ],
            [
              'data' => $element['label'],
            ],
            [
              'data' => $element['description'],
            ],
          ],
        ];
      }
      $build[$category_name] = $this
        ->buildTable($category_name, $header, $rows, 'h2');
    }
    return $this
      ->response($build);
  }

  /****************************************************************************/

  // Libraries.

  /****************************************************************************/

  /**
   * Returns webform libraries.
   *
   * @return array
   *   A renderable array containing webform libraries editorial.
   */
  public function libraries() {

    // Header.
    $header = [
      [
        'data' => $this
          ->t('Name'),
        'width' => '10%',
      ],
      [
        'data' => $this
          ->t('Title'),
        'width' => '10%',
      ],
      [
        'data' => $this
          ->t('Description'),
        'width' => '40%',
      ],
      [
        'data' => $this
          ->t('Notes'),
        'width' => '40%',
      ],
    ];

    // Rows.
    $rows = [];
    $libraries = $this->librariesManager
      ->getLibraries();
    foreach ($libraries as $name => $library) {
      $rows[] = [
        'data' => [
          [
            'data' => $name,
          ],
          [
            'data' => '<a href="' . $library['homepage_url']
              ->toString() . '">' . $library['title'] . '</a>',
          ],
          [
            'data' => $library['description'],
          ],
          [
            'data' => $library['notes'],
          ],
        ],
      ];
    }
    $build = $this
      ->buildTable('Webform: Libraries editorial', $header, $rows);
    return $this
      ->response($build);
  }

  /****************************************************************************/

  // Schema.

  /****************************************************************************/

  /**
   * Returns webform schema.
   *
   * @return array
   *   A renderable array containing webform entity scheme.
   */
  public function schema() {

    // Header.
    $header = [
      [
        'data' => $this
          ->t('Name'),
        'width' => '20%',
      ],
      [
        'data' => $this
          ->t('Type'),
        'width' => '20%',
      ],
      [
        'data' => $this
          ->t('Description'),
        'width' => '60%',
      ],
    ];

    // Rows.
    $rows = [];

    /** @var \Drupal\Core\Field\BaseFieldDefinition[] $base_fields */
    $base_fields = $this->entityFieldManager
      ->getBaseFieldDefinitions('webform_submission');
    foreach ($base_fields as $field_name => $base_field) {
      $rows[] = [
        'data' => [
          [
            'data' => $field_name,
          ],
          [
            'data' => $base_field
              ->getType(),
          ],
          [
            'data' => $base_field
              ->getDescription(),
          ],
        ],
      ];
    }
    $build = $this
      ->buildTable('Webform Submission', $header, $rows);
    return $this
      ->response($build);
  }

  /****************************************************************************/

  // Drush.

  /****************************************************************************/

  /**
   * Returns webform drush.
   *
   * @return array
   *   A renderable array containing webform entity scheme.
   */
  public function drush() {
    module_load_include('inc', 'webform', 'drush/webform.drush');
    $build = [];
    $build['title'] = [
      '#prefix' => '<h1>',
      '#suffix' => '</h1>',
      '#markup' => $this
        ->t('Webform: Drush editorial'),
    ];

    // Header.
    $header = [
      [
        'data' => $this
          ->t('Name'),
        'width' => '30%',
      ],
      [
        'data' => $this
          ->t('Value'),
        'width' => '70%',
      ],
    ];
    $build = [];
    $commands = webform_drush_command();
    foreach ($commands as $command_name => $command) {
      $build[$command_name] = [];
      $build[$command_name]['title'] = [
        '#prefix' => '<h2>',
        '#suffix' => '</h2>',
        '#markup' => $command_name,
      ];
      $build[$command_name]['description'] = [
        '#prefix' => '<p>',
        '#suffix' => '</p>',
        '#markup' => $command['description'],
      ];
      if ($help = webform_drush_help('drush:' . $command_name)) {
        $build[$command_name]['help'] = [
          '#prefix' => '<address>',
          '#suffix' => '</address>',
          '#markup' => $help,
        ];
      }
      $properties = [
        'arguments',
        'options',
        'examples',
      ];
      foreach ($properties as $property) {
        if (isset($command[$property])) {
          $rows = [];
          foreach ($command[$property] as $name => $value) {
            $rows[] = [
              'data' => [
                [
                  'data' => $name,
                ],
                [
                  'data' => $value,
                ],
              ],
            ];
          }
          $build[$command_name][$property] = $this
            ->buildTable($property, $header, $rows, 'h3', FALSE);
        }
      }
      $build[$command_name]['hr'] = [
        '#markup' => '<br/><hr/>',
      ];
    }
    return $this
      ->response($build);
  }

  /****************************************************************************/

  // Helper methods.

  /****************************************************************************/

  /**
   * Build a reusable and styled table for inputs, outputs, and publications.
   *
   * @param string $title
   *   The table's title.
   * @param array $header
   *   The table's header.
   * @param array $rows
   *   The table's rows.
   * @param string $title_tag
   *   The header tag for title.
   * @param bool $hr
   *   Append horizontal rule.
   *
   * @return array
   *   A renderable array representing a table with title.
   */
  protected function buildTable($title, array $header, array $rows, $title_tag = 'h1', $hr = TRUE) {

    // Add style and alignment to header.
    foreach ($header as &$column) {
      $column['style'] = 'background-color: #ccc';
      $column['valign'] = 'top';
      $column['align'] = 'left';
    }

    // Add style and alignment to rows.
    foreach ($rows as &$row) {
      foreach ($row['data'] as &$column) {
        if (isset($column['data'])) {
          $column['data'] = [
            '#markup' => $column['data'],
            '#allowed_tags' => Xss::getAdminTagList(),
          ];
        }
      }
      $row['valign'] = 'top';
      $row['align'] = 'left';
    }
    return [
      'title' => [
        '#prefix' => "<{$title_tag}>",
        '#suffix' => "</{$title_tag}>",
        '#markup' => $title,
      ],
      'description' => [],
      'table' => [
        '#theme' => 'table',
        '#header' => $header,
        '#rows' => $rows,
        '#attributes' => [
          'border' => 1,
          'cellspacing' => 0,
          'cellpadding' => 5,
          'width' => '950',
        ],
      ],
      '#suffix' => $hr ? '<br/><hr/>' : '',
    ];
  }

  /**
   * Build a custom response the returns raw HTML markup.
   *
   * @param array $build
   *   A renderable array.
   *
   * @return \Symfony\Component\HttpFoundation\Response
   *   a custom response that contains raw HTML markup.
   */
  protected function response(array $build) {
    $output = $this->renderer
      ->renderPlain($build);
    $headers = [
      'Content-Length' => strlen($output),
      'Content-Type' => 'text/html',
    ];
    return new Response($output, 200, $headers);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ControllerBase::$configFactory protected property The configuration factory.
ControllerBase::$currentUser protected property The current user service. 1
ControllerBase::$entityFormBuilder protected property The entity form builder.
ControllerBase::$entityManager protected property The entity manager.
ControllerBase::$entityTypeManager protected property The entity type manager.
ControllerBase::$formBuilder protected property The form builder. 2
ControllerBase::$keyValue protected property The key-value storage. 1
ControllerBase::$languageManager protected property The language manager. 1
ControllerBase::$moduleHandler protected property The module handler. 2
ControllerBase::$stateService protected property The state service.
ControllerBase::cache protected function Returns the requested cache bin.
ControllerBase::config protected function Retrieves a configuration object.
ControllerBase::container private function Returns the service container.
ControllerBase::currentUser protected function Returns the current user. 1
ControllerBase::entityFormBuilder protected function Retrieves the entity form builder.
ControllerBase::entityManager Deprecated protected function Retrieves the entity manager service.
ControllerBase::entityTypeManager protected function Retrieves the entity type manager.
ControllerBase::formBuilder protected function Returns the form builder service. 2
ControllerBase::keyValue protected function Returns a key/value storage collection. 1
ControllerBase::languageManager protected function Returns the language manager service. 1
ControllerBase::moduleHandler protected function Returns the module handler. 2
ControllerBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
ControllerBase::state protected function Returns the state storage service.
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.
WebformEditorialController::$database protected property Active database connection.
WebformEditorialController::$elementManager protected property The webform element manager.
WebformEditorialController::$entityFieldManager protected property The entity field manager.
WebformEditorialController::$helpManager protected property The webform help manager.
WebformEditorialController::$librariesManager protected property The webform libraries manager.
WebformEditorialController::$renderer protected property The renderer.
WebformEditorialController::buildTable protected function Build a reusable and styled table for inputs, outputs, and publications.
WebformEditorialController::create public static function Instantiates a new instance of this class. Overrides ControllerBase::create
WebformEditorialController::drush public function Returns webform drush.
WebformEditorialController::elements public function Returns webform elements editorial.
WebformEditorialController::help public function Returns webform help editorial.
WebformEditorialController::index public function Returns webform help index page.
WebformEditorialController::libraries public function Returns webform libraries.
WebformEditorialController::response protected function Build a custom response the returns raw HTML markup.
WebformEditorialController::schema public function Returns webform schema.
WebformEditorialController::videos public function Returns webform videos editorial.
WebformEditorialController::__construct public function Constructs a WebformEditorialController object.