AttributeHelper.php 2.4 KB

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