FieldDescriptionCollection.php 2.3 KB

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