FieldDescriptionCollection.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. <?php
  2. /*
  3. * This file is part of the Sonata 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. */
  11. namespace Sonata\AdminBundle\Admin;
  12. class FieldDescriptionCollection implements \ArrayAccess, \Countable
  13. {
  14. protected $elements = array();
  15. /**
  16. * @param \Sonata\AdminBundle\Admin\FieldDescriptionInterface $fieldDescription
  17. *
  18. * @return void
  19. */
  20. public function add(FieldDescriptionInterface $fieldDescription)
  21. {
  22. $this->elements[$fieldDescription->getName()] = $fieldDescription;
  23. }
  24. /**
  25. * @return array
  26. */
  27. public function getElements()
  28. {
  29. return $this->elements;
  30. }
  31. /**
  32. * @param string $name
  33. *
  34. * @return bool
  35. */
  36. public function has($name)
  37. {
  38. return array_key_exists($name, $this->elements);
  39. }
  40. /**
  41. * @throws \InvalidArgumentException
  42. *
  43. * @param string $name
  44. *
  45. * @return FieldDescriptionInterface
  46. */
  47. public function get($name)
  48. {
  49. if ($this->has($name)) {
  50. return $this->elements[$name];
  51. }
  52. throw new \InvalidArgumentException(sprintf('Element "%s" does not exist.', $name));
  53. }
  54. /**
  55. * @param string $name
  56. *
  57. * @return void
  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. }