混淆的電子郵件格式化程式

在我們的示例中,我們將為電子郵件地址建立一個自定義格式化程式,這將允許我們顯示模糊的電子郵件地址,以欺騙那些討厭的垃圾郵件傳送者。

格式化程式將有一些配置選項,允許我們控制電子郵件地址的混淆方式:

  • 刪除 @和。並用空格替換它們,
  • 用和替換 @。按點,

請注意,這只是一個學術示例,用於說明欄位格式化程式的顯示和配置方式,對於實際的反垃圾郵件顯然不是很有用。

此示例假定你已正確配置並啟用名為 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;
  }
}