3 namespace Drupal\Tests\views\Kernel;
5 use Drupal\comment\Tests\CommentTestTrait;
6 use Drupal\Component\Utility\Xss;
7 use Drupal\node\Entity\NodeType;
8 use Drupal\views\Entity\View;
9 use Drupal\views\Views;
10 use Drupal\views\ViewExecutable;
11 use Drupal\views\ViewExecutableFactory;
12 use Drupal\views\DisplayPluginCollection;
13 use Drupal\views\Plugin\views\display\DefaultDisplay;
14 use Drupal\views\Plugin\views\display\Page;
15 use Drupal\views\Plugin\views\style\DefaultStyle;
16 use Drupal\views\Plugin\views\style\Grid;
17 use Drupal\views\Plugin\views\row\Fields;
18 use Drupal\views\Plugin\views\query\Sql;
19 use Drupal\views\Plugin\views\pager\PagerPluginBase;
20 use Drupal\views\Plugin\views\query\QueryPluginBase;
21 use Drupal\views_test_data\Plugin\views\display\DisplayTest;
22 use Symfony\Component\HttpFoundation\Response;
25 * Tests the ViewExecutable class.
28 * @see \Drupal\views\ViewExecutable
30 class ViewExecutableTest extends ViewsKernelTestBase {
34 public static $modules = ['system', 'node', 'comment', 'user', 'filter', 'field', 'text'];
37 * Views used by this test.
41 public static $testViews = ['test_destroy', 'test_executable_displays'];
44 * Properties that should be stored in the configuration.
48 protected $configProperties = [
60 * Properties that should be stored in the executable.
64 protected $executableProperties = [
79 protected function setUpFixtures() {
80 $this->installEntitySchema('user');
81 $this->installEntitySchema('node');
82 $this->installEntitySchema('comment');
83 $this->installSchema('comment', ['comment_entity_statistics']);
84 $this->installConfig(['system', 'field', 'node', 'comment']);
90 $this->addDefaultCommentField('node', 'page');
91 parent::setUpFixtures();
93 $this->installConfig(['filter']);
97 * Tests the views.executable container service.
99 public function testFactoryService() {
100 $factory = $this->container->get('views.executable');
101 $this->assertTrue($factory instanceof ViewExecutableFactory, 'A ViewExecutableFactory instance was returned from the container.');
102 $view = View::load('test_executable_displays');
103 $this->assertTrue($factory->get($view) instanceof ViewExecutable, 'A ViewExecutable instance was returned from the factory.');
107 * Tests the initDisplay() and initHandlers() methods.
109 public function testInitMethods() {
110 $view = Views::getView('test_destroy');
111 $view->initDisplay();
113 $this->assertTrue($view->display_handler instanceof DefaultDisplay, 'Make sure a reference to the current display handler is set.');
114 $this->assertTrue($view->displayHandlers->get('default') instanceof DefaultDisplay, 'Make sure a display handler is created for each display.');
117 $view->initHandlers();
119 // Check for all handler types.
120 $handler_types = array_keys(ViewExecutable::getHandlerTypes());
121 foreach ($handler_types as $type) {
122 // The views_test integration doesn't have relationships.
123 if ($type == 'relationship') {
126 $this->assertTrue(count($view->$type), format_string('Make sure a %type instance got instantiated.', ['%type' => $type]));
129 // initHandlers() should create display handlers automatically as well.
130 $this->assertTrue($view->display_handler instanceof DefaultDisplay, 'Make sure a reference to the current display handler is set.');
131 $this->assertTrue($view->displayHandlers->get('default') instanceof DefaultDisplay, 'Make sure a display handler is created for each display.');
133 $view_hash = spl_object_hash($view);
134 $display_hash = spl_object_hash($view->display_handler);
136 // Test the initStyle() method.
138 $this->assertTrue($view->style_plugin instanceof DefaultStyle, 'Make sure a reference to the style plugin is set.');
139 // Test the plugin has been inited and view have references to the view and
141 $this->assertEqual(spl_object_hash($view->style_plugin->view), $view_hash);
142 $this->assertEqual(spl_object_hash($view->style_plugin->displayHandler), $display_hash);
144 // Test the initQuery method().
146 $this->assertTrue($view->query instanceof Sql, 'Make sure a reference to the query is set');
147 $this->assertEqual(spl_object_hash($view->query->view), $view_hash);
148 $this->assertEqual(spl_object_hash($view->query->displayHandler), $display_hash);
152 // Test the plugin get methods.
153 $display_plugin = $view->getDisplay();
154 $this->assertTrue($display_plugin instanceof DefaultDisplay, 'An instance of DefaultDisplay was returned.');
155 $this->assertTrue($view->display_handler instanceof DefaultDisplay, 'The display_handler property has been set.');
156 $this->assertIdentical($display_plugin, $view->getDisplay(), 'The same display plugin instance was returned.');
158 $style_plugin = $view->getStyle();
159 $this->assertTrue($style_plugin instanceof DefaultStyle, 'An instance of DefaultStyle was returned.');
160 $this->assertTrue($view->style_plugin instanceof DefaultStyle, 'The style_plugin property has been set.');
161 $this->assertIdentical($style_plugin, $view->getStyle(), 'The same style plugin instance was returned.');
163 $pager_plugin = $view->getPager();
164 $this->assertTrue($pager_plugin instanceof PagerPluginBase, 'An instance of PagerPluginBase was returned.');
165 $this->assertTrue($view->pager instanceof PagerPluginBase, 'The pager property has been set.');
166 $this->assertIdentical($pager_plugin, $view->getPager(), 'The same pager plugin instance was returned.');
168 $query_plugin = $view->getQuery();
169 $this->assertTrue($query_plugin instanceof QueryPluginBase, 'An instance of QueryPluginBase was returned.');
170 $this->assertTrue($view->query instanceof QueryPluginBase, 'The query property has been set.');
171 $this->assertIdentical($query_plugin, $view->getQuery(), 'The same query plugin instance was returned.');
175 * Tests the generation of the executable object.
177 public function testConstructing() {
178 Views::getView('test_destroy');
182 * Tests the accessing of values on the object.
184 public function testProperties() {
185 $view = Views::getView('test_destroy');
186 foreach ($this->executableProperties as $property) {
187 $this->assertTrue(isset($view->{$property}));
190 // Per default exposed input should fall back to an empty array.
191 $this->assertEqual($view->getExposedInput(), []);
194 public function testSetDisplayWithInvalidDisplay() {
195 $view = Views::getView('test_executable_displays');
196 $view->initDisplay();
198 // Error is triggered while calling the wrong display.
200 $view->setDisplay('invalid');
201 $this->fail('Expected error, when setDisplay() called with invalid display ID');
203 catch (\PHPUnit_Framework_Error_Warning $e) {
204 $this->assertEquals('setDisplay() called with invalid display ID "invalid".', $e->getMessage());
207 $this->assertEqual($view->current_display, 'default', 'If setDisplay is called with an invalid display id the default display should be used.');
208 $this->assertEqual(spl_object_hash($view->display_handler), spl_object_hash($view->displayHandlers->get('default')));
212 * Tests the display related methods and properties.
214 public function testDisplays() {
215 $view = Views::getView('test_executable_displays');
217 // Tests Drupal\views\ViewExecutable::initDisplay().
218 $view->initDisplay();
219 $this->assertTrue($view->displayHandlers instanceof DisplayPluginCollection, 'The displayHandlers property has the right class.');
220 // Tests the classes of the instances.
221 $this->assertTrue($view->displayHandlers->get('default') instanceof DefaultDisplay);
222 $this->assertTrue($view->displayHandlers->get('page_1') instanceof Page);
223 $this->assertTrue($view->displayHandlers->get('page_2') instanceof Page);
225 // After initializing the default display is the current used display.
226 $this->assertEqual($view->current_display, 'default');
227 $this->assertEqual(spl_object_hash($view->display_handler), spl_object_hash($view->displayHandlers->get('default')));
229 // All handlers should have a reference to the default display.
230 $this->assertEqual(spl_object_hash($view->displayHandlers->get('page_1')->default_display), spl_object_hash($view->displayHandlers->get('default')));
231 $this->assertEqual(spl_object_hash($view->displayHandlers->get('page_2')->default_display), spl_object_hash($view->displayHandlers->get('default')));
233 // Tests Drupal\views\ViewExecutable::setDisplay().
235 $this->assertEqual($view->current_display, 'default', 'If setDisplay is called with no parameter the default display should be used.');
236 $this->assertEqual(spl_object_hash($view->display_handler), spl_object_hash($view->displayHandlers->get('default')));
238 // Set two different valid displays.
239 $view->setDisplay('page_1');
240 $this->assertEqual($view->current_display, 'page_1', 'If setDisplay is called with a valid display id the appropriate display should be used.');
241 $this->assertEqual(spl_object_hash($view->display_handler), spl_object_hash($view->displayHandlers->get('page_1')));
243 $view->setDisplay('page_2');
244 $this->assertEqual($view->current_display, 'page_2', 'If setDisplay is called with a valid display id the appropriate display should be used.');
245 $this->assertEqual(spl_object_hash($view->display_handler), spl_object_hash($view->displayHandlers->get('page_2')));
247 // Destroy the view, so we can start again and test an invalid display.
250 // Test the style and row plugins are replaced correctly when setting the
252 $view->setDisplay('page_1');
254 $this->assertTrue($view->style_plugin instanceof DefaultStyle);
255 $this->assertTrue($view->rowPlugin instanceof Fields);
257 $view->setDisplay('page_2');
259 $this->assertTrue($view->style_plugin instanceof Grid);
260 // @todo Change this rowPlugin type too.
261 $this->assertTrue($view->rowPlugin instanceof Fields);
263 // Test the newDisplay() method.
264 $view = $this->container->get('entity.manager')->getStorage('view')->create(['id' => 'test_executable_displays']);
265 $executable = $view->getExecutable();
267 $executable->newDisplay('page');
268 $executable->newDisplay('page');
269 $executable->newDisplay('display_test');
271 $this->assertTrue($executable->displayHandlers->get('default') instanceof DefaultDisplay);
272 $this->assertFalse(isset($executable->displayHandlers->get('default')->default_display));
273 $this->assertTrue($executable->displayHandlers->get('page_1') instanceof Page);
274 $this->assertTrue($executable->displayHandlers->get('page_1')->default_display instanceof DefaultDisplay);
275 $this->assertTrue($executable->displayHandlers->get('page_2') instanceof Page);
276 $this->assertTrue($executable->displayHandlers->get('page_2')->default_display instanceof DefaultDisplay);
277 $this->assertTrue($executable->displayHandlers->get('display_test_1') instanceof DisplayTest);
278 $this->assertTrue($executable->displayHandlers->get('display_test_1')->default_display instanceof DefaultDisplay);
282 * Tests the setting/getting of properties.
284 public function testPropertyMethods() {
285 $view = Views::getView('test_executable_displays');
287 // Test the setAjaxEnabled() method.
288 $this->assertFalse($view->ajaxEnabled());
289 $view->setAjaxEnabled(TRUE);
290 $this->assertTrue($view->ajaxEnabled());
293 // There should be no pager set initially.
294 $this->assertNull($view->usePager());
296 // Add a pager, initialize, and test.
297 $view->displayHandlers->get('default')->overrideOption('pager', [
299 'options' => ['items_per_page' => 10],
302 $this->assertTrue($view->usePager());
304 // Test setting and getting the offset.
306 $view->setOffset($rand);
307 $this->assertEqual($view->getOffset(), $rand);
309 // Test the getBaseTable() method.
311 'views_test_data' => TRUE,
314 $this->assertIdentical($view->getBaseTables(), $expected);
316 // Test response methods.
317 $this->assertTrue($view->getResponse() instanceof Response, 'New response object returned.');
318 $new_response = new Response();
319 $view->setResponse($new_response);
320 $this->assertIdentical(spl_object_hash($view->getResponse()), spl_object_hash($new_response), 'New response object correctly set.');
322 // Test the getPath() method.
323 $path = $this->randomMachineName();
324 $view->displayHandlers->get('page_1')->overrideOption('path', $path);
325 $view->setDisplay('page_1');
326 $this->assertEqual($view->getPath(), $path);
327 // Test the override_path property override.
328 $override_path = $this->randomMachineName();
329 $view->override_path = $override_path;
330 $this->assertEqual($view->getPath(), $override_path);
332 // Test the title methods.
333 $title = $this->randomString();
334 $view->setTitle($title);
335 $this->assertEqual($view->getTitle(), Xss::filterAdmin($title));
339 * Tests the deconstructor to be sure that necessary objects are removed.
341 public function testDestroy() {
342 $view = Views::getView('test_destroy');
347 $this->assertViewDestroy($view);
351 * Asserts that expected view properties have been unset by destroy().
353 * @param \Drupal\views\ViewExecutable $view
355 protected function assertViewDestroy($view) {
356 $reflection = new \ReflectionClass($view);
357 $defaults = $reflection->getDefaultProperties();
358 // The storage and user should remain.
360 $defaults['storage'],
362 $defaults['request'],
363 $defaults['routeProvider'],
364 $defaults['viewsData']
367 foreach ($defaults as $property => $default) {
368 $this->assertIdentical($this->getProtectedProperty($view, $property), $default);
373 * Returns a protected property from a class instance.
375 * @param object $instance
376 * The class instance to return the property from.
377 * @param string $property
378 * The name of the property to return.
381 * The instance property value.
383 protected function getProtectedProperty($instance, $property) {
384 $reflection = new \ReflectionProperty($instance, $property);
385 $reflection->setAccessible(TRUE);
386 return $reflection->getValue($instance);
390 * Tests ViewExecutable::getHandlerTypes().
392 public function testGetHandlerTypes() {
393 $types = ViewExecutable::getHandlerTypes();
394 foreach (['field', 'filter', 'argument', 'sort', 'header', 'footer', 'empty'] as $type) {
395 $this->assertTrue(isset($types[$type]));
396 // @todo The key on the display should be footers, headers and empties
397 // or something similar instead of the singular, but so long check for
398 // this special case.
399 if (isset($types[$type]['type']) && $types[$type]['type'] == 'area') {
400 $this->assertEqual($types[$type]['plural'], $type);
403 $this->assertEqual($types[$type]['plural'], $type . 's');
409 * Tests ViewExecutable::getHandlers().
411 public function testGetHandlers() {
412 $view = Views::getView('test_executable_displays');
413 $view->setDisplay('page_1');
415 $view->getHandlers('field', 'page_2');
417 // getHandlers() shouldn't change the active display.
418 $this->assertEqual('page_1', $view->current_display, "The display shouldn't change after getHandlers()");
422 * Tests the validation of display handlers.
424 public function testValidate() {
425 $view = Views::getView('test_executable_displays');
426 $view->setDisplay('page_1');
428 $validate = $view->validate();
430 // Validating a view shouldn't change the active display.
431 $this->assertEqual('page_1', $view->current_display, "The display should be constant while validating");
434 foreach ($view->displayHandlers as $id => $display) {
435 $match = function ($value) use ($display) {
436 return strpos($value, $display->display['display_title']) !== FALSE;
438 $this->assertTrue(array_filter($validate[$id], $match), format_string('Error message found for @id display', ['@id' => $id]));
442 $this->assertEqual(count($view->displayHandlers), $count, 'Error messages from all handlers merged.');
444 // Test that a deleted display is not included.
445 $display = &$view->storage->getDisplay('default');
446 $display['deleted'] = TRUE;
447 $validate_deleted = $view->validate();
449 $this->assertNotIdentical($validate, $validate_deleted, 'Master display has not been validated.');
453 * Tests that nested loops of the display handlers won't break validation.
455 public function testValidateNestedLoops() {
456 $view = View::create(['id' => 'test_validate_nested_loops']);
457 $executable = $view->getExecutable();
459 $executable->newDisplay('display_test');
460 $executable->newDisplay('display_test');
461 $errors = $executable->validate();
462 $total_error_count = array_reduce($errors, function ($carry, $item) {
463 $carry += count($item);
467 // Assert that there were 9 total errors across 3 displays.
468 $this->assertIdentical(9, $total_error_count);
469 $this->assertIdentical(3, count($errors));
473 * Tests serialization of the ViewExecutable object.
475 public function testSerialization() {
476 $view = Views::getView('test_executable_displays');
477 $view->setDisplay('page_1');
478 $view->setArguments(['test']);
479 $view->setCurrentPage(2);
481 $serialized = serialize($view);
483 // Test the view storage object is not present in the actual serialized
485 $this->assertIdentical(strpos($serialized, '"Drupal\views\Entity\View"'), FALSE, 'The Drupal\views\Entity\View class was not found in the serialized string.');
487 /** @var \Drupal\views\ViewExecutable $unserialized */
488 $unserialized = unserialize($serialized);
490 $this->assertTrue($unserialized instanceof ViewExecutable);
491 $this->assertIdentical($view->storage->id(), $unserialized->storage->id(), 'The expected storage entity was loaded on the unserialized view.');
492 $this->assertIdentical($unserialized->current_display, 'page_1', 'The expected display was set on the unserialized view.');
493 $this->assertIdentical($unserialized->args, ['test'], 'The expected argument was set on the unserialized view.');
494 $this->assertIdentical($unserialized->getCurrentPage(), 2, 'The expected current page was set on the unserialized view.');
496 // Get the definition of node's nid field, for example. Only get it not from
497 // the field manager directly, but from the item data definition. It should
498 // be the same base field definition object (the field and item definitions
499 // refer to each other).
500 // See https://bugs.php.net/bug.php?id=66052
501 $field_manager = $this->container->get('entity_field.manager');
502 $nid_definition_before = $field_manager->getBaseFieldDefinitions('node')['nid']
503 ->getItemDefinition()
504 ->getFieldDefinition();
506 // Load and execute a view.
507 $view_entity = View::load('content');
508 $view_executable = $view_entity->getExecutable();
509 $view_executable->execute('page_1');
511 // Reset the static cache. Don't use clearCachedFieldDefinitions() since
512 // that clears the persistent cache and we need to get the serialized cache
514 $field_manager->useCaches(FALSE);
515 $field_manager->useCaches(TRUE);
517 // Serialize the ViewExecutable as part of other data.
518 unserialize(serialize(['SOMETHING UNEXPECTED', $view_executable]));
520 // Make sure the serialisation of the ViewExecutable didn't influence the
521 // field definitions.
522 $nid_definition_after = $field_manager->getBaseFieldDefinitions('node')['nid']
523 ->getItemDefinition()
524 ->getFieldDefinition();
525 $this->assertEquals($nid_definition_before->getPropertyDefinitions(), $nid_definition_after->getPropertyDefinitions());