cefrl-1.0.0-beta1/src/Plugin/Field/FieldFormatter/CEFRLLevelDefaultFormatter.php
src/Plugin/Field/FieldFormatter/CEFRLLevelDefaultFormatter.php
<?php
namespace Drupal\cefrl\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\cefrl\CEFRLOptionsInterface;
use Drupal\cefrl\Plugin\Field\FieldType\CEFRLLevelItem;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Plugin implementation of the 'cefrl_default' formatter.
*
* @FieldFormatter(
* id = "cefrl_default",
* label = @Translation("Default"),
* field_types = {"cefrl"}
* )
*/
class CEFRLLevelDefaultFormatter extends FormatterBase implements ContainerFactoryPluginInterface {
/**
* The CEFRL Options service.
*
* @var \Drupal\cefrl\CEFRLOptionsInterface
*/
protected $cefrlOptions;
/**
* {@inheritdoc}
*/
public function __construct(
$plugin_id,
$plugin_definition,
FieldDefinitionInterface $field_definition,
array $settings,
$label,
$view_mode,
array $third_party_settings,
CEFRLOptionsInterface $cefrl_options
) {
parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings);
$this->cefrlOptions = $cefrl_options;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$plugin_id,
$plugin_definition,
$configuration['field_definition'],
$configuration['settings'],
$configuration['label'],
$configuration['view_mode'],
$configuration['third_party_settings'],
$container->get('cefrl.options')
);
}
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
$element = [];
foreach ($items as $delta => $item) {
if ($item->level) {
$element[$delta][CEFRLLevelItem::CEFRL_LEVEL] = [
'#markup' => $this->getProcessedLabel($item->level),
];
}
}
return $element;
}
/**
* Helper method to provide a processed label.
*
* @param string $key
* The key for which to retrieve a processed label.
*
* @return string
* The processsed label.
*/
protected function getProcessedLabel(string $key): string {
$label = $this->cefrlOptions->getLabel($key);
$processed = (!empty($label)) ? implode(' - ', [$key, $label]) : $key;
if ($this->isNativeSpeaker($key)) {
$processed = $label;
}
return $processed;
}
/**
* Helper method to handle the 'Native speaker' pseudo-level label.
*
* @param string $key
* The key to check.
*
* @return bool
* Whether the key corresponds to the 'Native speaker' pseudo-level.
*/
protected function isNativeSpeaker(string $key): bool {
$native_speaker = $this->cefrlOptions->getNativeSpeakerOption();
return (array_key_exists($key, $native_speaker));
}
}
