public function FileEntityNormalizer::denormalize in Better Normalizers 8
Implements \Symfony\Component\Serializer\Normalizer\DenormalizerInterface::denormalize().
Parameters
array $data: Entity data to restore.
string $class: Unused parameter.
string $format: Format the given data was extracted from.
array $context: Options available to the denormalizer. Keys that can be used:
- request_method: if set to "patch" the denormalization will clear out all default values for entity fields before applying $data to the entity.
Return value
\Drupal\Core\Entity\EntityInterface An unserialized entity object containing the data in $data.
Throws
\Symfony\Component\Serializer\Exception\UnexpectedValueException
Overrides ContentEntityNormalizer::denormalize
File
- src/
Normalizer/ FileEntityNormalizer.php, line 56
Class
- FileEntityNormalizer
- Normalizer for File entity.
Namespace
Drupal\better_normalizers\NormalizerCode
public function denormalize($data, $class, $format = NULL, array $context = array()) {
// Avoid 'data' being treated as a field.
$file_data = $data['data'][0]['value'];
unset($data['data']);
// Decode and save to file.
$file_contents = base64_decode($file_data);
$entity = parent::denormalize($data, $class, $format, $context);
$dirname = $this->fileSystem
->dirname($entity
->getFileUri());
$this->fileSystem
->prepareDirectory($dirname, FileSystemInterface::CREATE_DIRECTORY);
if ($uri = $this->fileSystem
->saveData($file_contents, $entity
->getFileUri())) {
$entity
->setFileUri($uri);
}
else {
throw new \RuntimeException(sprintf('Failed to write %s.', $entity
->getFilename()));
}
return $entity;
}