View source  
  <?php
namespace Drupal\rest\Tests\Views;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\entity_test\Entity\EntityTest;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\system\Tests\Cache\AssertPageCacheContextsAndTagsTrait;
use Drupal\views\Entity\View;
use Drupal\views\Plugin\views\display\DisplayPluginBase;
use Drupal\views\Views;
use Drupal\views\Tests\Plugin\PluginTestBase;
use Drupal\views\Tests\ViewTestData;
use Symfony\Component\HttpFoundation\Request;
class StyleSerializerTest extends PluginTestBase {
  use AssertPageCacheContextsAndTagsTrait;
  
  protected $dumpHeaders = TRUE;
  
  public static $modules = array(
    'views_ui',
    'entity_test',
    'hal',
    'rest_test_views',
    'node',
    'text',
    'field',
  );
  
  public static $testViews = array(
    'test_serializer_display_field',
    'test_serializer_display_entity',
    'test_serializer_node_display_field',
    'test_serializer_node_exposed_filter',
  );
  
  protected $adminUser;
  protected function setUp() {
    parent::setUp();
    ViewTestData::createTestViews(get_class($this), array(
      'rest_test_views',
    ));
    $this->adminUser = $this
      ->drupalCreateUser(array(
      'administer views',
      'administer entity_test content',
      'access user profiles',
      'view test entity',
    ));
    
    for ($i = 1; $i <= 10; $i++) {
      entity_create('entity_test', array(
        'name' => 'test_' . $i,
        'user_id' => $this->adminUser
          ->id(),
      ))
        ->save();
    }
    $this
      ->enableViewsTestModule();
  }
  
  public function testSerializerResponses() {
    
    $view = Views::getView('test_serializer_display_field');
    $view
      ->initDisplay();
    $this
      ->executeView($view);
    $actual_json = $this
      ->drupalGetWithFormat('test/serialize/field', 'json');
    $this
      ->assertResponse(200);
    $this
      ->assertCacheTags($view
      ->getCacheTags());
    $this
      ->assertCacheContexts([
      'languages:language_interface',
      'theme',
      'request_format',
    ]);
    
    $headers = $this
      ->drupalGetHeaders();
    $this
      ->assertEqual($headers['content-type'], 'application/json', 'The header Content-type is correct.');
    $expected = array();
    foreach ($view->result as $row) {
      $expected_row = array();
      foreach ($view->field as $id => $field) {
        $expected_row[$id] = $field
          ->render($row);
      }
      $expected[] = $expected_row;
    }
    $this
      ->assertIdentical($actual_json, json_encode($expected), 'The expected JSON output was found.');
    
    $view
      ->destroy();
    $view
      ->setDisplay('rest_export_1');
    
    $view->display_handler
      ->setContentType('json');
    $output = $view
      ->preview();
    $this
      ->assertIdentical($actual_json, (string) drupal_render_root($output), 'The expected JSON preview output was found.');
    
    $this
      ->drupalGet('test/serialize/denied');
    $this
      ->assertResponse(403);
    
    $view = Views::getView('test_serializer_display_entity');
    $view
      ->initDisplay();
    $this
      ->executeView($view);
    
    $serializer = $this->container
      ->get('serializer');
    $entities = array();
    foreach ($view->result as $row) {
      $entities[] = $row->_entity;
    }
    $expected = $serializer
      ->serialize($entities, 'json');
    $actual_json = $this
      ->drupalGetWithFormat('test/serialize/entity', 'json');
    $this
      ->assertResponse(200);
    $this
      ->assertIdentical($actual_json, $expected, 'The expected JSON output was found.');
    $expected_cache_tags = $view
      ->getCacheTags();
    $expected_cache_tags[] = 'entity_test_list';
    
    foreach ($entities as $entity) {
      $expected_cache_tags = Cache::mergeTags($expected_cache_tags, $entity
        ->getCacheTags());
    }
    $this
      ->assertCacheTags($expected_cache_tags);
    $this
      ->assertCacheContexts([
      'languages:language_interface',
      'theme',
      'entity_test_view_grants',
      'request_format',
    ]);
    $expected = $serializer
      ->serialize($entities, 'hal_json');
    $actual_json = $this
      ->drupalGetWithFormat('test/serialize/entity', 'hal_json');
    $this
      ->assertIdentical($actual_json, $expected, 'The expected HAL output was found.');
    $this
      ->assertCacheTags($expected_cache_tags);
    
    $view
      ->setDisplay('rest_export_1');
    $view
      ->getDisplay()
      ->setOption('style', array(
      'type' => 'serializer',
      'options' => array(
        'uses_fields' => FALSE,
        'formats' => array(
          'xml' => 'xml',
        ),
      ),
    ));
    $view
      ->save();
    $expected = $serializer
      ->serialize($entities, 'xml');
    $actual_xml = $this
      ->drupalGet('test/serialize/entity');
    $this
      ->assertIdentical($actual_xml, $expected, 'The expected XML output was found.');
    $this
      ->assertCacheContexts([
      'languages:language_interface',
      'theme',
      'entity_test_view_grants',
      'request_format',
    ]);
    
    $view
      ->setDisplay('rest_export_1');
    $view
      ->getDisplay()
      ->setOption('style', array(
      'type' => 'serializer',
      'options' => array(
        'uses_fields' => FALSE,
        'formats' => array(
          'xml' => 'xml',
          'json' => 'json',
        ),
      ),
    ));
    $view
      ->save();
    $expected = $serializer
      ->serialize($entities, 'json');
    $actual_json = $this
      ->drupalGetWithFormat('test/serialize/entity', 'json');
    $this
      ->assertIdentical($actual_json, $expected, 'The expected JSON output was found.');
    $expected = $serializer
      ->serialize($entities, 'xml');
    $actual_xml = $this
      ->drupalGetWithFormat('test/serialize/entity', 'xml');
    $this
      ->assertIdentical($actual_xml, $expected, 'The expected XML output was found.');
  }
  
