FieldTimerJsFormatterBase.php in Field Timer 8
File
src/Plugin/Field/FieldFormatter/FieldTimerJsFormatterBase.php
View source
<?php
namespace Drupal\field_timer\Plugin\Field\FieldFormatter;
use Drupal\Component\Utility\Crypt;
use Drupal\Core\Field\FieldItemInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;
abstract class FieldTimerJsFormatterBase extends FormatterBase {
const LIBRARY_NAME = '';
const JS_KEY = '';
protected $itemKeys;
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
$elements['#attached']['library'][] = 'field_timer/' . static::LIBRARY_NAME;
$elements['#attached']['library'][] = 'field_timer/init';
$elements['#attached']['drupalSettings']['field_timer'] = $this
->generateJsSettings($items, $langcode);
return $elements;
}
protected function getItemKeys(FieldItemListInterface $items) {
$entity = $items
->getEntity();
if (!isset($this->itemKeys[$entity
->getEntityTypeId()][$entity
->id()][$items
->getFieldDefinition()
->getName()])) {
$entity = $items
->getEntity();
$this->itemKeys = [];
foreach ($items as $delta => $item) {
$this->itemKeys[$entity
->getEntityTypeId()][$entity
->id()][$items
->getFieldDefinition()
->getName()][$delta] = implode('-', [
$entity
->getEntityTypeId(),
$entity
->id(),
$items
->getFieldDefinition()
->getName(),
$delta,
Crypt::randomBytesBase64(8),
]);
}
}
return $this->itemKeys[$entity
->getEntityTypeId()][$entity
->id()][$items
->getFieldDefinition()
->getName()] ?? [];
}
protected function generateJsSettings(FieldItemListInterface $items, $langcode) {
$keys = $this
->getItemKeys($items);
$js_settings = [];
foreach ($items as $delta => $item) {
$timestamp = $this
->getTimestamp($item);
if ($timestamp !== NULL) {
$js_settings[$keys[$delta]]['settings'] = $this
->preparePluginSettings($item, $langcode);
$js_settings[$keys[$delta]]['plugin'] = static::JS_KEY;
}
}
return $js_settings;
}
protected function getTimestamp(FieldItemInterface $item) {
if (!empty($item->date)) {
return $item->date
->getTimestamp();
}
return NULL;
}
protected abstract function preparePluginSettings(FieldItemInterface $item, $langcode);
}