混淆的电子邮件格式化程序

在我们的示例中,我们将为电子邮件地址创建一个自定义格式化程序,这将允许我们显示模糊的电子邮件地址,以欺骗那些讨厌的垃圾邮件发送者。

格式化程序将有一些配置选项,允许我们控制电子邮件地址的混淆方式:

  • 删除 @和。并用空格替换它们,
  • 用和替换 @。按点,

请注意,这只是一个学术示例,用于说明字段格式化程序的显示和配置方式,对于实际的反垃圾邮件显然不是很有用。

此示例假定你已正确配置并激活名为 obfuscator_field_formatter 的模块。

namespace Drupal\obfuscator_field_formatter\Plugin\Field\FieldFormatter;

use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Plugin implementation of the 'example_field_formatter' formatter.
 *
 * @FieldFormatter(
 *   id = "email_obfuscator_field_formatter",
 *   label = @Translation("Obfuscated Email"),
 *   field_types = {
 *     "email"
 *   }
 * )
 */
class ObfuscatorFieldFormatter extends FormatterBase {
  private $options = [];

  public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, $label, $view_mode, array $third_party_settings) {
    parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings);

    $this->options = [
      'remove_chars' => $this->t('Remove @ and . and replace them with a space'),
      'replace_chars' => $this->t('Replace @ by at and . by dot'),
    ];
  }

  public static function defaultSettings() {
    return [
      'obfuscator_formatter_type' => '',
    ] + parent::defaultSettings();
  }

  public function settingsForm(array $form, FormStateInterface $form_state) {
    return [
      'obfuscator_formatter_type' => [
        '#type' => 'select',
        '#title' => $this->t('Obfuscation Type'),
        '#options' => $this->options,
        '#default_value' => $this->getSetting('obfuscator_formatter_type'),
      ]
    ] + parent::settingsForm($form, $form_state);
  }

  public function settingsSummary() {
    $summary = parent::settingsSummary();
    $type = $this->getSetting('obfuscator_formatter_type');

    if(!is_null($type) && !empty($type)) {
      $summary[] = $this->t('Obfuscation: @value', ['@value' => $this->options[$type]]);
    }

    return $summary;
  }

  public function viewElements(FieldItemListInterface $items, $langcode) {
    $elements = [];

    foreach ($items as $delta => $item) {
      $elements[$delta] = [
        '#type' => 'inline_template',
        '#template' => '{{ value|nl2br }}',
        '#context' => ['value' => $this->viewValue($item)],
      ];
    }

    return $elements;
  }

  protected function viewValue(FieldItemInterface $item) {
    $obfuscated = $item->value;
    $type = $this->getSetting('obfuscator_formatter_type');

    switch($type) {
      case 'remove_chars': {
        $obfuscated = str_ireplace(['@', '.'], ' ', $item->value);
        break;
      }

      case 'replace_chars': {
        $obfuscated = str_ireplace(['@', '.'], [' AT ', ' DOT '], $item->value);
        break;
      }
    }

    return $obfuscated;
  }
}