Provide a ContentEntityNormalizer with an option to explicity include columns.

This commit is contained in:
Michael Stenta 2024-01-22 07:35:16 -05:00
parent 5fcb89a16f
commit 410da5d812
2 changed files with 49 additions and 0 deletions

View File

@ -0,0 +1,6 @@
services:
farm_csv.normalizer.content_entity_normalizer:
class: Drupal\farm_csv\Normalizer\ContentEntityNormalizer
tags:
- { name: normalizer, priority: 10 }
arguments: ['@entity_type.manager', '@entity_type.repository', '@entity_field.manager']

View File

@ -0,0 +1,43 @@
<?php
namespace Drupal\farm_csv\Normalizer;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\serialization\Normalizer\ContentEntityNormalizer as CoreContentEntityNormalizer;
/**
* Normalizes farmOS content entities for CSV exports.
*/
class ContentEntityNormalizer extends CoreContentEntityNormalizer {
/**
* The supported format.
*/
const FORMAT = 'csv';
/**
* {@inheritdoc}
*/
public function normalize($entity, $format = NULL, array $context = []): array|string|int|float|bool|\ArrayObject|NULL {
$data = parent::normalize($entity, $format, $context);
// If columns were explicitly included, remove others.
if (!empty($context['include_columns'])) {
foreach (array_keys($data) as $key) {
if (!in_array($key, $context['include_columns'])) {
unset($data[$key]);
}
}
}
return $data;
}
/**
* {@inheritdoc}
*/
public function supportsNormalization($data, string $format = NULL, array $context = []): bool {
return $data instanceof ContentEntityInterface && $format == static::FORMAT;
}
}