FieldDescriptionCollection.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  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. * Class FieldDescriptionCollection.
  13. *
  14. * @author Thomas Rabaix <thomas.rabaix@sonata-project.org>
  15. */
  16. class FieldDescriptionCollection implements \ArrayAccess, \Countable
  17. {
  18. protected $elements = array();
  19. /**
  20. * @param \Sonata\AdminBundle\Admin\FieldDescriptionInterface $fieldDescription
  21. */
  22. public function add(FieldDescriptionInterface $fieldDescription)
  23. {
  24. $this->elements[$fieldDescription->getName()] = $fieldDescription;
  25. }
  26. /**
  27. * @return array
  28. */
  29. public function getElements()
  30. {
  31. return $this->elements;
  32. }
  33. /**
  34. * @param string $name
  35. *
  36. * @return bool
  37. */
  38. public function has($name)
  39. {
  40. return array_key_exists($name, $this->elements);
  41. }
  42. /**
  43. * @throws \InvalidArgumentException
  44. *
  45. * @param string $name
  46. *
  47. * @return FieldDescriptionInterface
  48. */
  49. public function get($name)
  50. {
  51. if ($this->has($name)) {
  52. return $this->elements[$name];
  53. }
  54. throw new \InvalidArgumentException(sprintf('Element "%s" does not exist.', $name));
  55. }
  56. /**
  57. * @param string $name
  58. */
  59. public function remove($name)
  60. {
  61. if ($this->has($name)) {
  62. unset($this->elements[$name]);
  63. }
  64. }
  65. /**
  66. * {@inheritdoc}
  67. */
  68. public function offsetExists($offset)
  69. {
  70. return $this->has($offset);
  71. }
  72. /**
  73. * {@inheritdoc}
  74. */
  75. public function offsetGet($offset)
  76. {
  77. return $this->get($offset);
  78. }
  79. /**
  80. * {@inheritdoc}
  81. */
  82. public function offsetSet($offset, $value)
  83. {
  84. throw new \RunTimeException('Cannot set value, use add');
  85. }
  86. /**
  87. * {@inheritdoc}
  88. */
  89. public function offsetUnset($offset)
  90. {
  91. $this->remove($offset);
  92. }
  93. /**
  94. * {@inheritdoc}
  95. */
  96. public function count()
  97. {
  98. return count($this->elements);
  99. }
  100. /**
  101. * @param array $keys
  102. */
  103. public function reorder(array $keys)
  104. {
  105. if ($this->has('batch')) {
  106. array_unshift($keys, 'batch');
  107. }
  108. $this->elements = array_merge(array_flip($keys), $this->elements);
  109. }
  110. }