You are here

public function ShowEmailAddress::viewElements in Show Email Address 8

Builds a renderable array for a field value.

Parameters

\Drupal\Core\Field\FieldItemListInterface $items: The field values to be rendered.

string $langcode: The language that should be used to render the field.

Return value

array A renderable array for $items, as an array of child elements keyed by consecutive numeric indexes starting from 0.

Overrides FormatterInterface::viewElements

File

src/Plugin/Field/FieldFormatter/ShowEmailAddress.php, line 92

Class

ShowEmailAddress
Plugin implementation of the 'show_email_address' formatter.

Namespace

Drupal\show_email\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $elements = [];
  $user_one = $this
    ->getSetting('hide_user_one');
  $hide_per_role = $this
    ->getSetting('hide_per_role');
  $roles_to_hide = [];
  $i = 0;

  // Refactor the hidden roles array so I can compare with ::getRoles().
  foreach ($hide_per_role as $label) {
    $i++;
    if (!is_numeric($label)) {
      $roles_to_hide[$i] = $label;
    }
  }
  foreach ($items as $delta => $item) {

    // Load the user attached to this entity.
    $current_user = user_load_by_mail($item->value);

    // If this is userone and its selected be hidden then lets hide it.
    if (1 == $current_user
      ->id() && 1 == $user_one) {
      $elements = [];
    }
    elseif (count(array_intersect($roles_to_hide, $current_user
      ->getRoles()))) {
      $elements = [];
    }
    else {
      $elements[$delta] = [
        '#markup' => 1 == $this
          ->getSetting('email_mailto') ? '<a href=mailto:' . $item->value . '>' . $item->value . '</a>' : $item->value,
      ];
    }
  }
  return $elements;
}