public static BubbleableMetadata::mergeAttachments(array $a, array $b)
Merges two attachments arrays (which live under the '#attached' key).
The values under the 'drupalSettings' key are merged in a special way, to match the behavior of:
jQuery.extend(true, {}, $settings_items[0], $settings_items[1], ...)
This means integer indices are preserved just like string indices are, rather than re-indexed as is common in PHP array merging.
Example:
function module1_page_attachments(&$page) { $page['a']['#attached']['drupalSettings']['foo'] = ['a', 'b', 'c']; } function module2_page_attachments(&$page) { $page['#attached']['drupalSettings']['foo'] = ['d']; } // When the page is rendered after the above code, and the browser runs the // resulting <SCRIPT> tags, the value of drupalSettings.foo is // ['d', 'b', 'c'], not ['a', 'b', 'c', 'd'].
By following jQuery.extend() merge logic rather than common PHP array merge logic, the following are ensured:
array $a: An attachments array.
array $b: Another attachments array.
array The merged attachments array.
public static function mergeAttachments(array $a, array $b) { // If both #attached arrays contain drupalSettings, then merge them // correctly; adding the same settings multiple times needs to behave // idempotently. if (!empty($a['drupalSettings']) && !empty($b['drupalSettings'])) { $drupalSettings = NestedArray::mergeDeepArray(array($a['drupalSettings'], $b['drupalSettings']), TRUE); // No need for re-merging them. unset($a['drupalSettings']); unset($b['drupalSettings']); } // Optimize merging of placeholders: no need for deep merging. if (!empty($a['placeholders']) && !empty($b['placeholders'])) { $placeholders = $a['placeholders'] + $b['placeholders']; // No need for re-merging them. unset($a['placeholders']); unset($b['placeholders']); } // Apply the normal merge. $a = array_merge_recursive($a, $b); if (isset($drupalSettings)) { // Save the custom merge for the drupalSettings. $a['drupalSettings'] = $drupalSettings; } if (isset($placeholders)) { // Save the custom merge for the placeholders. $a['placeholders'] = $placeholders; } return $a; }
© 2001–2016 by the original authors
Licensed under the GNU General Public License, version 2 and later.
Drupal is a registered trademark of Dries Buytaert.
https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Render!BubbleableMetadata.php/function/BubbleableMetadata::mergeAttachments/8.1.x