1<?php 2 3namespace Drupal\Core\Template; 4 5use Drupal\Component\Utility\NestedArray; 6 7/** 8 * Helper class to deal with mixed array and Attribute operations. 9 * 10 * This class contains static methods only and is not meant to be instantiated. 11 */ 12class AttributeHelper { 13 14 /** 15 * This class should not be instantiated. 16 */ 17 private function __construct() { 18 } 19 20 /** 21 * Checks if the given attribute collection has an attribute. 22 * 23 * @param string $name 24 * The name of the attribute to check for. 25 * @param \Drupal\Core\Template\Attribute|array $collection 26 * An Attribute object or an array of attributes. 27 * 28 * @return bool 29 * TRUE if the attribute exists, FALSE otherwise. 30 * 31 * @throws \InvalidArgumentException 32 * When the input $collection is neither an Attribute object nor an array. 33 */ 34 public static function attributeExists($name, $collection) { 35 if ($collection instanceof Attribute) { 36 return $collection->hasAttribute($name); 37 } 38 elseif (is_array($collection)) { 39 return array_key_exists($name, $collection); 40 } 41 throw new \InvalidArgumentException('Invalid collection argument'); 42 } 43 44 /** 45 * Merges two attribute collections. 46 * 47 * @param \Drupal\Core\Template\Attribute|array $a 48 * First Attribute object or array to merge. The returned value type will 49 * be the same as the type of this argument. 50 * @param \Drupal\Core\Template\Attribute|array $b 51 * Second Attribute object or array to merge. 52 * 53 * @return \Drupal\Core\Template\Attribute|array 54 * The merged attributes, as an Attribute object or an array. 55 * 56 * @throws \InvalidArgumentException 57 * If at least one collection argument is neither an Attribute object nor an 58 * array. 59 */ 60 public static function mergeCollections($a, $b) { 61 if (!($a instanceof Attribute || is_array($a)) || !($b instanceof Attribute || is_array($b))) { 62 throw new \InvalidArgumentException('Invalid collection argument'); 63 } 64 // If both collections are arrays, just merge them. 65 if (is_array($a) && is_array($b)) { 66 return NestedArray::mergeDeep($a, $b); 67 } 68 // If at least one collections is an Attribute object, merge through 69 // Attribute::merge. 70 $merge_a = $a instanceof Attribute ? $a : new Attribute($a); 71 $merge_b = $b instanceof Attribute ? $b : new Attribute($b); 72 $merge_a->merge($merge_b); 73 return $a instanceof Attribute ? $merge_a : $merge_a->toArray(); 74 } 75 76} 77