UnpublishByKeywordComment.php 2.14 KB
Newer Older
1 2 3 4 5 6 7 8 9
<?php

/**
 * @file
 * Contains \Drupal\comment\Plugin\Action\UnpublishByKeywordComment.
 */

namespace Drupal\comment\Plugin\Action;

10
use Drupal\Component\Utility\Tags;
11
use Drupal\Core\Action\ConfigurableActionBase;
12
use Drupal\Core\Form\FormStateInterface;
13
use Drupal\Core\Session\AccountInterface;
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33

/**
 * Unpublishes a comment containing certain keywords.
 *
 * @Action(
 *   id = "comment_unpublish_by_keyword_action",
 *   label = @Translation("Unpublish comment containing keyword(s)"),
 *   type = "comment"
 * )
 */
class UnpublishByKeywordComment extends ConfigurableActionBase {

  /**
   * {@inheritdoc}
   */
  public function execute($comment = NULL) {
    $build = comment_view($comment);
    $text = drupal_render($build);
    foreach ($this->configuration['keywords'] as $keyword) {
      if (strpos($text, $keyword) !== FALSE) {
34
        $comment->setPublished(FALSE);
35 36 37 38 39 40 41 42 43
        $comment->save();
        break;
      }
    }
  }

  /**
   * {@inheritdoc}
   */
44
  public function defaultConfiguration() {
45 46 47 48 49 50 51 52
    return array(
      'keywords' => array(),
    );
  }

  /**
   * {@inheritdoc}
   */
53
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
54 55 56 57
    $form['keywords'] = array(
      '#title' => t('Keywords'),
      '#type' => 'textarea',
      '#description' => t('The comment will be unpublished if it contains any of the phrases above. Use a case-sensitive, comma-separated list of phrases. Example: funny, bungee jumping, "Company, Inc."'),
58
      '#default_value' => Tags::implode($this->configuration['keywords']),
59 60 61 62 63 64 65
    );
    return $form;
  }

  /**
   * {@inheritdoc}
   */
66
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
67
    $this->configuration['keywords'] = Tags::explode($form_state->getValue('keywords'));
68 69
  }

70 71 72 73 74 75 76 77 78 79 80
  /**
   * {@inheritdoc}
   */
  public function access($object, AccountInterface $account = NULL, $return_as_object = FALSE) {
    /** @var \Drupal\comment\CommentInterface $object */
    $result = $object->access('update', $account, TRUE)
      ->andIf($object->status->access('edit', $account, TRUE));

    return $return_as_object ? $result : $result->isAllowed();
  }

81
}