  protected function addRequestWithFormat($format) {
    $request = \Drupal::request();
    $request = clone $request;
    $request
      ->setRequestFormat($format);
    \Drupal::requestStack()
      ->push($request);
  }
  
  public function testRestRenderCaching() {
    $this
      ->drupalLogin($this->adminUser);
    
    $render_cache = \Drupal::service('render_cache');
    
    
    $storage = View::load('test_serializer_display_entity');
    $options =& $storage
      ->getDisplay('default');
    $options['display_options']['cache'] = [
      'type' => 'tag',
    ];
    $storage
      ->save();
    $original = DisplayPluginBase::buildBasicRenderable('test_serializer_display_entity', 'rest_export_1');
    
    $original['#cache'] += [
      'contexts' => [],
    ];
    $original['#cache']['contexts'] = Cache::mergeContexts($original['#cache']['contexts'], $this->container
      ->getParameter('renderer.config')['required_cache_contexts']);
    $cache_tags = [
      'config:views.view.test_serializer_display_entity',
      'entity_test:1',
      'entity_test:10',
      'entity_test:2',
      'entity_test:3',
      'entity_test:4',
      'entity_test:5',
      'entity_test:6',
      'entity_test:7',
      'entity_test:8',
      'entity_test:9',
      'entity_test_list',
    ];
    $cache_contexts = [
      'entity_test_view_grants',
      'languages:language_interface',
      'theme',
      'request_format',
    ];
    $this
      ->assertFalse($render_cache
      ->get($original));
    
    $result1 = $this
      ->drupalGetJSON('test/serialize/entity');
    $this
      ->addRequestWithFormat('json');
    $this
      ->assertHeader('content-type', 'application/json');
    $this
      ->assertCacheContexts($cache_contexts);
    $this
      ->assertCacheTags($cache_tags);
    $this
      ->assertTrue($render_cache
      ->get($original));
    $result_xml = $this
      ->drupalGetWithFormat('test/serialize/entity', 'xml');
    $this
      ->addRequestWithFormat('xml');
    $this
      ->assertHeader('content-type', 'text/xml; charset=UTF-8');
    $this
      ->assertCacheContexts($cache_contexts);
    $this
      ->assertCacheTags($cache_tags);
    $this
      ->assertTrue($render_cache
      ->get($original));
    
    $this
      ->assertNotEqual($result1, $result_xml);
    
    $result2 = $this
      ->drupalGetJSON('test/serialize/entity');
    $this
      ->addRequestWithFormat('json');
    $this
      ->assertHeader('content-type', 'application/json');
    $this
      ->assertEqual($result2, $result1);
    $this
      ->assertCacheContexts($cache_contexts);
    $this
      ->assertCacheTags($cache_tags);
    $this
      ->assertTrue($render_cache
      ->get($original));
    
    EntityTest::create([
      'name' => 'test_11',
      'user_id' => $this->adminUser
        ->id(),
    ])
      ->save();
    $result3 = $this
      ->drupalGetJSON('test/serialize/entity');
    $this
      ->addRequestWithFormat('json');
    $this
      ->assertHeader('content-type', 'application/json');
    $this
      ->assertNotEqual($result3, $result2);
    
    $cache_tags[] = 'entity_test:11';
    unset($cache_tags[array_search('entity_test:1', $cache_tags)]);
    $this
      ->assertCacheContexts($cache_contexts);
    $this
      ->assertCacheTags($cache_tags);
    $this
      ->assertTrue($render_cache
      ->get($original));
  }
  
