Version 1
[yaffs-website] / web / core / modules / system / src / Tests / Ajax / FrameworkTest.php
1 <?php
2
3 namespace Drupal\system\Tests\Ajax;
4
5 use Drupal\Core\Ajax\AddCssCommand;
6 use Drupal\Core\Ajax\AlertCommand;
7 use Drupal\Core\Ajax\AppendCommand;
8 use Drupal\Core\Ajax\HtmlCommand;
9 use Drupal\Core\Ajax\PrependCommand;
10 use Drupal\Core\Ajax\SettingsCommand;
11 use Drupal\Core\Asset\AttachedAssets;
12
13 /**
14  * Performs tests on AJAX framework functions.
15  *
16  * @group Ajax
17  */
18 class FrameworkTest extends AjaxTestBase {
19   /**
20    * Verifies the Ajax rendering of a command in the settings.
21    */
22   public function testAJAXRender() {
23     // Verify that settings command is generated if JavaScript settings exist.
24     $commands = $this->drupalGetAjax('ajax-test/render');
25     $expected = new SettingsCommand(['ajax' => 'test'], TRUE);
26     $this->assertCommand($commands, $expected->render(), 'JavaScript settings command is present.');
27   }
28
29   /**
30    * Tests AjaxResponse::prepare() AJAX commands ordering.
31    */
32   public function testOrder() {
33     $expected_commands = [];
34
35     // Expected commands, in a very specific order.
36     $asset_resolver = \Drupal::service('asset.resolver');
37     $css_collection_renderer = \Drupal::service('asset.css.collection_renderer');
38     $js_collection_renderer = \Drupal::service('asset.js.collection_renderer');
39     $renderer = \Drupal::service('renderer');
40     $expected_commands[0] = new SettingsCommand(['ajax' => 'test'], TRUE);
41     $build['#attached']['library'][] = 'ajax_test/order-css-command';
42     $assets = AttachedAssets::createFromRenderArray($build);
43     $css_render_array = $css_collection_renderer->render($asset_resolver->getCssAssets($assets, FALSE));
44     $expected_commands[1] = new AddCssCommand($renderer->renderRoot($css_render_array));
45     $build['#attached']['library'][] = 'ajax_test/order-header-js-command';
46     $build['#attached']['library'][] = 'ajax_test/order-footer-js-command';
47     $assets = AttachedAssets::createFromRenderArray($build);
48     list($js_assets_header, $js_assets_footer) = $asset_resolver->getJsAssets($assets, FALSE);
49     $js_header_render_array = $js_collection_renderer->render($js_assets_header);
50     $js_footer_render_array = $js_collection_renderer->render($js_assets_footer);
51     $expected_commands[2] = new PrependCommand('head', $js_header_render_array);
52     $expected_commands[3] = new AppendCommand('body', $js_footer_render_array);
53     $expected_commands[4] = new HtmlCommand('body', 'Hello, world!');
54
55     // Load any page with at least one CSS file, at least one JavaScript file
56     // and at least one #ajax-powered element. The latter is an assumption of
57     // drupalPostAjaxForm(), the two former are assumptions of the Ajax
58     // renderer.
59     // @todo refactor AJAX Framework + tests to make less assumptions.
60     $this->drupalGet('ajax_forms_test_lazy_load_form');
61
62     // Verify AJAX command order — this should always be the order:
63     // 1. JavaScript settings
64     // 2. CSS files
65     // 3. JavaScript files in the header
66     // 4. JavaScript files in the footer
67     // 5. Any other AJAX commands, in whatever order they were added.
68     $commands = $this->drupalPostAjaxForm(NULL, [], NULL, 'ajax-test/order', [], [], NULL, []);
69     $this->assertCommand(array_slice($commands, 0, 1), $expected_commands[0]->render(), 'Settings command is first.');
70     $this->assertCommand(array_slice($commands, 1, 1), $expected_commands[1]->render(), 'CSS command is second (and CSS files are ordered correctly).');
71     $this->assertCommand(array_slice($commands, 2, 1), $expected_commands[2]->render(), 'Header JS command is third.');
72     $this->assertCommand(array_slice($commands, 3, 1), $expected_commands[3]->render(), 'Footer JS command is fourth.');
73     $this->assertCommand(array_slice($commands, 4, 1), $expected_commands[4]->render(), 'HTML command is fifth.');
74   }
75
76   /**
77    * Tests the behavior of an error alert command.
78    */
79   public function testAJAXRenderError() {
80     // Verify custom error message.
81     $edit = [
82       'message' => 'Custom error message.',
83     ];
84     $commands = $this->drupalGetAjax('ajax-test/render-error', ['query' => $edit]);
85     $expected = new AlertCommand($edit['message']);
86     $this->assertCommand($commands, $expected->render(), 'Custom error message is output.');
87   }
88
89   /**
90    * Tests that new JavaScript and CSS files are lazy-loaded on an AJAX request.
91    */
92   public function testLazyLoad() {
93     $asset_resolver = \Drupal::service('asset.resolver');
94     $css_collection_renderer = \Drupal::service('asset.css.collection_renderer');
95     $js_collection_renderer = \Drupal::service('asset.js.collection_renderer');
96     $renderer = \Drupal::service('renderer');
97
98     $expected = [
99       'setting_name' => 'ajax_forms_test_lazy_load_form_submit',
100       'setting_value' => 'executed',
101       'library_1' => 'system/admin',
102       'library_2' => 'system/drupal.system',
103     ];
104
105     // Get the base page.
106     $this->drupalGet('ajax_forms_test_lazy_load_form');
107     $original_settings = $this->getDrupalSettings();
108     $original_libraries = explode(',', $original_settings['ajaxPageState']['libraries']);
109
110     // Verify that the base page doesn't have the settings and files that are to
111     // be lazy loaded as part of the next requests.
112     $this->assertTrue(!isset($original_settings[$expected['setting_name']]), format_string('Page originally lacks the %setting, as expected.', ['%setting' => $expected['setting_name']]));
113     $this->assertTrue(!in_array($expected['library_1'], $original_libraries), format_string('Page originally lacks the %library library, as expected.', ['%library' => $expected['library_1']]));
114     $this->assertTrue(!in_array($expected['library_2'], $original_libraries), format_string('Page originally lacks the %library library, as expected.', ['%library' => $expected['library_2']]));
115
116     // Calculate the expected CSS and JS.
117     $assets = new AttachedAssets();
118     $assets->setLibraries([$expected['library_1']])
119       ->setAlreadyLoadedLibraries($original_libraries);
120     $css_render_array = $css_collection_renderer->render($asset_resolver->getCssAssets($assets, FALSE));
121     $expected_css_html = $renderer->renderRoot($css_render_array);
122
123     $assets->setLibraries([$expected['library_2']])
124       ->setAlreadyLoadedLibraries($original_libraries);
125     $js_assets = $asset_resolver->getJsAssets($assets, FALSE)[1];
126     unset($js_assets['drupalSettings']);
127     $js_render_array = $js_collection_renderer->render($js_assets);
128     $expected_js_html = $renderer->renderRoot($js_render_array);
129
130     // Submit the AJAX request without triggering files getting added.
131     $commands = $this->drupalPostAjaxForm(NULL, ['add_files' => FALSE], ['op' => t('Submit')]);
132     $new_settings = $this->getDrupalSettings();
133     $new_libraries = explode(',', $new_settings['ajaxPageState']['libraries']);
134
135     // Verify the setting was not added when not expected.
136     $this->assertTrue(!isset($new_settings[$expected['setting_name']]), format_string('Page still lacks the %setting, as expected.', ['%setting' => $expected['setting_name']]));
137     $this->assertTrue(!in_array($expected['library_1'], $new_libraries), format_string('Page still lacks the %library library, as expected.', ['%library' => $expected['library_1']]));
138     $this->assertTrue(!in_array($expected['library_2'], $new_libraries), format_string('Page still lacks the %library library, as expected.', ['%library' => $expected['library_2']]));
139     // Verify a settings command does not add CSS or scripts to drupalSettings
140     // and no command inserts the corresponding tags on the page.
141     $found_settings_command = FALSE;
142     $found_markup_command = FALSE;
143     foreach ($commands as $command) {
144       if ($command['command'] == 'settings' && (array_key_exists('css', $command['settings']['ajaxPageState']) || array_key_exists('js', $command['settings']['ajaxPageState']))) {
145         $found_settings_command = TRUE;
146       }
147       if (isset($command['data']) && ($command['data'] == $expected_js_html || $command['data'] == $expected_css_html)) {
148         $found_markup_command = TRUE;
149       }
150     }
151     $this->assertFalse($found_settings_command, format_string('Page state still lacks the %library_1 and %library_2 libraries, as expected.', ['%library_1' => $expected['library_1'], '%library_2' => $expected['library_2']]));
152     $this->assertFalse($found_markup_command, format_string('Page still lacks the %library_1 and %library_2 libraries, as expected.', ['%library_1' => $expected['library_1'], '%library_2' => $expected['library_2']]));
153
154     // Submit the AJAX request and trigger adding files.
155     $commands = $this->drupalPostAjaxForm(NULL, ['add_files' => TRUE], ['op' => t('Submit')]);
156     $new_settings = $this->getDrupalSettings();
157     $new_libraries = explode(',', $new_settings['ajaxPageState']['libraries']);
158
159     // Verify the expected setting was added, both to drupalSettings, and as
160     // the first AJAX command.
161     $this->assertIdentical($new_settings[$expected['setting_name']], $expected['setting_value'], format_string('Page now has the %setting.', ['%setting' => $expected['setting_name']]));
162     $expected_command = new SettingsCommand([$expected['setting_name'] => $expected['setting_value']], TRUE);
163     $this->assertCommand(array_slice($commands, 0, 1), $expected_command->render(), 'The settings command was first.');
164
165     // Verify the expected CSS file was added, both to drupalSettings, and as
166     // the second AJAX command for inclusion into the HTML.
167     $this->assertTrue(in_array($expected['library_1'], $new_libraries), format_string('Page state now has the %library library.', ['%library' => $expected['library_1']]));
168     $this->assertCommand(array_slice($commands, 1, 1), ['data' => $expected_css_html], format_string('Page now has the %library library.', ['%library' => $expected['library_1']]));
169
170     // Verify the expected JS file was added, both to drupalSettings, and as
171     // the third AJAX command for inclusion into the HTML. By testing for an
172     // exact HTML string containing the SCRIPT tag, we also ensure that
173     // unexpected JavaScript code, such as a jQuery.extend() that would
174     // potentially clobber rather than properly merge settings, didn't
175     // accidentally get added.
176     $this->assertTrue(in_array($expected['library_2'], $new_libraries), format_string('Page state now has the %library library.', ['%library' => $expected['library_2']]));
177     $this->assertCommand(array_slice($commands, 2, 1), ['data' => $expected_js_html], format_string('Page now has the %library library.', ['%library' => $expected['library_2']]));
178   }
179
180   /**
181    * Tests that drupalSettings.currentPath is not updated on AJAX requests.
182    */
183   public function testCurrentPathChange() {
184     $commands = $this->drupalPostAjaxForm('ajax_forms_test_lazy_load_form', ['add_files' => FALSE], ['op' => t('Submit')]);
185     foreach ($commands as $command) {
186       if ($command['command'] == 'settings') {
187         $this->assertFalse(isset($command['settings']['currentPath']), 'Value of drupalSettings.currentPath is not updated after an AJAX request.');
188       }
189     }
190   }
191
192   /**
193    * Tests that overridden CSS files are not added during lazy load.
194    */
195   public function testLazyLoadOverriddenCSS() {
196     // The test theme overrides js.module.css without an implementation,
197     // thereby removing it.
198     \Drupal::service('theme_handler')->install(['test_theme']);
199     $this->config('system.theme')
200       ->set('default', 'test_theme')
201       ->save();
202
203     // This gets the form, and emulates an Ajax submission on it, including
204     // adding markup to the HEAD and BODY for any lazy loaded JS/CSS files.
205     $this->drupalPostAjaxForm('ajax_forms_test_lazy_load_form', ['add_files' => TRUE], ['op' => t('Submit')]);
206
207     // Verify that the resulting HTML does not load the overridden CSS file.
208     // We add a "?" to the assertion, because drupalSettings may include
209     // information about the file; we only really care about whether it appears
210     // in a LINK or STYLE tag, for which Drupal always adds a query string for
211     // cache control.
212     $this->assertNoText('js.module.css?', 'Ajax lazy loading does not add overridden CSS files.');
213   }
214
215 }