FieldTemplateProcessor.php in UI Patterns 8
File
modules/ui_patterns_ds/src/FieldTemplateProcessor.php
View source
<?php
namespace Drupal\ui_patterns_ds;
use Drupal\Core\Entity\ContentEntityBase;
class FieldTemplateProcessor implements FieldTemplateProcessorInterface {
protected $variables = [];
public function process(array &$variables) {
$this->variables = $variables;
$content = [];
foreach ($variables['items'] as $delta => $item) {
$fields = [];
foreach ($this
->getMapping() as $mapping) {
$fields[$mapping['destination']][] = $this
->getSourceValue($mapping, $delta);
}
$content['pattern_' . $delta] = [
'#type' => 'pattern',
'#id' => $this
->getPatternId(),
'#variant' => $this
->getVariant(),
'#fields' => $fields,
'#context' => $this
->getContext(),
'#multiple_sources' => TRUE,
];
}
$variables['pattern'] = $content;
}
public function getSourceValue(array $mapping, $delta) {
$value = $this->variables['items'][$delta]['content'];
if ($mapping['source'] != $this
->getFieldName()) {
$column = $this
->getColumnName($mapping['source']);
$value = $this
->getEntity()
->get($this
->getFieldName())
->getValue();
$value = $value[$delta][$column];
}
return $value;
}
protected function getEntity() {
return $this->variables['element']['#object'];
}
protected function getPatternId() {
return $this
->getSetting('pattern');
}
protected function getMapping() {
return $this
->getSetting('pattern_mapping', []);
}
protected function getVariant() {
return $this
->getSetting('pattern_variant');
}
protected function getSetting($name, $default = '') {
return isset($this->variables['ds-config']['settings'][$name]) ? $this->variables['ds-config']['settings'][$name] : $default;
}
protected function getFieldName() {
return $this->variables['field_name'];
}
protected function getColumnName($source) {
return str_replace($this
->getFieldName() . '__', '', $source);
}
protected function getContext() {
$element = $this->variables['element'];
$context = [
'type' => 'ds_field_template',
'field_name' => $this
->getFieldName(),
'entity_type' => $element['#entity_type'],
'bundle' => $element['#bundle'],
'view_mode' => $element['#view_mode'],
'entity' => NULL,
];
if (isset($element['#object']) && is_object($element['#object']) && $element['#object'] instanceof ContentEntityBase) {
$context['entity'] = $element['#object'];
}
return $context;
}
}