Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
namespace Drupal\bullseye_api\Normalizer;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\node\Entity\Node;
/**
* Custom Normalization for Benefit entities.
*/
class BenefitDenormalizer extends DenormalizerInterface {
protected $supportedInterfaceOrClass = 'Drupal\Core\TypedData\TypedDataInterface';
public function supportsDenormalization($data, $class, $format = null, array $context = array()) {
// If we aren't dealing with an object or the format is not supported return now.
if (!is_array($data) || !$this->checkFormat($format)) {
return FALSE;
}
// This custom normalizer should be supported for Article bundle for the Node Entity.
if ( $class instanceOf Node ) {
return $this->hasRequiredFields($data); // You could perform a check to make sure we are getting what we expect..
}
// Otherwise, this normalizer does not support the $data object.
return FALSE;
}
/**
* {@inheritdoc}
*/
public function denormalize($data, $class, $format = null, array $context = array()) {
$data = [];
$entity = FALSE;
if ($data['id']) {
// Load and update the entity, return it.
$entity = entity_load('node', $data['id']);
....
}
else {
// Create a new entity.
$data = [
'id' => $entity->id(),
'type' => $entity->bundle(),
'title' => $entity->title->value,
'summary' => $entity->body->summary,
...
];
$entity = Node::create($data);
}
return $entity;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment