FileEntityNormalizer.php in Zircon Profile 8
File
core/modules/hal/src/Normalizer/FileEntityNormalizer.php
View source
<?php
namespace Drupal\hal\Normalizer;
use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\rest\LinkManager\LinkManagerInterface;
use GuzzleHttp\ClientInterface;
class FileEntityNormalizer extends ContentEntityNormalizer {
protected $supportedInterfaceOrClass = 'Drupal\\file\\FileInterface';
protected $httpClient;
public function __construct(EntityManagerInterface $entity_manager, ClientInterface $http_client, LinkManagerInterface $link_manager, ModuleHandlerInterface $module_handler) {
parent::__construct($link_manager, $entity_manager, $module_handler);
$this->httpClient = $http_client;
}
public function normalize($entity, $format = NULL, array $context = array()) {
$data = parent::normalize($entity, $format, $context);
$data['uri'][0]['value'] = $this
->getEntityUri($entity);
return $data;
}
public function denormalize($data, $class, $format = NULL, array $context = array()) {
$file_data = (string) $this->httpClient
->get($data['uri'][0]['value'])
->getBody();
$path = 'temporary://' . drupal_basename($data['uri'][0]['value']);
$data['uri'] = file_unmanaged_save_data($file_data, $path);
return $this->entityManager
->getStorage('file')
->create($data);
}
}