View source
<?php
namespace Drupal\bibcite_entity\Normalizer;
use Drupal\bibcite_entity\Entity\ReferenceInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Symfony\Component\Serializer\Exception\LogicException;
class CslReferenceNormalizer extends ReferenceNormalizerBase {
protected $dateFields = [
'bibcite_year',
'bibcite_access_date',
'bibcite_date',
];
public function supportsDenormalization($data, $type, $format = NULL) {
return FALSE;
}
public function denormalize($data, $class, $format = NULL, array $context = []) {
throw new LogicException("Cannot denormalize from 'CSL' format.");
}
public function normalize($reference, $format = NULL, array $context = []) {
$attributes = parent::normalize($reference, $format, $context);
$contributor_key = $this
->getContributorKey();
if (isset($attributes[$contributor_key])) {
$authors = $attributes[$contributor_key];
foreach ($authors as $role => $contributors) {
$attributes[$role] = $contributors;
}
}
return $attributes;
}
protected function extractFields(ReferenceInterface $reference, $format = NULL) {
$attributes = [];
$attributes['title'] = $this
->extractScalar($reference
->get('title'));
foreach ($this->fieldsMapping[$this->format] as $csl_field => $entity_field) {
if ($entity_field && $reference
->hasField($entity_field) && ($field = $reference
->get($entity_field)) && !$field
->isEmpty()) {
if (in_array($entity_field, $this->dateFields)) {
$attributes[$csl_field] = $this
->extractDate($field);
}
else {
$attributes[$csl_field] = $this
->extractScalar($field);
}
}
}
return $attributes;
}
protected function extractAuthors(FieldItemListInterface $field_item_list) {
$authors = [];
foreach ($field_item_list as $field) {
if ($contributor = $field->entity) {
switch ($field->role) {
case 'editor':
case 'series_editor':
$authors['editor'][] = [
'category' => $field->category,
'role' => $field->role,
'family' => $contributor
->getLastName(),
'given' => $contributor
->getFirstName() . ' ' . $contributor
->getMiddleName(),
'suffix' => $contributor
->getSuffix(),
'literal' => $contributor
->getName(),
];
break;
case 'recipient':
case 'translator':
$authors[$field->role][] = [
'category' => $field->category,
'role' => $field->role,
'family' => $contributor
->getLastName(),
'given' => $contributor
->getFirstName() . ' ' . $contributor
->getMiddleName(),
'suffix' => $contributor
->getSuffix(),
'literal' => $contributor
->getName(),
];
break;
default:
$authors['author'][] = [
'category' => $field->category,
'role' => $field->role,
'family' => $contributor
->getLastName(),
'given' => $contributor
->getFirstName() . ' ' . $contributor
->getMiddleName(),
'suffix' => $contributor
->getSuffix(),
'literal' => $contributor
->getName(),
];
break;
}
}
}
return $authors;
}
protected function extractDate(FieldItemListInterface $date_field) {
$value = $this
->extractScalar($date_field);
return [
'date-parts' => [
[
$value,
],
],
'literal' => $value,
];
}
}