datafield-1.x-dev/src/Plugin/Field/FieldFormatter/JsonExport.php
src/Plugin/Field/FieldFormatter/JsonExport.php
<?php
namespace Drupal\datafield\Plugin\Field\FieldFormatter;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Field\Attribute\FieldFormatter;
use Drupal\Core\Field\EntityReferenceFieldItemListInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\file\FileInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Plugin implementations for 'html_list' formatter.
*/
#[FieldFormatter(
id: 'data_field_json_export',
label: new TranslatableMarkup('Json export'),
description: new TranslatableMarkup('Use for view Json export'),
field_types: [
'data_field',
],
)]
class JsonExport extends FormatterBase {
/**
* Constructs a FormatterBase object.
*
* @param string $plugin_id
* The plugin_id for the formatter.
* @param mixed $plugin_definition
* The plugin implementation definition.
* @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
* The definition of the field to which the formatter is associated.
* @param array $settings
* The formatter settings.
* @param string $label
* The formatter label display setting.
* @param string $view_mode
* The view mode.
* @param array $third_party_settings
* Any third party settings.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
* Entity type manager service.
*/
public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, $label, $view_mode, array $third_party_settings, protected EntityTypeManagerInterface $entityTypeManager) {
parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings);
}
/**
* {@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('entity_type.manager'),
);
}
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
$fieldSettings = $this->getFieldSetting('field_settings');
$columns = $this->getFieldSetting("columns");
foreach ($items as $delta => $item) {
foreach (array_keys($columns) as $column) {
$value = $item->$column;
if (!empty($value)) {
switch ($columns[$column]['type']) {
case 'entity_reference':
if (is_numeric($value)) {
$storage = $this->entityTypeManager->getStorage($fieldSettings[$column]['entity_reference_type']);
$entity = $storage->load($value);
}
elseif ($value instanceof EntityInterface) {
$entity = $value;
}
if (!empty($entity)) {
$value = $this->serializeEntity($entity, $this->getSetting('recursion_level'));
}
break;
case 'file':
$storage = $this->entityTypeManager->getStorage('file');
$file = $storage->load($value);
if (!empty($file)) {
$value = [];
foreach ($file->getFields() as $name => $field) {
$value[$name] = $field->getString();
}
$value['link'] = $file->createFileUrl();
}
break;
case 'json':
$value = json_decode($value);
break;
}
}
$elements[$delta][$column] = $value;
}
}
return [['#markup' => json_encode($elements)]];
}
/**
* {@inheritdoc}
*/
public function settingsSummary() {
$summary = [];
$summary[] = $this->t('Outputs the field data in JSON format, useful for view export json data.');
$summary[] = $this->t('Recursion max level: @level', ['@level' => $this->getSetting('recursion_level')]);
return $summary;
}
/**
* {@inheritdoc}
*/
public static function defaultSettings(): array {
$setting = ['recursion_level' => 2];
return $setting + parent::defaultSettings();
}
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state): array {
$elements['recursion_level'] = [
'#type' => 'number',
'#title' => $this->t('Recursion max level'),
'#default_value' => $this->getSetting('recursion_level'),
];
return $elements;
}
/**
* {@inheritdoc}
*/
public function serializeEntity($entity, $maxDepth = 1, $depth = 0) {
$data = [];
if ($depth > $maxDepth) {
return $data;
}
if (method_exists($entity, 'getFieldDefinitions')) {
foreach ($entity->getFieldDefinitions() as $field_name => $field_definition) {
if (!$entity->hasField($field_name)) {
continue;
}
$field = $entity->get($field_name);
$fieldDefType = $field->getFieldDefinition()->getType();
if ($fieldDefType == 'password') {
continue;
}
if ($field instanceof EntityReferenceFieldItemListInterface) {
$referenced_entities = $field->referencedEntities();
$data[$field_name] = [];
foreach ($referenced_entities as $referenced_entity) {
$subEntity = $this->serializeEntity($referenced_entity, $maxDepth, $depth + 1);
if (!empty($subEntity)) {
$data[$field_name][] = $subEntity;
}
}
}
elseif (method_exists($field, 'getString')) {
$data[$field_name] = $field->getString();
}
if ($data[$field_name] !== 0 && empty($data[$field_name])) {
unset($data[$field_name]);
}
}
$data['link'] = $this->getEntityUrl($entity);
}
return $data;
}
/**
* {@inheritDoc}
*/
public function getEntityUrl(ContentEntityInterface $entity) {
if ($entity instanceof FileInterface) {
return $entity->createFileUrl();
}
if ($entity->hasLinkTemplate('canonical')) {
return $entity->toUrl()->toString();
}
return NULL;
}
}
