You are here

class SmartTrimFormatter in Smart Trim 8

Plugin implementation of the 'smart_trim' formatter.

Plugin annotation


@FieldFormatter(
  id = "smart_trim",
  label = @Translation("Smart trimmed"),
  field_types = {
    "text",
    "text_long",
    "text_with_summary",
    "string",
    "string_long"
  },
  settings = {
    "trim_length" = "300",
    "trim_type" = "chars",
    "trim_suffix" = "...",
    "more_link" = FALSE,
    "more_text" = "Read more",
    "summary_handler" = "full",
    "trim_options" = ""
  }
)

Hierarchy

Expanded class hierarchy of SmartTrimFormatter

File

src/Plugin/Field/FieldFormatter/SmartTrimFormatter.php, line 34

Namespace

Drupal\smart_trim\Plugin\Field\FieldFormatter
View source
class SmartTrimFormatter extends FormatterBase {

  /**
   * {@inheritdoc}
   */
  public static function defaultSettings() {
    return [
      'trim_length' => '600',
      'trim_type' => 'chars',
      'trim_suffix' => '',
      'wrap_output' => 0,
      'wrap_class' => 'trimmed',
      'more_link' => 0,
      'more_class' => 'more-link',
      'more_text' => 'More',
      'more_aria_label' => 'Read more about [node:title]',
      'summary_handler' => 'full',
      'trim_options' => [],
    ] + parent::defaultSettings();
  }

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state) {
    $element = parent::settingsForm($form, $form_state);
    $element['trim_length'] = [
      '#title' => $this
        ->t('Trim length'),
      '#type' => 'textfield',
      '#size' => 10,
      '#default_value' => $this
        ->getSetting('trim_length'),
      '#min' => 0,
      '#required' => TRUE,
    ];
    $element['trim_type'] = [
      '#title' => $this
        ->t('Trim units'),
      '#type' => 'select',
      '#options' => [
        'chars' => $this
          ->t("Characters"),
        'words' => $this
          ->t("Words"),
      ],
      '#default_value' => $this
        ->getSetting('trim_type'),
    ];
    $element['trim_suffix'] = [
      '#title' => $this
        ->t('Suffix'),
      '#type' => 'textfield',
      '#size' => 10,
      '#default_value' => $this
        ->getSetting('trim_suffix'),
    ];
    $element['wrap_output'] = [
      '#title' => $this
        ->t('Wrap trimmed content?'),
      '#type' => 'checkbox',
      '#default_value' => $this
        ->getSetting('wrap_output'),
      '#description' => $this
        ->t('Adds a wrapper div to trimmed content.'),
    ];
    $element['wrap_class'] = [
      '#title' => $this
        ->t('Wrapped content class.'),
      '#type' => 'textfield',
      '#size' => 20,
      '#default_value' => $this
        ->getSetting('wrap_class'),
      '#description' => $this
        ->t('If wrapping, define the class name here.'),
      '#states' => [
        'visible' => [
          ':input[name="fields[body][settings_edit_form][settings][wrap_output]"]' => [
            'checked' => TRUE,
          ],
        ],
      ],
    ];
    $element['more_link'] = [
      '#title' => $this
        ->t('Display more link?'),
      '#type' => 'checkbox',
      '#default_value' => $this
        ->getSetting('more_link'),
      '#description' => $this
        ->t('Displays a link to the entity (if one exists)'),
    ];
    $element['more_text'] = [
      '#title' => $this
        ->t('More link text'),
      '#type' => 'textfield',
      '#size' => 20,
      '#default_value' => $this
        ->getSetting('more_text'),
      '#description' => $this
        ->t('If displaying more link, enter the text for the link.'),
      '#states' => [
        'visible' => [
          ':input[name="fields[body][settings_edit_form][settings][more_link]"]' => [
            'checked' => TRUE,
          ],
        ],
      ],
    ];
    $element['more_aria_label'] = [
      '#title' => $this
        ->t('More link aria-label'),
      '#type' => 'textfield',
      '#size' => 30,
      '#default_value' => $this
        ->getSetting('more_aria_label'),
      '#description' => $this
        ->t('If displaying more link, provide additional context for screen-reader users. Tokens supported. In most cases, the aria-label value will be announced instead of the link text.'),
      '#states' => [
        'visible' => [
          ':input[name="fields[body][settings_edit_form][settings][more_link]"]' => [
            'checked' => TRUE,
          ],
        ],
      ],
    ];
    $element['token_browser'] = [
      '#type' => 'item',
      '#theme' => 'token_tree_link',
      '#token_types' => [
        $this->fieldDefinition
          ->getTargetEntityTypeId(),
      ],
      '#states' => [
        'visible' => [
          ':input[name="fields[body][settings_edit_form][settings][more_link]"]' => [
            'checked' => TRUE,
          ],
        ],
      ],
    ];
    $element['more_class'] = [
      '#title' => $this
        ->t('More link class'),
      '#type' => 'textfield',
      '#size' => 20,
      '#default_value' => $this
        ->getSetting('more_class'),
      '#description' => $this
        ->t('If displaying more link, add a custom class for formatting.'),
      '#states' => [
        'visible' => [
          ':input[name="fields[body][settings_edit_form][settings][more_link]"]' => [
            'checked' => TRUE,
          ],
        ],
      ],
    ];
    if ($this->fieldDefinition
      ->getType() == 'text_with_summary') {
      $element['summary_handler'] = [
        '#title' => $this
          ->t('Summary'),
        '#type' => 'select',
        '#options' => [
          'full' => $this
            ->t("Use summary if present, and do not trim"),
          'trim' => $this
            ->t("Use summary if present, honor trim settings"),
          'ignore' => $this
            ->t("Do not use summary"),
        ],
        '#default_value' => $this
          ->getSetting('summary_handler'),
      ];
    }
    $trim_options_value = $this
      ->getSetting('trim_options');
    $element['trim_options'] = [
      '#title' => $this
        ->t('Additional options'),
      '#type' => 'checkboxes',
      '#options' => [
        'text' => $this
          ->t('Strip HTML'),
        'trim_zero' => $this
          ->t('Honor a zero trim length'),
      ],
      '#default_value' => empty($trim_options_value) ? [] : array_keys(array_filter($trim_options_value)),
    ];
    return $element;
  }

  /**
   * {@inheritdoc}
   */
  public function settingsSummary() {
    $summary = [];
    $type = $this
      ->t('words');
    if ($this
      ->getSetting('trim_type') == 'chars') {
      $type = $this
        ->t('characters');
    }
    $trim_string = $this
      ->getSetting('trim_length') . ' ' . $type;
    if (mb_strlen(trim($this
      ->getSetting('trim_suffix')))) {
      $trim_string .= " " . $this
        ->t("with suffix");
    }
    if ($this
      ->getSetting('more_link')) {
      $trim_string .= ", " . $this
        ->t("with more link");
    }
    $summary[] = $trim_string;
    return $summary;
  }

  /**
   * {@inheritdoc}
   */
  public function viewElements(FieldItemListInterface $items, $langcode = NULL) {
    $element = [];
    $setting_trim_options = $this
      ->getSetting('trim_options');
    $settings_summary_handler = $this
      ->getSetting('summary_handler');
    $entity = $items
      ->getEntity();
    foreach ($items as $delta => $item) {
      if ($settings_summary_handler != 'ignore' && !empty($item->summary)) {
        $output = $item->summary;
      }
      else {
        $output = $item->value;
      }

      // Process additional options (currently only HTML on/off).
      if (!empty($setting_trim_options)) {

        // Allow a zero length trim.
        if (!empty($setting_trim_options['trim_zero']) && $this
          ->getSetting('trim_length') == 0) {

          // If the summary is empty, trim to zero length.
          if (empty($item->summary)) {
            $output = '';
          }
          elseif ($settings_summary_handler != 'full') {
            $output = '';
          }
        }
        if (!empty($setting_trim_options['text'])) {

          // Strip caption.
          $output = preg_replace('/<figcaption[^>]*>.*?<\\/figcaption>/is', ' ', $output);

          // Strip script.
          $output = preg_replace('/<script[^>]*>.*?<\\/script>/is', ' ', $output);

          // Strip style.
          $output = preg_replace('/<style[^>]*>.*?<\\/style>/is', ' ', $output);

          // Strip tags.
          $output = strip_tags($output);

          // Strip out line breaks.
          $output = preg_replace('/\\n|\\r|\\t/m', ' ', $output);

          // Strip out non-breaking spaces.
          $output = str_replace('&nbsp;', ' ', $output);
          $output = str_replace(" ", ' ', $output);

          // Strip out extra spaces.
          $output = trim(preg_replace('/\\s\\s+/', ' ', $output));
        }
      }

      // Make the trim, provided we're not showing a full summary.
      if ($this
        ->getSetting('summary_handler') != 'full' || empty($item->summary)) {
        $truncate = new TruncateHTML();
        $length = $this
          ->getSetting('trim_length');
        $ellipse = $this
          ->getSetting('trim_suffix');
        if ($this
          ->getSetting('trim_type') == 'words') {
          $output = $truncate
            ->truncateWords($output, $length, $ellipse);
        }
        else {
          $output = $truncate
            ->truncateChars($output, $length, $ellipse);
        }
      }
      $element[$delta] = [
        '#type' => 'processed_text',
        '#text' => $output,
        '#format' => $item->format,
      ];

      // Wrap content in container div.
      if ($this
        ->getSetting('wrap_output')) {
        $element[$delta]['#prefix'] = '<div class="' . $this
          ->getSetting('wrap_class') . '">';
        $element[$delta]['#suffix'] = '</div>';
      }

      // Add the link, if there is one!
      // The entity must have an id already. Content entities usually get their
      // IDs by saving them. In some cases, eg: Inline Entity Form preview there
      // is no ID until everything is saved.
      // https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Entity!Entity.php/function/Entity%3A%3AtoUrl/8.2.x
      if ($this
        ->getSetting('more_link') && $entity
        ->id() && $entity
        ->hasLinkTemplate('canonical')) {

        // But wait! Don't add a more link if the field ends in <!--break-->.
        if (strpos(strrev($output), strrev('<!--break-->')) !== 0) {
          $more = $this
            ->t($this
            ->getSetting('more_text'));
          $class = $this
            ->getSetting('more_class');
          $project_link = $entity
            ->toLink($more)
            ->toRenderable();
          $project_link['#attributes'] = [
            'class' => [
              $class,
            ],
          ];

          // Ensure we don't create an empty aria-label attribute.
          $aria_label = $this
            ->t($this
            ->getSetting('more_aria_label'));
          if ($aria_label) {
            $project_link['#attributes']['aria-label'] = \Drupal::token()
              ->replace($aria_label, [
              $entity
                ->getEntityTypeId() => $entity,
            ]);
          }
          $project_link['#prefix'] = '<div class="' . $class . '">';
          $project_link['#suffix'] = '</div>';
          $element[$delta]['more_link'] = $project_link;
        }
      }
    }
    return $element;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
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
FormatterBase::$fieldDefinition protected property The field definition.
FormatterBase::$label protected property The label display setting.
FormatterBase::$settings protected property The formatter settings. Overrides PluginSettingsBase::$settings
FormatterBase::$viewMode protected property The view mode.
FormatterBase::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create 11
FormatterBase::getFieldSetting protected function Returns the value of a field setting.
FormatterBase::getFieldSettings protected function Returns the array of field settings.
FormatterBase::isApplicable public static function Returns if the formatter can be used for the provided field. Overrides FormatterInterface::isApplicable 14
FormatterBase::prepareView public function Allows formatters to load information for field values being displayed. Overrides FormatterInterface::prepareView 2
FormatterBase::view public function Builds a renderable array for a fully themed field. Overrides FormatterInterface::view 1
FormatterBase::__construct public function Constructs a FormatterBase object. Overrides PluginBase::__construct 11
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
PluginSettingsBase::$defaultSettingsMerged protected property Whether default settings have been merged into the current $settings.
PluginSettingsBase::$thirdPartySettings protected property The plugin settings injected by third party modules.
PluginSettingsBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides DependentPluginInterface::calculateDependencies 6
PluginSettingsBase::getSetting public function Returns the value of a setting, or its default value if absent. Overrides PluginSettingsInterface::getSetting
PluginSettingsBase::getSettings public function Returns the array of settings, including defaults for missing settings. Overrides PluginSettingsInterface::getSettings
PluginSettingsBase::getThirdPartyProviders public function Gets the list of third parties that store information. Overrides ThirdPartySettingsInterface::getThirdPartyProviders
PluginSettingsBase::getThirdPartySetting public function Gets the value of a third-party setting. Overrides ThirdPartySettingsInterface::getThirdPartySetting
PluginSettingsBase::getThirdPartySettings public function Gets all third-party settings of a given module. Overrides ThirdPartySettingsInterface::getThirdPartySettings
PluginSettingsBase::mergeDefaults protected function Merges default settings values into $settings.
PluginSettingsBase::onDependencyRemoval public function Informs the plugin that some configuration it depends on will be deleted. Overrides PluginSettingsInterface::onDependencyRemoval 3
PluginSettingsBase::setSetting public function Sets the value of a setting for the plugin. Overrides PluginSettingsInterface::setSetting
PluginSettingsBase::setSettings public function Sets the settings for the plugin. Overrides PluginSettingsInterface::setSettings
PluginSettingsBase::setThirdPartySetting public function Sets the value of a third-party setting. Overrides ThirdPartySettingsInterface::setThirdPartySetting
PluginSettingsBase::unsetThirdPartySetting public function Unsets a third-party setting. Overrides ThirdPartySettingsInterface::unsetThirdPartySetting
SmartTrimFormatter::defaultSettings public static function Defines the default settings for this plugin. Overrides PluginSettingsBase::defaultSettings
SmartTrimFormatter::settingsForm public function Returns a form to configure settings for the formatter. Overrides FormatterBase::settingsForm
SmartTrimFormatter::settingsSummary public function Returns a short summary for the current formatter settings. Overrides FormatterBase::settingsSummary
SmartTrimFormatter::viewElements public function Builds a renderable array for a field value. Overrides FormatterInterface::viewElements
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.