3 namespace Drupal\hal\Normalizer;
5 use Drupal\Core\Entity\EntityManagerInterface;
6 use Drupal\Core\Extension\ModuleHandlerInterface;
7 use Drupal\hal\LinkManager\LinkManagerInterface;
8 use GuzzleHttp\ClientInterface;
11 * Converts the Drupal entity object structure to a HAL array structure.
13 class FileEntityNormalizer extends ContentEntityNormalizer {
16 * The interface or class that this Normalizer supports.
20 protected $supportedInterfaceOrClass = 'Drupal\file\FileInterface';
25 * @var \GuzzleHttp\ClientInterface
27 protected $httpClient;
30 * Constructs a FileEntityNormalizer object.
32 * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
34 * @param \GuzzleHttp\ClientInterface $http_client
36 * @param \Drupal\hal\LinkManager\LinkManagerInterface $link_manager
37 * The hypermedia link manager.
38 * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
41 public function __construct(EntityManagerInterface $entity_manager, ClientInterface $http_client, LinkManagerInterface $link_manager, ModuleHandlerInterface $module_handler) {
42 parent::__construct($link_manager, $entity_manager, $module_handler);
44 $this->httpClient = $http_client;
50 public function normalize($entity, $format = NULL, array $context = []) {
51 $data = parent::normalize($entity, $format, $context);
52 // Replace the file url with a full url for the file.
53 $data['uri'][0]['value'] = $this->getEntityUri($entity);
61 public function denormalize($data, $class, $format = NULL, array $context = []) {
62 $file_data = (string) $this->httpClient->get($data['uri'][0]['value'])->getBody();
64 $path = 'temporary://' . drupal_basename($data['uri'][0]['value']);
65 $data['uri'] = file_unmanaged_save_data($file_data, $path);
67 return $this->entityManager->getStorage('file')->create($data);