Version 1
[yaffs-website] / web / core / modules / hal / src / Normalizer / FileEntityNormalizer.php
1 <?php
2
3 namespace Drupal\hal\Normalizer;
4
5 use Drupal\Core\Entity\EntityManagerInterface;
6 use Drupal\Core\Extension\ModuleHandlerInterface;
7 use Drupal\hal\LinkManager\LinkManagerInterface;
8 use GuzzleHttp\ClientInterface;
9
10 /**
11  * Converts the Drupal entity object structure to a HAL array structure.
12  */
13 class FileEntityNormalizer extends ContentEntityNormalizer {
14
15   /**
16    * The interface or class that this Normalizer supports.
17    *
18    * @var string
19    */
20   protected $supportedInterfaceOrClass = 'Drupal\file\FileInterface';
21
22   /**
23    * The HTTP client.
24    *
25    * @var \GuzzleHttp\ClientInterface
26    */
27   protected $httpClient;
28
29   /**
30    * Constructs a FileEntityNormalizer object.
31    *
32    * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
33    *   The entity manager.
34    * @param \GuzzleHttp\ClientInterface $http_client
35    *   The HTTP Client.
36    * @param \Drupal\hal\LinkManager\LinkManagerInterface $link_manager
37    *   The hypermedia link manager.
38    * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
39    *   The module handler.
40    */
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);
43
44     $this->httpClient = $http_client;
45   }
46
47   /**
48    * {@inheritdoc}
49    */
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);
54
55     return $data;
56   }
57
58   /**
59    * {@inheritdoc}
60    */
61   public function denormalize($data, $class, $format = NULL, array $context = []) {
62     $file_data = (string) $this->httpClient->get($data['uri'][0]['value'])->getBody();
63
64     $path = 'temporary://' . drupal_basename($data['uri'][0]['value']);
65     $data['uri'] = file_unmanaged_save_data($file_data, $path);
66
67     return $this->entityManager->getStorage('file')->create($data);
68   }
69
70 }