  public function testResponseFormatConfiguration() {
    $this
      ->drupalLogin($this->adminUser);
    $style_options = 'admin/structure/views/nojs/display/test_serializer_display_field/rest_export_1/style_options';
    
    $this
      ->drupalPostForm($style_options, array(
      'style_options[formats][xml]' => 'xml',
    ), t('Apply'));
    $this
      ->drupalPostForm(NULL, array(), t('Save'));
    
    $this
      ->drupalGetWithFormat('test/serialize/field', 'json');
    $this
      ->assertHeader('content-type', 'application/json');
    $this
      ->assertResponse(406, 'A 406 response was returned when JSON was requested.');
    
    $this
      ->drupalGetWithFormat('test/serialize/field', 'xml');
    $this
      ->assertHeader('content-type', 'text/xml; charset=UTF-8');
    $this
      ->assertResponse(200, 'A 200 response was returned when XML was requested.');
    
    $this
      ->drupalPostForm($style_options, array(
      'style_options[formats][json]' => 'json',
    ), t('Apply'));
    $this
      ->drupalPostForm(NULL, array(), t('Save'));
    
    $this
      ->drupalGet('test/serialize/field');
    $this
      ->assertHeader('content-type', 'application/json');
    $this
      ->assertResponse(200, 'A 200 response was returned when any format was requested.');
    
    $this
      ->drupalGet('test/serialize/field', array(), array(
      'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    ));
    $this
      ->assertHeader('content-type', 'application/json');
    $this
      ->assertResponse(200, 'A 200 response was returned when a browser accept header was requested.');
    
    $this
      ->drupalGetWithFormat('test/serialize/field', 'json');
    $this
      ->assertHeader('content-type', 'application/json');
    $this
      ->assertResponse(200, 'A 200 response was returned when JSON was requested.');
    $headers = $this
      ->drupalGetHeaders();
    $this
      ->assertEqual($headers['content-type'], 'application/json', 'The header Content-type is correct.');
    
    $this
      ->drupalGetWithFormat('test/serialize/field', 'xml');
    $this
      ->assertHeader('content-type', 'text/xml; charset=UTF-8');
    $this
      ->assertResponse(200, 'A 200 response was returned when XML was requested');
    $headers = $this
      ->drupalGetHeaders();
    $this
      ->assertTrue(strpos($headers['content-type'], 'text/xml') !== FALSE, 'The header Content-type is correct.');
    
    $this
      ->drupalGetWithFormat('test/serialize/field', 'html');
    
    $this
      ->assertHeader('content-type', 'application/json');
    $this
      ->assertResponse(200, 'A 200 response was returned when HTML was requested.');
    
    $this
      ->drupalPostForm($style_options, array(
      'style_options[formats][json]' => '0',
      'style_options[formats][xml]' => '0',
    ), t('Apply'));
    
    $this
      ->drupalGetWithFormat('test/serialize/field', 'json');
    $this
      ->assertHeader('content-type', 'application/json');
    $this
      ->assertResponse(200, 'A 200 response was returned when JSON was requested.');
    
    $this
      ->drupalGetWithFormat('test/serialize/field', 'xml');
    $this
      ->assertHeader('content-type', 'text/xml; charset=UTF-8');
    $this
      ->assertResponse(200, 'A 200 response was returned when XML was requested');
    
    $this
      ->drupalGetWithFormat('test/serialize/field', 'html');
    
    $this
      ->assertHeader('content-type', 'application/json');
    $this
      ->assertResponse(200, 'A 200 response was returned when HTML was requested.');
  }
  
  public function testUIFieldAlias() {
    $this
      ->drupalLogin($this->adminUser);
    
    $this
      ->drupalGet('admin/structure/views/view/test_serializer_display_field/edit/rest_export_1');
    $row_options = 'admin/structure/views/nojs/display/test_serializer_display_field/rest_export_1/row_options';
    $this
      ->assertLinkByHref($row_options);
    
    $this
      ->drupalPostForm($row_options, array(
      'row_options[field_options][name][alias]' => '',
    ), t('Apply'));
    $this
      ->drupalPostForm(NULL, array(), t('Save'));
    $view = Views::getView('test_serializer_display_field');
    $view
      ->setDisplay('rest_export_1');
    $this
      ->executeView($view);
    $expected = array();
    foreach ($view->result as $row) {
      $expected_row = array();
      foreach ($view->field as $id => $field) {
        $expected_row[$id] = $field
          ->render($row);
      }
      $expected[] = $expected_row;
    }
    $this
      ->assertIdentical($this
      ->drupalGetJSON('test/serialize/field'), $this
      ->castSafeStrings($expected));
    
    $alias_map = array(
      'name' => $this
        ->randomMachineName(),
      
      'nothing' => '#' . $this
        ->randomMachineName(),
      'created' => 'created',
    );
    $edit = array(
      'row_options[field_options][name][alias]' => $alias_map['name'],
      'row_options[field_options][nothing][alias]' => $alias_map['nothing'],
    );
    $this
      ->drupalPostForm($row_options, $edit, t('Apply'));
    $this
      ->assertText(t('The machine-readable name must contain only letters, numbers, dashes and underscores.'));
    
    $alias_map['nothing'] = $this
      ->randomMachineName();
    $edit = array(
      'row_options[field_options][name][alias]' => $alias_map['name'],
      'row_options[field_options][nothing][alias]' => $alias_map['nothing'],
    );
    $this
      ->drupalPostForm($row_options, $edit, t('Apply'));
    $this
      ->drupalPostForm(NULL, array(), t('Save'));
    $view = Views::getView('test_serializer_display_field');
    $view
      ->setDisplay('rest_export_1');
    $this
      ->executeView($view);
    $expected = array();
    foreach ($view->result as $row) {
      $expected_row = array();
      foreach ($view->field as $id => $field) {
        $expected_row[$alias_map[$id]] = $field
          ->render($row);
      }
      $expected[] = $expected_row;
    }
    $this
      ->assertIdentical($this
      ->drupalGetJSON('test/serialize/field'), $this
      ->castSafeStrings($expected));
  }
  
  public function testFieldRawOutput() {
    $this
      ->drupalLogin($this->adminUser);
    
    $this
      ->drupalGet('admin/structure/views/view/test_serializer_display_field/edit/rest_export_1');
    $row_options = 'admin/structure/views/nojs/display/test_serializer_display_field/rest_export_1/row_options';
    $this
      ->assertLinkByHref($row_options);
    
    $this
      ->drupalPostForm($row_options, array(
      'row_options[field_options][created][raw_output]' => '1',
    ), t('Apply'));
    $this
      ->drupalPostForm(NULL, array(), t('Save'));
    $view = Views::getView('test_serializer_display_field');
    $view
      ->setDisplay('rest_export_1');
    $this
      ->executeView($view);
    
    foreach ($this
      ->drupalGetJSON('test/serialize/field') as $index => $values) {
      $this
        ->assertIdentical($values['created'], $view->result[$index]->views_test_data_created, 'Expected raw created value found.');
    }
  }
  
  public function testLivePreview() {
    
    $request = new Request();
    $request
      ->setFormat('drupal_ajax', 'application/vnd.drupal-ajax');
    $request->headers
      ->set('Accept', 'application/vnd.drupal-ajax');
    
    $request_stack = \Drupal::service('request_stack');
    $request_stack
      ->push($request);
    $view = Views::getView('test_serializer_display_entity');
    $view
      ->setDisplay('rest_export_1');
    $this
      ->executeView($view);
    
    $serializer = $this->container
      ->get('serializer');
    $entities = array();
    foreach ($view->result as $row) {
      $entities[] = $row->_entity;
    }
    $expected = $serializer
      ->serialize($entities, 'json');
    $view->live_preview = TRUE;
    $build = $view
      ->preview();
    $rendered_json = $build['#plain_text'];
    $this
      ->assertTrue(!isset($build['#markup']) && $rendered_json == $expected, 'Ensure the previewed json is escaped.');
    $view
      ->destroy();
    $expected = $serializer
      ->serialize($entities, 'xml');
    
    $view
      ->setDisplay('rest_export_1');
    $view
      ->getDisplay()
      ->setOption('style', array(
      'type' => 'serializer',
      'options' => array(
        'uses_fields' => FALSE,
        'formats' => array(
          'xml' => 'xml',
        ),
      ),
    ));
    $this
      ->executeView($view);
    $build = $view
      ->preview();
    $rendered_xml = $build['#plain_text'];
    $this
      ->assertEqual($rendered_xml, $expected, 'Ensure we preview xml when we change the request format.');
  }
  
  public function testSerializerViewsUI() {
    $this
      ->drupalLogin($this->adminUser);
    
    $this
      ->drupalPostForm('admin/structure/views/view/test_serializer_display_field/edit/rest_export_1', $edit = array(), t('Update preview'));
    $this
      ->assertResponse(200);
    
    $result = $this
      ->xpath('//div[@id="views-live-preview"]/pre');
    $this
      ->assertIdentical($this
      ->drupalGet('test/serialize/field'), (string) $result[0], 'The expected JSON preview output was found.');
  }
  
  public function testFieldapiField() {
    $this
      ->drupalCreateContentType(array(
      'type' => 'page',
    ));
    $node = $this
      ->drupalCreateNode();
    $result = $this
      ->drupalGetJSON('test/serialize/node-field');
    $this
      ->assertEqual($result[0]['nid'], $node
      ->id());
    $this
      ->assertEqual($result[0]['body'], $node->body->processed);
    
    $node = $this
      ->drupalCreateNode();
    $node->body = [
      'value' => '<script type="text/javascript">alert("node-body");</script>' . $this
        ->randomMachineName(32),
      'format' => filter_default_format(),
    ];
    $node
      ->save();
    $result = $this
      ->drupalGetJSON('test/serialize/node-field');
    $this
      ->assertEqual($result[1]['nid'], $node
      ->id());
    $this
      ->assertTrue(strpos($this
      ->getRawContent(), "<script") === FALSE, "No script tag is present in the raw page contents.");
  }
  
  public function testGroupRows() {
    
    $renderer = $this->container
      ->get('renderer');
    $this
      ->drupalCreateContentType([
      'type' => 'page',
    ]);
    
    $field_name = 'field_group_rows';
    $field_storage = FieldStorageConfig::create([
      'field_name' => $field_name,
      'entity_type' => 'node',
      'type' => 'string',
      'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED,
    ]);
    $field_storage
      ->save();
    
    $field = FieldConfig::create([
      'field_storage' => $field_storage,
      'bundle' => 'page',
    ]);
    $field
      ->save();
    $grouped_field_values = [
      'a',
      'b',
      'c',
    ];
    $edit = [
      'title' => $this
        ->randomMachineName(),
      $field_name => $grouped_field_values,
    ];
    $this
      ->drupalCreateNode($edit);
    $view = Views::getView('test_serializer_node_display_field');
    $view
      ->setDisplay('rest_export_1');
    
    $fields = [
      $field_name => [
        'id' => $field_name,
        'table' => 'node__' . $field_name,
        'field' => $field_name,
        'type' => 'string',
        'group_rows' => TRUE,
      ],
    ];
    $view->displayHandlers
      ->get('default')
      ->overrideOption('fields', $fields);
    $build = $view
      ->preview();
    
    $serializer = $this->container
      ->get('serializer');
    
    $expected = [];
    $expected[] = [
      $field_name => implode(', ', $grouped_field_values),
    ];
    $this
      ->assertEqual($serializer
      ->serialize($expected, 'json'), (string) $renderer
      ->renderRoot($build));
    
    $view = Views::getView('test_serializer_node_display_field');
    $view
      ->setDisplay('rest_export_1');
    $fields[$field_name]['group_rows'] = FALSE;
    $view->displayHandlers
      ->get('default')
      ->overrideOption('fields', $fields);
    $build = $view
      ->preview();
    
    $expected = [];
    foreach ($grouped_field_values as $grouped_field_value) {
      $expected[] = [
        $field_name => $grouped_field_value,
      ];
    }
    $this
      ->assertEqual($serializer
      ->serialize($expected, 'json'), (string) $renderer
      ->renderRoot($build));
  }
  
  public function testRestViewExposedFilter() {
    $this
      ->drupalCreateContentType(array(
      'type' => 'page',
    ));
    $node0 = $this
      ->drupalCreateNode(array(
      'title' => 'Node 1',
    ));
    $node1 = $this
      ->drupalCreateNode(array(
      'title' => 'Node 11',
    ));
    $node2 = $this
      ->drupalCreateNode(array(
      'title' => 'Node 111',
    ));
    
    $result = $this
      ->drupalGetJSON('test/serialize/node-exposed-filter');
    $expected = array(
      0 => array(
        'nid' => $node0
          ->id(),
        'body' => $node0->body->processed,
      ),
      1 => array(
        'nid' => $node1
          ->id(),
        'body' => $node1->body->processed,
      ),
      2 => array(
        'nid' => $node2
          ->id(),
        'body' => $node2->body->processed,
      ),
    );
    $this
      ->assertEqual($result, $expected, 'Querying a view with no exposed filter returns all nodes.');
    
    $result = $this
      ->drupalGetJSON('test/serialize/node-exposed-filter', [
      'query' => [
        'title' => 'Node 11',
      ],
    ]);
    $expected = array(
      0 => array(
        'nid' => $node1
          ->id(),
        'body' => $node1->body->processed,
      ),
      1 => array(
        'nid' => $node2
          ->id(),
        'body' => $node2->body->processed,
      ),
    );
    $cache_contexts = [
      'languages:language_content',
      'languages:language_interface',
      'theme',
      'request_format',
      'user.node_grants:view',
      'url',
    ];
    $this
      ->assertEqual($result, $expected, 'Querying a view with a starts with exposed filter on the title returns nodes whose title starts with value provided.');
    $this
      ->assertCacheContexts($cache_contexts);
  }
}