DependencyTrait.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. namespace Drupal\Core\Entity;
  3. /**
  4. * Provides a trait for managing an object's dependencies.
  5. */
  6. trait DependencyTrait {
  7. /**
  8. * The object's dependencies.
  9. *
  10. * @var array
  11. */
  12. protected $dependencies = [];
  13. /**
  14. * Adds a dependency.
  15. *
  16. * @param string $type
  17. * Type of dependency being added: 'module', 'theme', 'config', 'content'.
  18. * @param string $name
  19. * If $type is 'module' or 'theme', the name of the module or theme. If
  20. * $type is 'config' or 'content', the result of
  21. * EntityInterface::getConfigDependencyName().
  22. *
  23. * @see \Drupal\Core\Entity\EntityInterface::getConfigDependencyName()
  24. *
  25. * @return $this
  26. */
  27. protected function addDependency($type, $name) {
  28. if (empty($this->dependencies[$type])) {
  29. $this->dependencies[$type] = [$name];
  30. if (count($this->dependencies) > 1) {
  31. // Ensure a consistent order of type keys.
  32. ksort($this->dependencies);
  33. }
  34. }
  35. elseif (!in_array($name, $this->dependencies[$type])) {
  36. $this->dependencies[$type][] = $name;
  37. // Ensure a consistent order of dependency names.
  38. sort($this->dependencies[$type], SORT_FLAG_CASE);
  39. }
  40. return $this;
  41. }
  42. /**
  43. * Adds multiple dependencies.
  44. *
  45. * @param array $dependencies
  46. * An array of dependencies keyed by the type of dependency. One example:
  47. * @code
  48. * array(
  49. * 'module' => array(
  50. * 'node',
  51. * 'field',
  52. * 'image',
  53. * ),
  54. * );
  55. * @endcode
  56. *
  57. * @see \Drupal\Core\Entity\DependencyTrait::addDependency
  58. */
  59. protected function addDependencies(array $dependencies) {
  60. foreach ($dependencies as $dependency_type => $list) {
  61. foreach ($list as $name) {
  62. $this->addDependency($dependency_type, $name);
  63. }
  64. }
  65. }
  66. }