access_policy-1.0.x-dev/src/LabelHelper.php
src/LabelHelper.php
<?php namespace Drupal\access_policy; /** * Helper class for rending arrays as labels. */ class LabelHelper { /** * Default label options. * * @return array * The default label options. */ protected static function defaultOptions() { return [ 'limit' => 0, 'empty_value' => t('None'), ]; } /** * Render the labels. * * @param array $labels * Array of labels. * @param array $options * Array of label options. * * @return \Drupal\Core\StringTranslation\TranslatableMarkup * The rendered labels. */ public static function render(array $labels, array $options = []) { $options += self::defaultOptions(); if (empty($labels)) { return $options['empty_value']; } $truncated = FALSE; $total = count($labels); $limit = $options['limit']; if ($limit && count($labels) > $limit) { $labels = array_slice($labels, 0, $limit); $truncated = TRUE; } $string = implode(', ', $labels); if ($truncated) { $diff_count = $total - $limit; $string .= "… (" . $diff_count . " more)"; } return $string; } /** * Get a list of entity labels. * * @param array $entities * Array of entities. * @param array $options * Array of label options. * * @return string * The array of entity labels. */ public static function renderEntities(array $entities, array $options = []) { $labels = array_map(function ($entity) { return $entity->label(); }, $entities); return self::render($labels, $options); } }