RestExport.php 8.41 KB
Newer Older
1 2 3 4 5 6 7 8 9
<?php

/**
 * @file
 * Contains \Drupal\rest\Plugin\views\display\RestExport.
 */

namespace Drupal\rest\Plugin\views\display;

10
use Drupal\Core\Form\FormErrorInterface;
11
use Drupal\Core\State\StateInterface;
12
use Drupal\Core\Routing\RouteProviderInterface;
13
use Drupal\Core\ContentNegotiation;
14 15
use Drupal\views\ViewExecutable;
use Drupal\views\Plugin\views\display\PathPluginBase;
16 17
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
18 19
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\RouteCollection;
20 21 22 23 24 25

/**
 * The plugin that handles Data response callbacks for REST resources.
 *
 * @ingroup views_display_plugins
 *
26
 * @ViewsDisplay(
27 28 29
 *   id = "rest_export",
 *   title = @Translation("REST export"),
 *   help = @Translation("Create a REST export resource."),
30
 *   uses_route = TRUE,
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
 *   admin = @Translation("REST export")
 * )
 */
class RestExport extends PathPluginBase {

  /**
   * Overrides \Drupal\views\Plugin\views\display\DisplayPluginBase::$usesAJAX.
   */
  protected $usesAJAX = FALSE;

  /**
   * Overrides \Drupal\views\Plugin\views\display\DisplayPluginBase::$usesPager.
   */
  protected $usesPager = FALSE;

  /**
   * Overrides \Drupal\views\Plugin\views\display\DisplayPluginBase::$usesMore.
   */
  protected $usesMore = FALSE;

  /**
   * Overrides \Drupal\views\Plugin\views\display\DisplayPluginBase::$usesAreas.
   */
  protected $usesAreas = FALSE;

  /**
   * Overrides \Drupal\views\Plugin\views\display\DisplayPluginBase::$usesAreas.
   */
  protected $usesOptions = FALSE;

  /**
   * Overrides the content type of the data response, if needed.
   *
   * @var string
   */
66
  protected $contentType = 'json';
67 68 69 70 71 72 73 74

  /**
   * The mime type for the response.
   *
   * @var string
   */
  protected $mimeType;

75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
  /**
   * The content negotiation library.
   *
   * @var \Drupal\Core\ContentNegotiation
   */
  protected $contentNegotiation;

  /**
   * The request object.
   *
   * @var \Symfony\Component\HttpFoundation\Request
   */
  protected $request;

  /**
   * Constructs a Drupal\rest\Plugin\ResourceBase object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
96
   * @param mixed $plugin_definition
97
   *   The plugin implementation definition.
98 99
   * @param \Drupal\Core\Routing\RouteProviderInterface $route_provider
   *   The route provider
100
   * @param \Drupal\Core\State\StateInterface $state
101
   *   The state key value store.
102 103
   * @param \Drupal\Core\Form\FormErrorInterface $form_error
   *   The form error helper.
104 105 106 107 108
   * @param \Drupal\Core\ContentNegotiation $content_negotiation
   *   The content negotiation library.
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The request object.
   */
109
  public function __construct(array $configuration, $plugin_id, $plugin_definition, RouteProviderInterface $route_provider, StateInterface $state, FormErrorInterface $form_error, ContentNegotiation $content_negotiation, Request $request) {
110
    parent::__construct($configuration, $plugin_id, $plugin_definition, $route_provider, $state, $form_error);
111 112 113 114 115 116 117
    $this->contentNegotiation = $content_negotiation;
    $this->request = $request;
  }

  /**
   * {@inheritdoc}
   */
118
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
119 120 121 122
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
123 124
      $container->get('router.route_provider'),
      $container->get('state'),
125
      $container->get('form_validator'),
126 127 128 129 130
      $container->get('content_negotiation'),
      $container->get('request')
    );
  }

131
  /**
132
   * {@inheritdoc}
133 134 135 136
   */
  public function initDisplay(ViewExecutable $view, array &$display, array &$options = NULL) {
    parent::initDisplay($view, $display, $options);

137
    $request_content_type = $this->contentNegotiation->getContentType($this->request);
138 139
    // Only use the requested content type if it's not 'html'. If it is then
    // default to 'json' to aid debugging.
140 141
    // @todo Remove the need for this when we have better content negotiation.
    if ($request_content_type != 'html') {
142 143 144
      $this->setContentType($request_content_type);
    }

145
    $this->setMimeType($this->request->getMimeType($this->contentType));
146 147 148
  }

  /**
149
   * {@inheritdoc}
150
   */
