Version 1
[yaffs-website] / web / core / modules / rest / src / Plugin / views / style / Serializer.php
1 <?php
2
3 namespace Drupal\rest\Plugin\views\style;
4
5 use Drupal\Core\Cache\Cache;
6 use Drupal\Core\Cache\CacheableDependencyInterface;
7 use Drupal\Core\Form\FormStateInterface;
8 use Drupal\views\Plugin\views\style\StylePluginBase;
9 use Symfony\Component\DependencyInjection\ContainerInterface;
10 use Symfony\Component\Serializer\SerializerInterface;
11
12 /**
13  * The style plugin for serialized output formats.
14  *
15  * @ingroup views_style_plugins
16  *
17  * @ViewsStyle(
18  *   id = "serializer",
19  *   title = @Translation("Serializer"),
20  *   help = @Translation("Serializes views row data using the Serializer component."),
21  *   display_types = {"data"}
22  * )
23  */
24 class Serializer extends StylePluginBase implements CacheableDependencyInterface {
25
26   /**
27    * {@inheritdoc}
28    */
29   protected $usesRowPlugin = TRUE;
30
31   /**
32    * {@inheritdoc}
33    */
34   protected $usesGrouping = FALSE;
35
36   /**
37    * The serializer which serializes the views result.
38    *
39    * @var \Symfony\Component\Serializer\Serializer
40    */
41   protected $serializer;
42
43   /**
44    * The available serialization formats.
45    *
46    * @var array
47    */
48   protected $formats = [];
49
50   /**
51    * The serialization format providers, keyed by format.
52    *
53    * @var string[]
54    */
55   protected $formatProviders;
56
57   /**
58    * {@inheritdoc}
59    */
60   public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
61     return new static(
62       $configuration,
63       $plugin_id,
64       $plugin_definition,
65       $container->get('serializer'),
66       $container->getParameter('serializer.formats'),
67       $container->getParameter('serializer.format_providers')
68     );
69   }
70
71   /**
72    * Constructs a Plugin object.
73    */
74   public function __construct(array $configuration, $plugin_id, $plugin_definition, SerializerInterface $serializer, array $serializer_formats, array $serializer_format_providers) {
75     parent::__construct($configuration, $plugin_id, $plugin_definition);
76
77     $this->definition = $plugin_definition + $configuration;
78     $this->serializer = $serializer;
79     $this->formats = $serializer_formats;
80     $this->formatProviders = $serializer_format_providers;
81   }
82
83   /**
84    * {@inheritdoc}
85    */
86   protected function defineOptions() {
87     $options = parent::defineOptions();
88     $options['formats'] = ['default' => []];
89
90     return $options;
91   }
92
93   /**
94    * {@inheritdoc}
95    */
96   public function buildOptionsForm(&$form, FormStateInterface $form_state) {
97     parent::buildOptionsForm($form, $form_state);
98
99     $form['formats'] = [
100       '#type' => 'checkboxes',
101       '#title' => $this->t('Accepted request formats'),
102       '#description' => $this->t('Request formats that will be allowed in responses. If none are selected all formats will be allowed.'),
103       '#options' => $this->getFormatOptions(),
104       '#default_value' => $this->options['formats'],
105     ];
106   }
107
108   /**
109    * {@inheritdoc}
110    */
111   public function submitOptionsForm(&$form, FormStateInterface $form_state) {
112     parent::submitOptionsForm($form, $form_state);
113
114     $formats = $form_state->getValue(['style_options', 'formats']);
115     $form_state->setValue(['style_options', 'formats'], array_filter($formats));
116   }
117
118   /**
119    * {@inheritdoc}
120    */
121   public function render() {
122     $rows = [];
123     // If the Data Entity row plugin is used, this will be an array of entities
124     // which will pass through Serializer to one of the registered Normalizers,
125     // which will transform it to arrays/scalars. If the Data field row plugin
126     // is used, $rows will not contain objects and will pass directly to the
127     // Encoder.
128     foreach ($this->view->result as $row_index => $row) {
129       $this->view->row_index = $row_index;
130       $rows[] = $this->view->rowPlugin->render($row);
131     }
132     unset($this->view->row_index);
133
134     // Get the content type configured in the display or fallback to the
135     // default.
136     if ((empty($this->view->live_preview))) {
137       $content_type = $this->displayHandler->getContentType();
138     }
139     else {
140       $content_type = !empty($this->options['formats']) ? reset($this->options['formats']) : 'json';
141     }
142     return $this->serializer->serialize($rows, $content_type, ['views_style_plugin' => $this]);
143   }
144
145   /**
146    * Gets a list of all available formats that can be requested.
147    *
148    * This will return the configured formats, or all formats if none have been
149    * selected.
150    *
151    * @return array
152    *   An array of formats.
153    */
154   public function getFormats() {
155     return $this->options['formats'];
156   }
157
158   /**
159    * {@inheritdoc}
160    */
161   public function getCacheMaxAge() {
162     return Cache::PERMANENT;
163   }
164
165   /**
166    * {@inheritdoc}
167    */
168   public function getCacheContexts() {
169     return ['request_format'];
170   }
171
172   /**
173    * {@inheritdoc}
174    */
175   public function getCacheTags() {
176     return [];
177   }
178
179   /**
180    * {@inheritdoc}
181    */
182   public function calculateDependencies() {
183     $dependencies = parent::calculateDependencies();
184     $formats = $this->getFormats();
185     $providers = array_intersect_key($this->formatProviders, array_flip($formats));
186     // The plugin always uses services from the serialization module.
187     $providers[] = 'serialization';
188
189     $dependencies += ['module' => []];
190     $dependencies['module'] = array_merge($dependencies['module'], $providers);
191     return $dependencies;
192   }
193
194   /**
195    * Returns an array of format options
196    *
197    * @return string[]
198    *   An array of format options. Both key and value are the same.
199    */
200   protected function getFormatOptions() {
201     $formats = array_keys($this->formatProviders);
202     return array_combine($formats, $formats);
203   }
204
205 }