FieldHierarchy.inc 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. <?php
  2. /**
  3. * @file
  4. * Contains the FieldHierarchy class.
  5. */
  6. class FieldHierarchy implements Countable {
  7. /**
  8. * @var array
  9. * The flattened hierarchy data.
  10. */
  11. protected $data = array();
  12. const ROOT = 'root';
  13. public function __get($property) {
  14. return $this->{$property};
  15. }
  16. public function options($key = FieldHierarchy::ROOT, $parent = NULL, $depth = -1) {
  17. $options = array();
  18. $item = $this->data[$key];
  19. if (isset($item['label'])) {
  20. $options[$key] = str_repeat('-', $depth) . $item['label'];
  21. }
  22. if (isset($item['children'])) {
  23. foreach ($item['children'] as $child) {
  24. $options = array_merge($options, $this->options($child, $key, $depth + 1));
  25. }
  26. }
  27. return $options;
  28. }
  29. /**
  30. * Add an item of any type to the hierarchy.
  31. */
  32. public function add($item_key, $label = NULL, $parent = FieldHierarchy::ROOT) {
  33. if (!array_key_exists($item_key, $this->data)) {
  34. $this->data[$item_key]['label'] = isset($label) ? $label : $item_key;
  35. }
  36. if (!isset($this->data[$parent]['children'])) {
  37. $this->data[$parent]['children'] = array();
  38. }
  39. if (!in_array($item_key, $this->data[$parent]['children'])) {
  40. $this->data[$parent]['children'][] = $item_key;
  41. }
  42. }
  43. /**
  44. * Adds a single field plugin to the hierarchy.
  45. */
  46. public function addField(FieldInstance $field) {
  47. $bundle_key = "{$field->entityType}:{$field->bundle}";
  48. if ($field->isBundleable) {
  49. $this->add($field->entityType, $field->entityTypeLabel);
  50. $this->add($bundle_key, $field->bundleLabel, $field->entityType);
  51. }
  52. else {
  53. $this->add($bundle_key, $field->entityTypeLabel);
  54. }
  55. $field_key = "{$bundle_key}:{$field->name}";
  56. $this->add($field_key, $field->label, $bundle_key);
  57. }
  58. /**
  59. * Adds an entire field chain to the hierarchy.
  60. */
  61. public function addChain(FieldChain $chain) {
  62. $parents = array();
  63. foreach ($chain as $field) {
  64. if ($field->requireParent()) {
  65. $parent_key = implode('::', $parents);
  66. $field_key = "{$parent_key}::{$field}";
  67. $this->add($field_key, $field->label, $parent_key);
  68. }
  69. else {
  70. $this->addField($field);
  71. }
  72. $parents[] = $field->__toString();
  73. }
  74. }
  75. /**
  76. * @implements Countable::count().
  77. */
  78. public function count() {
  79. return sizeof($this->data);
  80. }
  81. }