ArrayCollection.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. /**
  3. * @package Grav\Framework\Collection
  4. *
  5. * @copyright Copyright (C) 2015 - 2019 Trilby Media, LLC. All rights reserved.
  6. * @license MIT License; see LICENSE file for details.
  7. */
  8. namespace Grav\Framework\Collection;
  9. use Doctrine\Common\Collections\ArrayCollection as BaseArrayCollection;
  10. /**
  11. * General JSON serializable collection.
  12. *
  13. * @package Grav\Framework\Collection
  14. */
  15. class ArrayCollection extends BaseArrayCollection implements CollectionInterface
  16. {
  17. /**
  18. * Reverse the order of the items.
  19. *
  20. * @return static
  21. */
  22. public function reverse()
  23. {
  24. return $this->createFrom(array_reverse($this->toArray()));
  25. }
  26. /**
  27. * Shuffle items.
  28. *
  29. * @return static
  30. */
  31. public function shuffle()
  32. {
  33. $keys = $this->getKeys();
  34. shuffle($keys);
  35. return $this->createFrom(array_replace(array_flip($keys), $this->toArray()));
  36. }
  37. /**
  38. * Split collection into chunks.
  39. *
  40. * @param int $size Size of each chunk.
  41. * @return array
  42. */
  43. public function chunk($size)
  44. {
  45. return array_chunk($this->toArray(), $size, true);
  46. }
  47. /**
  48. * Select items from collection.
  49. *
  50. * Collection is returned in the order of $keys given to the function.
  51. *
  52. * @param array $keys
  53. * @return static
  54. */
  55. public function select(array $keys)
  56. {
  57. $list = [];
  58. foreach ($keys as $key) {
  59. if ($this->containsKey($key)) {
  60. $list[$key] = $this->get($key);
  61. }
  62. }
  63. return $this->createFrom($list);
  64. }
  65. /**
  66. * Un-select items from collection.
  67. *
  68. * @param array $keys
  69. * @return static
  70. */
  71. public function unselect(array $keys)
  72. {
  73. return $this->select(array_diff($this->getKeys(), $keys));
  74. }
  75. /**
  76. * Implements JsonSerializable interface.
  77. *
  78. * @return array
  79. */
  80. public function jsonSerialize()
  81. {
  82. return $this->toArray();
  83. }
  84. }