151
  protected function getType() {
152 153 154 155
    return 'data';
  }

  /**
156
   * {@inheritdoc}
157 158 159 160 161 162
   */
  public function usesExposed() {
    return FALSE;
  }

  /**
163
   * {@inheritdoc}
164 165 166 167 168 169 170 171
   */
  public function displaysExposed() {
    return FALSE;
  }

  /**
   * Sets the request content type.
   *
172
   * @param string $mime_type
173 174 175 176 177 178 179 180 181
   *   The response mime type. E.g. 'application/json'.
   */
  public function setMimeType($mime_type) {
    $this->mimeType = $mime_type;
  }

  /**
   * Gets the mime type.
   *
182
   * This will return any overridden mime type, otherwise returns the mime type
183 184
   * from the request.
   *
185
   * @return string
186 187 188 189 190 191 192 193 194
   *   The response mime type. E.g. 'application/json'.
   */
  public function getMimeType() {
    return $this->mimeType;
  }

  /**
   * Sets the content type.
   *
195
   * @param string $content_type
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
   *   The content type machine name. E.g. 'json'.
   */
  public function setContentType($content_type) {
    $this->contentType = $content_type;
  }

  /**
   * Gets the content type.
   *
   * @return string
   *   The content type machine name. E.g. 'json'.
   */
  public function getContentType() {
    return $this->contentType;
  }

  /**
213
   * {@inheritdoc}
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
   */
  protected function defineOptions() {
    $options = parent::defineOptions();

    // Set the default style plugin to 'json'.
    $options['style']['contains']['type']['default'] = 'serializer';
    $options['row']['contains']['type']['default'] = 'data_entity';
    $options['defaults']['default']['style'] = FALSE;
    $options['defaults']['default']['row'] = FALSE;

    // Remove css/exposed form settings, as they are not used for the data display.
    unset($options['exposed_form']);
    unset($options['exposed_block']);
    unset($options['css_class']);

    return $options;
  }

  /**
233
   * {@inheritdoc}
234 235 236 237 238 239
   */
  public function optionsSummary(&$categories, &$options) {
    parent::optionsSummary($categories, $options);

    unset($categories['page'], $categories['exposed']);
    // Hide some settings, as they aren't useful for pure data output.
240
    unset($options['show_admin_links'], $options['analyze-theme']);
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259

    $categories['path'] = array(
      'title' => t('Path settings'),
      'column' => 'second',
      'build' => array(
        '#weight' => -10,
      ),
    );

    $options['path']['category'] = 'path';
    $options['path']['title'] = t('Path');

    // Remove css/exposed form settings, as they are not used for the data
    // display.
    unset($options['exposed_form']);
    unset($options['exposed_block']);
    unset($options['css_class']);
  }

260 261 262 263 264
  /**
   * {@inheritdoc}
   */
  public function collectRoutes(RouteCollection $collection) {
    parent::collectRoutes($collection);
265 266
    $view_id = $this->view->storage->id();
    $display_id = $this->display['id'];
267

268 269 270 271
    if ($route = $collection->get("view.$view_id.$display_id")) {
      $style_plugin = $this->getPlugin('style');
      // REST exports should only respond to get methods.
      $requirements = array('_method' => 'GET');
272

273 274
      // Format as a string using pipes as a delimeter.
      $requirements['_format'] = implode('|', $style_plugin->getFormats());
275

276
      // Add the new requirements to the route.
277 278 279
      $route->addRequirements($requirements);
    }
  }
280 281

  /**
282
   * {@inheritdoc}
283 284 285 286
   */
  public function execute() {
    parent::execute();

287 288
    $output = $this->view->render();
    return new Response(drupal_render($output), 200, array('Content-type' => $this->getMimeType()));
289 290 291
  }

  /**
292
   * {@inheritdoc}
293 294
   */
  public function render() {
295 296
    $build = array();
    $build['#markup'] = $this->view->style_plugin->render();
297

298
    // Wrap the output in a pre tag if this is for a live preview.
299
    if (!empty($this->view->live_preview)) {
300
      $build['#prefix'] = '<pre>';
301
      $build['#markup'] = check_plain($build['#markup']);
302
      $build['#suffix'] = '</pre>';
303 304
    }

305
    return $build;
306 307 308
  }

  /**
309
   * {@inheritdoc}
310 311 312 313 314 315 316 317 318
   *
   * The DisplayPluginBase preview method assumes we will be returning a render
   * array. The data plugin will already return the serialized string.
   */
  public function preview() {
    return $this->view->render();
  }

}