FieldDescriptionCollection.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. <?php
  2. /*
  3. * This file is part of the Sonata Project package.
  4. *
  5. * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Sonata\AdminBundle\Admin;
  11. /**
  12. * @author Thomas Rabaix <thomas.rabaix@sonata-project.org>
  13. */
  14. class FieldDescriptionCollection implements \ArrayAccess, \Countable
  15. {
  16. /**
  17. * @var FieldDescriptionInterface[]
  18. */
  19. protected $elements = array();
  20. /**
  21. * @param FieldDescriptionInterface $fieldDescription
  22. */
  23. public function add(FieldDescriptionInterface $fieldDescription)
  24. {
  25. $this->elements[$fieldDescription->getName()] = $fieldDescription;
  26. }
  27. /**
  28. * @return array
  29. */
  30. public function getElements()
  31. {
  32. return $this->elements;
  33. }
  34. /**
  35. * @param string $name
  36. *
  37. * @return bool
  38. */
  39. public function has($name)
  40. {
  41. return array_key_exists($name, $this->elements);
  42. }
  43. /**
  44. * @throws \InvalidArgumentException
  45. *
  46. * @param string $name
  47. *
  48. * @return FieldDescriptionInterface
  49. */
  50. public function get($name)
  51. {
  52. if ($this->has($name)) {
  53. return $this->elements[$name];
  54. }
  55. throw new \InvalidArgumentException(sprintf('Element "%s" does not exist.', $name));
  56. }
  57. /**
  58. * @param string $name
  59. */
  60. public function remove($name)
  61. {
  62. if ($this->has($name)) {
  63. unset($this->elements[$name]);
  64. }
  65. }
  66. /**
  67. * {@inheritdoc}
  68. */
  69. public function offsetExists($offset)
  70. {
  71. return $this->has($offset);
  72. }
  73. /**
  74. * {@inheritdoc}
  75. */
  76. public function offsetGet($offset)
  77. {
  78. return $this->get($offset);
  79. }
  80. /**
  81. * {@inheritdoc}
  82. */
  83. public function offsetSet($offset, $value)
  84. {
  85. throw new \RuntimeException('Cannot set value, use add');
  86. }
  87. /**
  88. * {@inheritdoc}
  89. */
  90. public function offsetUnset($offset)
  91. {
  92. $this->remove($offset);
  93. }
  94. /**
  95. * {@inheritdoc}
  96. */
  97. public function count()
  98. {
  99. return count($this->elements);
  100. }
  101. /**
  102. * @param array $keys
  103. */
  104. public function reorder(array $keys)
  105. {
  106. if ($this->has('batch')) {
  107. array_unshift($keys, 'batch');
  108. }
  109. $this->elements = array_merge(array_flip($keys), $this->elements);
  110. }
  111. }