You are here

class AnonymousPublishingClAdminModeration in Anonymous Publishing 8

This class defines the moderation setting form for this module, available at : admin/config/people/anonymous_publishing_cl/moderation

Hierarchy

Expanded class hierarchy of AnonymousPublishingClAdminModeration

1 string reference to 'AnonymousPublishingClAdminModeration'
anonymous_publishing_cl.routing.yml in modules/anonymous_publishing_cl/anonymous_publishing_cl.routing.yml
modules/anonymous_publishing_cl/anonymous_publishing_cl.routing.yml

File

modules/anonymous_publishing_cl/src/Form/AnonymousPublishingClAdminModeration.php, line 19

Namespace

Drupal\anonymous_publishing_cl\Form
View source
class AnonymousPublishingClAdminModeration extends FormBase {

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

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('database'));
  }

  /**
   * Constructs a \Drupal\anonymous_publishing_cl\Form\AnonymousPublishingClAdminModeration object.
   *
   * @param \Drupal\Core\Database\Connection $database
   *   The database connection service.
   */
  public function __construct(Connection $database) {
    $this->database = $database;
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'anonymous_publishing_cl_admin_moderation';
  }
  public function buildForm(array $form, FormStateInterface $form_state) {

    // Build an 'Update options' form.
    $form['options'] = array(
      '#type' => 'details',
      '#title' => $this
        ->t('Update options'),
      '#open' => TRUE,
      '#attributes' => array(
        'class' => array(
          'container-inline',
        ),
      ),
    );
    $options = array(
      'publish' => $this
        ->t('Publish the selected items'),
      'unpublish' => $this
        ->t('Unpublish the selected items'),
    );
    $form['options']['operation'] = array(
      '#type' => 'select',
      '#title' => $this
        ->t('Action'),
      '#title_display' => 'invisible',
      '#options' => $options,
      '#default_value' => 'publish',
    );
    $form['options']['submit'] = array(
      '#type' => 'submit',
      '#value' => $this
        ->t('Update'),
    );
    $form['apm_info'] = [
      '#markup' => t('<p>The following table shows all nodes that have been verified by email. You may publish or unpublish by selecting the corresponding line(s) and perform the update action.</p>'),
    ];
    $header = array(
      'title' => array(
        'data' => $this
          ->t('Title'),
        'specifier' => 'title',
        'sort' => 'desc',
      ),
      'type' => array(
        'data' => $this
          ->t('Type'),
        'class' => array(
          RESPONSIVE_PRIORITY_MEDIUM,
        ),
      ),
      'email' => array(
        'data' => $this
          ->t('Email'),
      ),
      'published' => array(
        'data' => $this
          ->t('Published'),
        'sort' => 'desc',
        'specifier' => 'published',
      ),
    );
    $options = array();
    $hidden_values = array();

    // Fetch all nodes that has been verified.
    $results = $this
      ->getAllContentsToModerate($header);
    foreach ($results as $row) {

      // Retrieve the title and status of the comment or node depending on
      // nature.
      if ($row->cid) {
        $comment = Comment::load($row->cid);
        if ($comment) {
          $title = $comment
            ->getSubject();
          $url = $comment
            ->permalink();
          $status = $comment
            ->isPublished() ? $this
            ->t('Published') : $this
            ->t('Unpublished');
        }
        else {
          $title = $this
            ->t('-deleted-');
          $url = null;
          $status = $this
            ->t('Unpublished');
        }
        $type = 'comment';
        $id = $row->cid;
      }
      else {
        $node = Node::load($row->nid);
        if ($node) {
          $title = $node
            ->getTitle();
          $url = Url::fromUri($node
            ->toUrl('canonical', array(
            'absolute' => TRUE,
          ))
            ->toString());
          $status = $node
            ->isPublished() ? $this
            ->t('Published') : $this
            ->t('Unpublished');
        }
        else {
          $title = $this
            ->t('-deleted-');
          $url = null;
          $status = $this
            ->t('Unpublished');
        }
        $type = 'node';
        $id = $row->nid;
      }
      if ($url) {
        $datatitle = array(
          '#type' => 'link',
          '#title' => Html::escape($title),
          '#url' => $url,
        );
      }
      else {
        $datatitle = array(
          '#markup' => Html::escape($title),
        );
      }
      $options[$id] = array(
        'title' => array(
          'data' => $datatitle,
        ),
        'type' => array(
          'data' => array(
            '#markup' => $this
              ->t($type),
          ),
        ),
        'email' => array(
          'data' => array(
            '#markup' => $row->email,
          ),
        ),
        'published' => array(
          'data' => array(
            '#markup' => $status,
          ),
        ),
      );
      $hidden_values[$row->nid] = $type;
    }
    $form['hidden_values'] = array(
      '#type' => 'hidden',
      '#value' => serialize($hidden_values),
    );
    $form['items'] = array(
      '#type' => 'tableselect',
      '#header' => $header,
      '#options' => $options,
      '#empty' => $this
        ->t('There is no verified content to moderate.'),
    );
    $form['pager'] = array(
      '#type' => 'pager',
    );
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $form_state
      ->setValue('items', array_diff($form_state
      ->getValue('items'), array(
      0,
    )));

    // We can't execute any 'Update options' if no items were selected.
    if (count($form_state
      ->getValue('items')) == 0) {
      $form_state
        ->setErrorByName('', $this
        ->t('Select one or more items to perform the update on.'));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $operation = $form_state
      ->getValue('operation');
    $ids = $form_state
      ->getValue('items');
    $hidden = unserialize($form_state
      ->getValue('hidden_values'));
    foreach ($ids as $id) {

      // Load the entity depending on type:
      $entity = NULL;
      switch ($hidden[$id]) {
        case 'node':
          $entity = Node::load($id);
          break;
        case 'comment':
          $entity = Comment::load($id);
          break;
      }
      if ($entity) {
        if ($operation == 'unpublish') {
          $entity
            ->setPublished(FALSE);
          $entity
            ->save();
        }
        elseif ($operation == 'publish') {
          $entity
            ->setPublished(TRUE);
          $entity
            ->save();
        }
      }
    }
    $this
      ->messenger()
      ->addMessage($this
      ->t('The update has been performed.'));
  }

  /**
   * Get all contents to moderate.
   *
   * @param int $test_id
   *   The test_id to retrieve results of.
   *
   * @return array
   *  Array of results grouped by test_class.
   */
  protected function getAllContentsToModerate($header) {
    $query = $this->database
      ->select('anonymous_publishing', 'a');
    $query
      ->fields('a');
    $query
      ->where('a.verified > 0');
    $query
      ->extend('Drupal\\Core\\Database\\Query\\TableSortExtender')
      ->orderByHeader($header);
    $query
      ->extend('Drupal\\Core\\Database\\Query\\PagerSelectExtender')
      ->limit(50);
    return $query
      ->execute()
      ->fetchAll();
  }

}

Members

Namesort descending Modifiers Type Description Overrides
AnonymousPublishingClAdminModeration::$database protected property The database connection service.
AnonymousPublishingClAdminModeration::buildForm public function Form constructor. Overrides FormInterface::buildForm
AnonymousPublishingClAdminModeration::create public static function Instantiates a new instance of this class. Overrides FormBase::create
AnonymousPublishingClAdminModeration::getAllContentsToModerate protected function Get all contents to moderate.
AnonymousPublishingClAdminModeration::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
AnonymousPublishingClAdminModeration::submitForm public function Form submission handler. Overrides FormInterface::submitForm
AnonymousPublishingClAdminModeration::validateForm public function Form validation handler. Overrides FormBase::validateForm
AnonymousPublishingClAdminModeration::__construct public function Constructs a \Drupal\anonymous_publishing_cl\Form\AnonymousPublishingClAdminModeration 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::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.
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.