Created
May 18, 2018 22:18
-
-
Save cmcintosh/c8aef1062d3a5036c3b8de0e2aa84b1e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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