You are here

function _entity_class_formatter_apply in Entity Class Formatter 8

Applies all field values using defined settings.

1 call to _entity_class_formatter_apply()
entity_class_formatter_entity_view_alter in ./entity_class_formatter.module
Implements hook_entity_view_alter().

File

./entity_class_formatter.module, line 77
Entity Class Formatter module.

Code

function _entity_class_formatter_apply(array &$build, FieldItemListInterface $field, array $settings) {
  $values = [];
  $field_definition = $field
    ->getFieldDefinition();

  // Get prefix to be attached before.
  $prefix = !empty($settings['prefix']) ? $settings['prefix'] : '';

  // Get suffix to be attached after.
  $suffix = !empty($settings['suffix']) ? $settings['suffix'] : '';

  // Get attribute name (class by default).
  $attr = !empty($settings['attr']) ? $settings['attr'] : 'class';

  // Only for entity reference field type.
  if ($field instanceof EntityReferenceFieldItemListInterface) {
    foreach ($field
      ->referencedEntities() as $referenced_entity) {

      // Fill title if not empty.
      $title = $referenced_entity
        ->label();
      if (!empty($title)) {
        $values[] = $prefix . $title . $suffix;
      }
    }
  }
  elseif ($field_definition
    ->getType() === 'boolean') {

    // Fill configured label based on value.
    if (filter_var($field->value, FILTER_VALIDATE_BOOLEAN)) {
      $label = $field_definition
        ->getSetting('on_label');
    }
    else {
      $label = $field_definition
        ->getSetting('off_label');
    }
    $values[] = $prefix . $label . $suffix;
  }
  else {
    foreach ($field
      ->getValue() as $item) {

      // Fill value if not empty.
      if (!empty($item['value'])) {

        // Split value into multiple classes when spaces are used.
        if ($attr === 'class') {
          foreach (explode(' ', $item['value']) as $class) {
            $values[] = $prefix . $class . $suffix;
          }
        }
        else {

          // Provide other attribute value as it is.
          $values[] = $prefix . $item['value'] . $suffix;
        }
      }
    }
  }

  // Process all discovered values.
  $method = $attr === 'class' ? 'getClass' : 'escape';
  foreach ($values as $value) {
    $build['#attributes'][$attr][] = Html::$method($value);
  }
}