CommentPermalinkFormatter.php 1.52 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
<?php

namespace Drupal\comment\Plugin\Field\FieldFormatter;

use Drupal\Component\Utility\Unicode;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\Plugin\Field\FieldFormatter\StringFormatter;

/**
 * Plugin implementation of the 'comment_permalink' formatter.
 *
 * All the other entities use 'canonical' or 'revision' links to link the entity
 * to itself but comments use permalink URL.
 *
 * @FieldFormatter(
 *   id = "comment_permalink",
 *   label = @Translation("Comment Permalink"),
 *   field_types = {
 *     "string",
 *     "uri",
 *   },
 *   quickedit = {
 *     "editor" = "plain_text"
 *   }
 * )
 */
class CommentPermalinkFormatter extends StringFormatter {

  /**
   * {@inheritdoc}
   */
  protected function getEntityUrl(EntityInterface $comment) {
    /* @var $comment \Drupal\comment\CommentInterface */
    $comment_permalink = $comment->permalink();
    if ($comment->hasField('comment_body') && ($body = $comment->get('comment_body')->value)) {
      $attributes = $comment_permalink->getOption('attributes') ?: [];
      $attributes += ['title' => Unicode::truncate($body, 128)];
      $comment_permalink->setOption('attributes', $attributes);
    }
    return $comment_permalink;
  }

  /**
   * {@inheritdoc}
   */
  public static function isApplicable(FieldDefinitionInterface $field_definition) {
    return parent::isApplicable($field_definition) && $field_definition->getTargetEntityTypeId() === 'comment' && $field_definition->getName() === 'subject';
  }

}