Version 1
[yaffs-website] / web / core / modules / system / src / Tests / Theme / ThemeTest.php
1 <?php
2
3 namespace Drupal\system\Tests\Theme;
4
5 use Drupal\Component\Serialization\Json;
6 use Drupal\simpletest\WebTestBase;
7 use Drupal\test_theme\ThemeClass;
8 use Symfony\Cmf\Component\Routing\RouteObjectInterface;
9 use Symfony\Component\HttpFoundation\Request;
10 use Symfony\Component\Routing\Route;
11 use Drupal\Component\Render\MarkupInterface;
12
13 /**
14  * Tests low-level theme functions.
15  *
16  * @group Theme
17  */
18 class ThemeTest extends WebTestBase {
19
20   /**
21    * Modules to enable.
22    *
23    * @var array
24    */
25   public static $modules = ['theme_test', 'node'];
26
27   protected function setUp() {
28     parent::setUp();
29     \Drupal::service('theme_handler')->install(['test_theme']);
30   }
31
32   /**
33    * Test attribute merging.
34    *
35    * Render arrays that use a render element and templates (and hence call
36    * template_preprocess()) must ensure the attributes at different occasions
37    * are all merged correctly:
38    *   - $variables['attributes'] as passed in to the theme hook implementation.
39    *   - the render element's #attributes
40    *   - any attributes set in the template's preprocessing function
41    */
42   public function testAttributeMerging() {
43     $theme_test_render_element = [
44       'elements' => [
45         '#attributes' => ['data-foo' => 'bar'],
46       ],
47       'attributes' => [
48         'id' => 'bazinga',
49       ],
50     ];
51     $this->assertThemeOutput('theme_test_render_element', $theme_test_render_element, '<div id="bazinga" data-foo="bar" data-variables-are-preprocessed></div>' . "\n");
52   }
53
54   /**
55    * Test that ThemeManager renders the expected data types.
56    */
57   public function testThemeDataTypes() {
58     // theme_test_false is an implemented theme hook so \Drupal::theme() service
59     // should return a string or an object that implements MarkupInterface,
60     // even though the theme function itself can return anything.
61     $foos = ['null' => NULL, 'false' => FALSE, 'integer' => 1, 'string' => 'foo', 'empty_string' => ''];
62     foreach ($foos as $type => $example) {
63       $output = \Drupal::theme()->render('theme_test_foo', ['foo' => $example]);
64       $this->assertTrue($output instanceof MarkupInterface || is_string($output), format_string('\Drupal::theme() returns an object that implements MarkupInterface or a string for data type @type.', ['@type' => $type]));
65       if ($output instanceof MarkupInterface) {
66         $this->assertIdentical((string) $example, $output->__toString());
67       }
68       elseif (is_string($output)) {
69         $this->assertIdentical($output, '', 'A string will be return when the theme returns an empty string.');
70       }
71     }
72
73     // suggestionnotimplemented is not an implemented theme hook so \Drupal::theme() service
74     // should return FALSE instead of a string.
75     $output = \Drupal::theme()->render(['suggestionnotimplemented'], []);
76     $this->assertIdentical($output, FALSE, '\Drupal::theme() returns FALSE when a hook suggestion is not implemented.');
77   }
78
79   /**
80    * Test function theme_get_suggestions() for SA-CORE-2009-003.
81    */
82   public function testThemeSuggestions() {
83     // Set the front page as something random otherwise the CLI
84     // test runner fails.
85     $this->config('system.site')->set('page.front', '/nobody-home')->save();
86     $args = ['node', '1', 'edit'];
87     $suggestions = theme_get_suggestions($args, 'page');
88     $this->assertEqual($suggestions, ['page__node', 'page__node__%', 'page__node__1', 'page__node__edit'], 'Found expected node edit page suggestions');
89     // Check attack vectors.
90     $args = ['node', '\\1'];
91     $suggestions = theme_get_suggestions($args, 'page');
92     $this->assertEqual($suggestions, ['page__node', 'page__node__%', 'page__node__1'], 'Removed invalid \\ from suggestions');
93     $args = ['node', '1/'];
94     $suggestions = theme_get_suggestions($args, 'page');
95     $this->assertEqual($suggestions, ['page__node', 'page__node__%', 'page__node__1'], 'Removed invalid / from suggestions');
96     $args = ['node', "1\0"];
97     $suggestions = theme_get_suggestions($args, 'page');
98     $this->assertEqual($suggestions, ['page__node', 'page__node__%', 'page__node__1'], 'Removed invalid \\0 from suggestions');
99     // Define path with hyphens to be used to generate suggestions.
100     $args = ['node', '1', 'hyphen-path'];
101     $result = ['page__node', 'page__node__%', 'page__node__1', 'page__node__hyphen_path'];
102     $suggestions = theme_get_suggestions($args, 'page');
103     $this->assertEqual($suggestions, $result, 'Found expected page suggestions for paths containing hyphens.');
104   }
105
106   /**
107    * Ensures preprocess functions run even for suggestion implementations.
108    *
109    * The theme hook used by this test has its base preprocess function in a
110    * separate file, so this test also ensures that that file is correctly loaded
111    * when needed.
112    */
113   public function testPreprocessForSuggestions() {
114     // Test with both an unprimed and primed theme registry.
115     drupal_theme_rebuild();
116     for ($i = 0; $i < 2; $i++) {
117       $this->drupalGet('theme-test/suggestion');
118       $this->assertText('Theme hook implementor=test_theme_theme_test__suggestion(). Foo=template_preprocess_theme_test', 'Theme hook suggestion ran with data available from a preprocess function for the base hook.');
119     }
120   }
121
122   /**
123    * Tests the priority of some theme negotiators.
124    */
125   public function testNegotiatorPriorities() {
126     $this->drupalGet('theme-test/priority');
127
128     // Ensure that the custom theme negotiator was not able to set the theme.
129
130     $this->assertNoText('Theme hook implementor=test_theme_theme_test__suggestion(). Foo=template_preprocess_theme_test', 'Theme hook suggestion ran with data available from a preprocess function for the base hook.');
131   }
132
133   /**
134    * Ensures that non-HTML requests never initialize themes.
135    */
136   public function testThemeOnNonHtmlRequest() {
137     $this->drupalGet('theme-test/non-html');
138     $json = Json::decode($this->getRawContent());
139     $this->assertFalse($json['theme_initialized']);
140   }
141
142   /**
143    * Ensure page-front template suggestion is added when on front page.
144    */
145   public function testFrontPageThemeSuggestion() {
146     // Set the current route to user.login because theme_get_suggestions() will
147     // query it to see if we are on the front page.
148     $request = Request::create('/user/login');
149     $request->attributes->set(RouteObjectInterface::ROUTE_NAME, 'user.login');
150     $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('/user/login'));
151     \Drupal::requestStack()->push($request);
152     $this->config('system.site')->set('page.front', '/user/login')->save();
153     $suggestions = theme_get_suggestions(['user', 'login'], 'page');
154     // Set it back to not annoy the batch runner.
155     \Drupal::requestStack()->pop();
156     $this->assertTrue(in_array('page__front', $suggestions), 'Front page template was suggested.');
157   }
158
159   /**
160    * Ensures a theme's .info.yml file is able to override a module CSS file from being added to the page.
161    *
162    * @see test_theme.info.yml
163    */
164   public function testCSSOverride() {
165     // Reuse the same page as in testPreprocessForSuggestions(). We're testing
166     // what is output to the HTML HEAD based on what is in a theme's .info.yml
167     // file, so it doesn't matter what page we get, as long as it is themed with
168     // the test theme. First we test with CSS aggregation disabled.
169     $config = $this->config('system.performance');
170     $config->set('css.preprocess', 0);
171     $config->save();
172     $this->drupalGet('theme-test/suggestion');
173     $this->assertNoText('js.module.css', 'The theme\'s .info.yml file is able to override a module CSS file from being added to the page.');
174
175     // Also test with aggregation enabled, simply ensuring no PHP errors are
176     // triggered during drupal_build_css_cache() when a source file doesn't
177     // exist. Then allow remaining tests to continue with aggregation disabled
178     // by default.
179     $config->set('css.preprocess', 1);
180     $config->save();
181     $this->drupalGet('theme-test/suggestion');
182     $config->set('css.preprocess', 0);
183     $config->save();
184   }
185
186   /**
187    * Ensures a themes template is overridable based on the 'template' filename.
188    */
189   public function testTemplateOverride() {
190     $this->config('system.theme')
191       ->set('default', 'test_theme')
192       ->save();
193     $this->drupalGet('theme-test/template-test');
194     $this->assertText('Success: Template overridden.', 'Template overridden by defined \'template\' filename.');
195   }
196
197   /**
198    * Ensures a theme template can override a theme function.
199    */
200   public function testFunctionOverride() {
201     $this->drupalGet('theme-test/function-template-overridden');
202     $this->assertText('Success: Template overrides theme function.', 'Theme function overridden by test_theme template.');
203   }
204
205   /**
206    * Test the listInfo() function.
207    */
208   public function testListThemes() {
209     $theme_handler = $this->container->get('theme_handler');
210     $theme_handler->install(['test_subtheme']);
211     $themes = $theme_handler->listInfo();
212
213     // Check if ThemeHandlerInterface::listInfo() retrieves enabled themes.
214     $this->assertIdentical(1, $themes['test_theme']->status, 'Installed theme detected');
215
216     // Check if ThemeHandlerInterface::listInfo() returns disabled themes.
217     // Check for base theme and subtheme lists.
218     $base_theme_list = ['test_basetheme' => 'Theme test base theme'];
219     $sub_theme_list = ['test_subsubtheme' => 'Theme test subsubtheme', 'test_subtheme' => 'Theme test subtheme'];
220
221     $this->assertIdentical($themes['test_basetheme']->sub_themes, $sub_theme_list, 'Base theme\'s object includes list of subthemes.');
222     $this->assertIdentical($themes['test_subtheme']->base_themes, $base_theme_list, 'Subtheme\'s object includes list of base themes.');
223     // Check for theme engine in subtheme.
224     $this->assertIdentical($themes['test_subtheme']->engine, 'twig', 'Subtheme\'s object includes the theme engine.');
225     // Check for theme engine prefix.
226     $this->assertIdentical($themes['test_basetheme']->prefix, 'twig', 'Base theme\'s object includes the theme engine prefix.');
227     $this->assertIdentical($themes['test_subtheme']->prefix, 'twig', 'Subtheme\'s object includes the theme engine prefix.');
228   }
229
230   /**
231    * Tests child element rendering for 'render element' theme hooks.
232    */
233   public function testDrupalRenderChildren() {
234     $element = [
235       '#theme' => 'theme_test_render_element_children',
236       'child' => [
237         '#markup' => 'Foo',
238       ],
239     ];
240     $this->assertThemeOutput('theme_test_render_element_children', $element, 'Foo', 'drupal_render() avoids #theme recursion loop when rendering a render element.');
241
242     $element = [
243       '#theme_wrappers' => ['theme_test_render_element_children'],
244       'child' => [
245         '#markup' => 'Foo',
246       ],
247     ];
248     $this->assertThemeOutput('theme_test_render_element_children', $element, 'Foo', 'drupal_render() avoids #theme_wrappers recursion loop when rendering a render element.');
249   }
250
251   /**
252    * Tests theme can provide classes.
253    */
254   public function testClassLoading() {
255     new ThemeClass();
256   }
257
258   /**
259    * Tests drupal_find_theme_templates().
260    */
261   public function testFindThemeTemplates() {
262     $registry = $this->container->get('theme.registry')->get();
263     $templates = drupal_find_theme_templates($registry, '.html.twig', drupal_get_path('theme', 'test_theme'));
264     $this->assertEqual($templates['node__1']['template'], 'node--1', 'Template node--1.tpl.twig was found in test_theme.');
265   }
266
267   /**
268    * Tests that the page variable is not prematurely flattened.
269    *
270    * Some modules check the page array in template_preprocess_html(), so we
271    * ensure that it has not been rendered prematurely.
272    */
273   public function testPreprocessHtml() {
274     $this->drupalGet('');
275     $attributes = $this->xpath('/html/body[@theme_test_page_variable="Page variable is an array."]');
276     $this->assertTrue(count($attributes) == 1, 'In template_preprocess_html(), the page variable is still an array (not rendered yet).');
277     $this->assertText('theme test page bottom markup', 'Modules are able to set the page bottom region.');
278   }
279
280   /**
281    * Tests that region attributes can be manipulated via preprocess functions.
282    */
283   public function testRegionClass() {
284     \Drupal::service('module_installer')->install(['block', 'theme_region_test']);
285
286     // Place a block.
287     $this->drupalPlaceBlock('system_main_block');
288     $this->drupalGet('');
289     $elements = $this->cssSelect(".region-sidebar-first.new_class");
290     $this->assertEqual(count($elements), 1, 'New class found.');
291   }
292
293   /**
294    * Ensures suggestion preprocess functions run for default implementations.
295    *
296    * The theme hook used by this test has its base preprocess function in a
297    * separate file, so this test also ensures that that file is correctly loaded
298    * when needed.
299    */
300   public function testSuggestionPreprocessForDefaults() {
301     $this->config('system.theme')->set('default', 'test_theme')->save();
302     // Test with both an unprimed and primed theme registry.
303     drupal_theme_rebuild();
304     for ($i = 0; $i < 2; $i++) {
305       $this->drupalGet('theme-test/preprocess-suggestions');
306       $items = $this->cssSelect('.suggestion');
307       $expected_values = [
308         'Suggestion',
309         'Kitten',
310         'Monkey',
311         'Kitten',
312         'Flamingo',
313       ];
314       foreach ($expected_values as $key => $value) {
315         $this->assertEqual((string) $value, $items[$key]);
316       }
317     }
318   }
319
320 }