CollectionUtils.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. namespace app\utils;
  3. class CollectionUtils
  4. {
  5. protected $_members = [];
  6. protected $_itemHasType; //标志是否指定元素的类型
  7. protected $_itemType; //集合中的元素类型
  8. public function __construct($items = [], $itemHasType = false, $itemType = NULL)
  9. {
  10. $this->_itemHasType = $itemHasType;
  11. $this->_itemType = $itemType;
  12. $tmp = $this->getArrayableItems($items);
  13. if ($this->_itemHasType) {
  14. foreach ($tmp as $val) {
  15. if ($val instanceof $this->_itemType) {
  16. $this->_members[] = $val;
  17. }
  18. }
  19. } else {
  20. $this->_members = $tmp;
  21. }
  22. }
  23. public function addItem($obj)
  24. {
  25. if ($this->_itemHasType) {
  26. if (!($obj instanceof $this->_itemType))
  27. throw new \Exception("The added obj is not the type of \"$this->_itemType\"!");
  28. }
  29. if ($this->exists($obj)) {
  30. throw new \Exception("Obj is already exists!");
  31. } else {
  32. $this->_members[] = $obj;
  33. }
  34. }
  35. public function removeItem($obj)
  36. {
  37. if (false != ($key = array_search($obj, $this->_members))) {
  38. unset($this->_members[$key]);
  39. } else {
  40. throw new \Exception("Obj is not exists!");
  41. }
  42. }
  43. public function all()
  44. {
  45. return $this->_members;
  46. }
  47. public function length()
  48. {
  49. return sizeof($this->_members);
  50. }
  51. public function exists($obj)
  52. {
  53. return in_array($obj, $this->_members);
  54. }
  55. protected function getArrayableItems($items)
  56. {
  57. if (is_array($items)) {
  58. return array_values(array_unique($items, SORT_REGULAR));
  59. } elseif ($items instanceof self) {
  60. return $items->all();
  61. }
  62. return (array) $items;
  63. }
  64. }