f843892e5da1c2c4cf490dda4b364590a7aaadbb
[yaffs-website] / web / core / modules / views / tests / src / Kernel / ViewExecutableTest.php
1 <?php
2
3 namespace Drupal\Tests\views\Kernel;
4
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;
23
24 /**
25  * Tests the ViewExecutable class.
26  *
27  * @group views
28  * @see \Drupal\views\ViewExecutable
29  */
30 class ViewExecutableTest extends ViewsKernelTestBase {
31
32   use CommentTestTrait;
33
34   public static $modules = ['system', 'node', 'comment', 'user', 'filter', 'field', 'text'];
35
36   /**
37    * Views used by this test.
38    *
39    * @var array
40    */
41   public static $testViews = ['test_destroy', 'test_executable_displays'];
42
43   /**
44    * Properties that should be stored in the configuration.
45    *
46    * @var array
47    */
48   protected $configProperties = [
49     'disabled',
50     'name',
51     'description',
52     'tag',
53     'base_table',
54     'label',
55     'core',
56     'display',
57   ];
58
59   /**
60    * Properties that should be stored in the executable.
61    *
62    * @var array
63    */
64   protected $executableProperties = [
65     'storage',
66     'built',
67     'executed',
68     'args',
69     'build_info',
70     'result',
71     'attachment_before',
72     'attachment_after',
73     'exposed_data',
74     'exposed_raw_input',
75     'old_view',
76     'parent_views',
77   ];
78
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']);
85
86     NodeType::create([
87       'type' => 'page',
88       'name' => 'Page',
89     ])->save();
90     $this->addDefaultCommentField('node', 'page');
91     parent::setUpFixtures();
92
93     $this->installConfig(['filter']);
94   }
95
96   /**
97    * Tests the views.executable container service.
98    */
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.');
104   }
105
106   /**
107    * Tests the initDisplay() and initHandlers() methods.
108    */
109   public function testInitMethods() {
110     $view = Views::getView('test_destroy');
111     $view->initDisplay();
112
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.');
115
116     $view->destroy();
117     $view->initHandlers();
118
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') {
124         continue;
125       }
126       $this->assertTrue(count($view->$type), format_string('Make sure a %type instance got instantiated.', ['%type' => $type]));
127     }
128
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.');
132
133     $view_hash = spl_object_hash($view);
134     $display_hash = spl_object_hash($view->display_handler);
135
136     // Test the initStyle() method.
137     $view->initStyle();
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
140     // display handler.
141     $this->assertEqual(spl_object_hash($view->style_plugin->view), $view_hash);
142     $this->assertEqual(spl_object_hash($view->style_plugin->displayHandler), $display_hash);
143
144     // Test the initQuery method().
145     $view->initQuery();
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);
149
150     $view->destroy();
151
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.');
157
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.');
162
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.');
167
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.');
172   }
173
174   /**
175    * Tests the generation of the executable object.
176    */
177   public function testConstructing() {
178     Views::getView('test_destroy');
179   }
180
181   /**
182    * Tests the accessing of values on the object.
183    */
184   public function testProperties() {
185     $view = Views::getView('test_destroy');
186     foreach ($this->executableProperties as $property) {
187       $this->assertTrue(isset($view->{$property}));
188     }
189
190     // Per default exposed input should fall back to an empty array.
191     $this->assertEqual($view->getExposedInput(), []);
192   }
193
194   public function testSetDisplayWithInvalidDisplay() {
195     $view = Views::getView('test_executable_displays');
196     $view->initDisplay();
197
198     // Error is triggered while calling the wrong display.
199     $this->setExpectedException(\PHPUnit_Framework_Error::class);
200     $view->setDisplay('invalid');
201
202     $this->assertEqual($view->current_display, 'default', 'If setDisplay is called with an invalid display id the default display should be used.');
203     $this->assertEqual(spl_object_hash($view->display_handler), spl_object_hash($view->displayHandlers->get('default')));
204   }
205
206   /**
207    * Tests the display related methods and properties.
208    */
209   public function testDisplays() {
210     $view = Views::getView('test_executable_displays');
211
212     // Tests Drupal\views\ViewExecutable::initDisplay().
213     $view->initDisplay();
214     $this->assertTrue($view->displayHandlers instanceof DisplayPluginCollection, 'The displayHandlers property has the right class.');
215     // Tests the classes of the instances.
216     $this->assertTrue($view->displayHandlers->get('default') instanceof DefaultDisplay);
217     $this->assertTrue($view->displayHandlers->get('page_1') instanceof Page);
218     $this->assertTrue($view->displayHandlers->get('page_2') instanceof Page);
219
220     // After initializing the default display is the current used display.
221     $this->assertEqual($view->current_display, 'default');
222     $this->assertEqual(spl_object_hash($view->display_handler), spl_object_hash($view->displayHandlers->get('default')));
223
224     // All handlers should have a reference to the default display.
225     $this->assertEqual(spl_object_hash($view->displayHandlers->get('page_1')->default_display), spl_object_hash($view->displayHandlers->get('default')));
226     $this->assertEqual(spl_object_hash($view->displayHandlers->get('page_2')->default_display), spl_object_hash($view->displayHandlers->get('default')));
227
228     // Tests Drupal\views\ViewExecutable::setDisplay().
229     $view->setDisplay();
230     $this->assertEqual($view->current_display, 'default', 'If setDisplay is called with no parameter the default display should be used.');
231     $this->assertEqual(spl_object_hash($view->display_handler), spl_object_hash($view->displayHandlers->get('default')));
232
233     // Set two different valid displays.
234     $view->setDisplay('page_1');
235     $this->assertEqual($view->current_display, 'page_1', 'If setDisplay is called with a valid display id the appropriate display should be used.');
236     $this->assertEqual(spl_object_hash($view->display_handler), spl_object_hash($view->displayHandlers->get('page_1')));
237
238     $view->setDisplay('page_2');
239     $this->assertEqual($view->current_display, 'page_2', 'If setDisplay is called with a valid display id the appropriate display should be used.');
240     $this->assertEqual(spl_object_hash($view->display_handler), spl_object_hash($view->displayHandlers->get('page_2')));
241
242     // Destroy the view, so we can start again and test an invalid display.
243     $view->destroy();
244
245     // Test the style and row plugins are replaced correctly when setting the
246     // display.
247     $view->setDisplay('page_1');
248     $view->initStyle();
249     $this->assertTrue($view->style_plugin instanceof DefaultStyle);
250     $this->assertTrue($view->rowPlugin instanceof Fields);
251
252     $view->setDisplay('page_2');
253     $view->initStyle();
254     $this->assertTrue($view->style_plugin instanceof Grid);
255     // @todo Change this rowPlugin type too.
256     $this->assertTrue($view->rowPlugin instanceof Fields);
257
258     // Test the newDisplay() method.
259     $view = $this->container->get('entity.manager')->getStorage('view')->create(['id' => 'test_executable_displays']);
260     $executable = $view->getExecutable();
261
262     $executable->newDisplay('page');
263     $executable->newDisplay('page');
264     $executable->newDisplay('display_test');
265
266     $this->assertTrue($executable->displayHandlers->get('default') instanceof DefaultDisplay);
267     $this->assertFalse(isset($executable->displayHandlers->get('default')->default_display));
268     $this->assertTrue($executable->displayHandlers->get('page_1') instanceof Page);
269     $this->assertTrue($executable->displayHandlers->get('page_1')->default_display instanceof DefaultDisplay);
270     $this->assertTrue($executable->displayHandlers->get('page_2') instanceof Page);
271     $this->assertTrue($executable->displayHandlers->get('page_2')->default_display instanceof DefaultDisplay);
272     $this->assertTrue($executable->displayHandlers->get('display_test_1') instanceof DisplayTest);
273     $this->assertTrue($executable->displayHandlers->get('display_test_1')->default_display instanceof DefaultDisplay);
274   }
275
276   /**
277    * Tests the setting/getting of properties.
278    */
279   public function testPropertyMethods() {
280     $view = Views::getView('test_executable_displays');
281
282     // Test the setAjaxEnabled() method.
283     $this->assertFalse($view->ajaxEnabled());
284     $view->setAjaxEnabled(TRUE);
285     $this->assertTrue($view->ajaxEnabled());
286
287     $view->setDisplay();
288     // There should be no pager set initially.
289     $this->assertNull($view->usePager());
290
291     // Add a pager, initialize, and test.
292     $view->displayHandlers->get('default')->overrideOption('pager', [
293       'type' => 'full',
294       'options' => ['items_per_page' => 10],
295     ]);
296     $view->initPager();
297     $this->assertTrue($view->usePager());
298
299     // Test setting and getting the offset.
300     $rand = rand();
301     $view->setOffset($rand);
302     $this->assertEqual($view->getOffset(), $rand);
303
304     // Test the getBaseTable() method.
305     $expected = [
306       'views_test_data' => TRUE,
307       '#global' => TRUE,
308     ];
309     $this->assertIdentical($view->getBaseTables(), $expected);
310
311     // Test response methods.
312     $this->assertTrue($view->getResponse() instanceof Response, 'New response object returned.');
313     $new_response = new Response();
314     $view->setResponse($new_response);
315     $this->assertIdentical(spl_object_hash($view->getResponse()), spl_object_hash($new_response), 'New response object correctly set.');
316
317     // Test the getPath() method.
318     $path = $this->randomMachineName();
319     $view->displayHandlers->get('page_1')->overrideOption('path', $path);
320     $view->setDisplay('page_1');
321     $this->assertEqual($view->getPath(), $path);
322     // Test the override_path property override.
323     $override_path = $this->randomMachineName();
324     $view->override_path = $override_path;
325     $this->assertEqual($view->getPath(), $override_path);
326
327     // Test the title methods.
328     $title = $this->randomString();
329     $view->setTitle($title);
330     $this->assertEqual($view->getTitle(), Xss::filterAdmin($title));
331   }
332
333   /**
334    * Tests the deconstructor to be sure that necessary objects are removed.
335    */
336   public function testDestroy() {
337     $view = Views::getView('test_destroy');
338
339     $view->preview();
340     $view->destroy();
341
342     $this->assertViewDestroy($view);
343   }
344
345   /**
346    * Asserts that expected view properties have been unset by destroy().
347    *
348    * @param \Drupal\views\ViewExecutable $view
349    */
350   protected function assertViewDestroy($view) {
351     $reflection = new \ReflectionClass($view);
352     $defaults = $reflection->getDefaultProperties();
353     // The storage and user should remain.
354     unset(
355       $defaults['storage'],
356       $defaults['user'],
357       $defaults['request'],
358       $defaults['routeProvider'],
359       $defaults['viewsData']
360     );
361
362     foreach ($defaults as $property => $default) {
363       $this->assertIdentical($this->getProtectedProperty($view, $property), $default);
364     }
365   }
366
367   /**
368    * Returns a protected property from a class instance.
369    *
370    * @param object $instance
371    *   The class instance to return the property from.
372    * @param string $property
373    *   The name of the property to return.
374    *
375    * @return mixed
376    *   The instance property value.
377    */
378   protected function getProtectedProperty($instance, $property) {
379     $reflection = new \ReflectionProperty($instance, $property);
380     $reflection->setAccessible(TRUE);
381     return $reflection->getValue($instance);
382   }
383
384   /**
385    * Tests ViewExecutable::getHandlerTypes().
386    */
387   public function testGetHandlerTypes() {
388     $types = ViewExecutable::getHandlerTypes();
389     foreach (['field', 'filter', 'argument', 'sort', 'header', 'footer', 'empty'] as $type) {
390       $this->assertTrue(isset($types[$type]));
391       // @todo The key on the display should be footers, headers and empties
392       //   or something similar instead of the singular, but so long check for
393       //   this special case.
394       if (isset($types[$type]['type']) && $types[$type]['type'] == 'area') {
395         $this->assertEqual($types[$type]['plural'], $type);
396       }
397       else {
398         $this->assertEqual($types[$type]['plural'], $type . 's');
399       }
400     }
401   }
402
403   /**
404    * Tests ViewExecutable::getHandlers().
405    */
406   public function testGetHandlers() {
407     $view = Views::getView('test_executable_displays');
408     $view->setDisplay('page_1');
409
410     $view->getHandlers('field', 'page_2');
411
412     // getHandlers() shouldn't change the active display.
413     $this->assertEqual('page_1', $view->current_display, "The display shouldn't change after getHandlers()");
414   }
415
416   /**
417    * Tests the validation of display handlers.
418    */
419   public function testValidate() {
420     $view = Views::getView('test_executable_displays');
421     $view->setDisplay('page_1');
422
423     $validate = $view->validate();
424
425     // Validating a view shouldn't change the active display.
426     $this->assertEqual('page_1', $view->current_display, "The display should be constant while validating");
427
428     $count = 0;
429     foreach ($view->displayHandlers as $id => $display) {
430       $match = function($value) use ($display) {
431         return strpos($value, $display->display['display_title']) !== FALSE;
432       };
433       $this->assertTrue(array_filter($validate[$id], $match), format_string('Error message found for @id display', ['@id' => $id]));
434       $count++;
435     }
436
437     $this->assertEqual(count($view->displayHandlers), $count, 'Error messages from all handlers merged.');
438
439     // Test that a deleted display is not included.
440     $display = &$view->storage->getDisplay('default');
441     $display['deleted'] = TRUE;
442     $validate_deleted = $view->validate();
443
444     $this->assertNotIdentical($validate, $validate_deleted, 'Master display has not been validated.');
445   }
446
447   /**
448    * Tests that nested loops of the display handlers won't break validation.
449    */
450   public function testValidateNestedLoops() {
451     $view = View::create(['id' => 'test_validate_nested_loops']);
452     $executable = $view->getExecutable();
453
454     $executable->newDisplay('display_test');
455     $executable->newDisplay('display_test');
456     $errors = $executable->validate();
457     $total_error_count = array_reduce($errors, function ($carry, $item) {
458       $carry += count($item);
459
460       return $carry;
461     });
462     // Assert that there were 9 total errors across 3 displays.
463     $this->assertIdentical(9, $total_error_count);
464     $this->assertIdentical(3, count($errors));
465   }
466
467   /**
468    * Tests serialization of the ViewExecutable object.
469    */
470   public function testSerialization() {
471     $view = Views::getView('test_executable_displays');
472     $view->setDisplay('page_1');
473     $view->setArguments(['test']);
474     $view->setCurrentPage(2);
475
476     $serialized = serialize($view);
477
478     // Test the view storage object is not present in the actual serialized
479     // string.
480     $this->assertIdentical(strpos($serialized, '"Drupal\views\Entity\View"'), FALSE, 'The Drupal\views\Entity\View class was not found in the serialized string.');
481
482     /** @var \Drupal\views\ViewExecutable $unserialized */
483     $unserialized = unserialize($serialized);
484
485     $this->assertTrue($unserialized instanceof ViewExecutable);
486     $this->assertIdentical($view->storage->id(), $unserialized->storage->id(), 'The expected storage entity was loaded on the unserialized view.');
487     $this->assertIdentical($unserialized->current_display, 'page_1', 'The expected display was set on the unserialized view.');
488     $this->assertIdentical($unserialized->args, ['test'], 'The expected argument was set on the unserialized view.');
489     $this->assertIdentical($unserialized->getCurrentPage(), 2, 'The expected current page was set on the unserialized view.');
490   }
491
492 }