66e06c88a467147c0d616b876e186f6d2db1bd42
[yaffs-website] / web / core / modules / system / src / Tests / Ajax / AjaxTestBase.php
1 <?php
2
3 namespace Drupal\system\Tests\Ajax;
4
5 use Drupal\simpletest\WebTestBase;
6
7 /**
8  * Provides a base class for Ajax tests.
9  */
10 abstract class AjaxTestBase extends WebTestBase {
11
12   /**
13    * Modules to enable.
14    *
15    * @var array
16    */
17   public static $modules = ['node', 'ajax_test', 'ajax_forms_test'];
18
19   /**
20    * Asserts the array of Ajax commands contains the searched command.
21    *
22    * An AjaxResponse object stores an array of Ajax commands. This array
23    * sometimes includes commands automatically provided by the framework in
24    * addition to commands returned by a particular controller. During testing,
25    * we're usually interested that a particular command is present, and don't
26    * care whether other commands precede or follow the one we're interested in.
27    * Additionally, the command we're interested in may include additional data
28    * that we're not interested in. Therefore, this function simply asserts that
29    * one of the commands in $haystack contains all of the keys and values in
30    * $needle. Furthermore, if $needle contains a 'settings' key with an array
31    * value, we simply assert that all keys and values within that array are
32    * present in the command we're checking, and do not consider it a failure if
33    * the actual command contains additional settings that aren't part of
34    * $needle.
35    *
36    * @param $haystack
37    *   An array of rendered Ajax commands returned by the server.
38    * @param $needle
39    *   Array of info we're expecting in one of those commands.
40    * @param $message
41    *   An assertion message.
42    */
43   protected function assertCommand($haystack, $needle, $message) {
44     $found = FALSE;
45     foreach ($haystack as $command) {
46       // If the command has additional settings that we're not testing for, do
47       // not consider that a failure.
48       if (isset($command['settings']) && is_array($command['settings']) && isset($needle['settings']) && is_array($needle['settings'])) {
49         $command['settings'] = array_intersect_key($command['settings'], $needle['settings']);
50       }
51       // If the command has additional data that we're not testing for, do not
52       // consider that a failure. Also, == instead of ===, because we don't
53       // require the key/value pairs to be in any particular order
54       // (http://php.net/manual/language.operators.array.php).
55       if (array_intersect_key($command, $needle) == $needle) {
56         $found = TRUE;
57         break;
58       }
59     }
60     $this->assertTrue($found, $message);
61   }
62
63 }