Collection.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006~2019 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: zhangyajun <448901948@qq.com>
  10. // +----------------------------------------------------------------------
  11. declare (strict_types = 1);
  12. namespace think;
  13. use ArrayAccess;
  14. use ArrayIterator;
  15. use Countable;
  16. use IteratorAggregate;
  17. use JsonSerializable;
  18. use think\contract\Arrayable;
  19. use think\contract\Jsonable;
  20. use think\helper\Arr;
  21. use Traversable;
  22. /**
  23. * 数据集管理类
  24. *
  25. * @template TKey of array-key
  26. * @template-covariant TValue
  27. *
  28. * @implements ArrayAccess<TKey, TValue>
  29. * @implements IteratorAggregate<TKey, TValue>
  30. */
  31. class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSerializable, Arrayable, Jsonable
  32. {
  33. /**
  34. * 数据集数据
  35. * @var array
  36. */
  37. protected $items = [];
  38. /**
  39. * 构造函数
  40. * @param iterable<TKey, TValue>|Collection<TKey, TValue> $items 数据
  41. */
  42. public function __construct($items = [])
  43. {
  44. $this->items = $this->convertToArray($items);
  45. }
  46. /**
  47. * @param iterable<TKey, TValue>|Collection<TKey, TValue> $items
  48. * @return static<TKey, TValue>
  49. */
  50. public static function make($items = [])
  51. {
  52. return new static($items);
  53. }
  54. /**
  55. * 是否为空
  56. * @return bool
  57. */
  58. public function isEmpty(): bool
  59. {
  60. return empty($this->items);
  61. }
  62. public function toArray(): array
  63. {
  64. return array_map(function ($value) {
  65. return $value instanceof Arrayable ? $value->toArray() : $value;
  66. }, $this->items);
  67. }
  68. /**
  69. * @return array<TKey, TValue>
  70. */
  71. public function all(): array
  72. {
  73. return $this->items;
  74. }
  75. /**
  76. * 合并数组
  77. *
  78. * @param mixed $items 数据
  79. * @return static
  80. */
  81. public function merge($items)
  82. {
  83. return new static(array_merge($this->items, $this->convertToArray($items)));
  84. }
  85. /**
  86. * 按指定键整理数据
  87. *
  88. * @param mixed $items 数据
  89. * @param string|null $indexKey 键名
  90. * @return array
  91. */
  92. public function dictionary($items = null, ?string &$indexKey = null)
  93. {
  94. if ($items instanceof self) {
  95. $items = $items->all();
  96. }
  97. $items = is_null($items) ? $this->items : $items;
  98. if ($items && empty($indexKey)) {
  99. $indexKey = is_array($items[0]) ? 'id' : $items[0]->getPk();
  100. }
  101. if (isset($indexKey) && is_string($indexKey)) {
  102. return array_column($items, null, $indexKey);
  103. }
  104. return $items;
  105. }
  106. /**
  107. * 比较数组,返回差集
  108. *
  109. * @param mixed $items 数据
  110. * @param string|null $indexKey 指定比较的键名
  111. * @return static<TKey, TValue>
  112. */
  113. public function diff($items, ?string $indexKey = null)
  114. {
  115. if ($this->isEmpty() || is_scalar($this->items[0])) {
  116. return new static(array_diff($this->items, $this->convertToArray($items)));
  117. }
  118. $diff = [];
  119. $dictionary = $this->dictionary($items, $indexKey);
  120. if (is_string($indexKey)) {
  121. foreach ($this->items as $item) {
  122. if (!isset($dictionary[$item[$indexKey]])) {
  123. $diff[] = $item;
  124. }
  125. }
  126. }
  127. return new static($diff);
  128. }
  129. /**
  130. * 比较数组,返回交集
  131. *
  132. * @param mixed $items 数据
  133. * @param string|null $indexKey 指定比较的键名
  134. * @return static<TKey, TValue>
  135. */
  136. public function intersect($items, ?string $indexKey = null)
  137. {
  138. if ($this->isEmpty() || is_scalar($this->items[0])) {
  139. return new static(array_intersect($this->items, $this->convertToArray($items)));
  140. }
  141. $intersect = [];
  142. $dictionary = $this->dictionary($items, $indexKey);
  143. if (is_string($indexKey)) {
  144. foreach ($this->items as $item) {
  145. if (isset($dictionary[$item[$indexKey]])) {
  146. $intersect[] = $item;
  147. }
  148. }
  149. }
  150. return new static($intersect);
  151. }
  152. /**
  153. * 交换数组中的键和值
  154. *
  155. * @return static<TValue, TKey>
  156. */
  157. public function flip()
  158. {
  159. return new static(array_flip($this->items));
  160. }
  161. /**
  162. * 返回数组中所有的键名
  163. *
  164. * @return static<TKey, TValue>
  165. */
  166. public function keys()
  167. {
  168. return new static(array_keys($this->items));
  169. }
  170. /**
  171. * 返回数组中所有的值组成的新 Collection 实例
  172. * @return static<int, TValue>
  173. */
  174. public function values()
  175. {
  176. return new static(array_values($this->items));
  177. }
  178. /**
  179. * 删除数组的最后一个元素(出栈)
  180. *
  181. * @return TValue
  182. */
  183. public function pop()
  184. {
  185. return array_pop($this->items);
  186. }
  187. /**
  188. * 通过使用用户自定义函数,以字符串返回数组
  189. *
  190. * @param callable $callback 调用方法
  191. * @param mixed $initial
  192. * @return mixed
  193. */
  194. public function reduce(callable $callback, $initial = null)
  195. {
  196. return array_reduce($this->items, $callback, $initial);
  197. }
  198. /**
  199. * 以相反的顺序返回数组。
  200. *
  201. * @return static<TKey, TValue>
  202. */
  203. public function reverse()
  204. {
  205. return new static(array_reverse($this->items));
  206. }
  207. /**
  208. * 删除数组中首个元素,并返回被删除元素的值
  209. *
  210. * @return TValue
  211. */
  212. public function shift()
  213. {
  214. return array_shift($this->items);
  215. }
  216. /**
  217. * 在数组结尾插入一个元素
  218. *
  219. * @param mixed $value 元素
  220. * @param string|null $key KEY
  221. * @return $this
  222. */
  223. public function push($value, ?string $key = null)
  224. {
  225. if (is_null($key)) {
  226. $this->items[] = $value;
  227. } else {
  228. $this->items[$key] = $value;
  229. }
  230. return $this;
  231. }
  232. /**
  233. * 把一个数组分割为新的数组块.
  234. *
  235. * @param int $size 块大小
  236. * @param bool $preserveKeys
  237. * @return static
  238. */
  239. public function chunk(int $size, bool $preserveKeys = false)
  240. {
  241. $chunks = [];
  242. foreach (array_chunk($this->items, $size, $preserveKeys) as $chunk) {
  243. $chunks[] = new static($chunk);
  244. }
  245. return new static($chunks);
  246. }
  247. /**
  248. * 在数组开头插入一个元素
  249. *
  250. * @param mixed $value 元素
  251. * @param string|null $key KEY
  252. * @return $this
  253. */
  254. public function unshift($value, ?string $key = null)
  255. {
  256. if (is_null($key)) {
  257. array_unshift($this->items, $value);
  258. } else {
  259. $this->items = [$key => $value] + $this->items;
  260. }
  261. return $this;
  262. }
  263. /**
  264. * 给每个元素执行个回调
  265. *
  266. *
  267. * @param callable $callback 回调
  268. * @return $this
  269. */
  270. public function each(callable $callback)
  271. {
  272. foreach ($this->items as $key => $item) {
  273. $result = $callback($item, $key);
  274. if (false === $result) {
  275. break;
  276. } elseif (!is_object($item)) {
  277. $this->items[$key] = $result;
  278. }
  279. }
  280. return $this;
  281. }
  282. /**
  283. * 用回调函数处理数组中的元素
  284. *
  285. * @param callable|null $callback 回调
  286. * @return static<TKey, TValue>
  287. */
  288. public function map(callable $callback)
  289. {
  290. return new static(array_map($callback, $this->items));
  291. }
  292. /**
  293. * 用回调函数过滤数组中的元素
  294. *
  295. * @param callable|null $callback 回调
  296. * @return static<TKey, TValue>
  297. */
  298. public function filter(?callable $callback = null)
  299. {
  300. if ($callback) {
  301. return new static(array_filter($this->items, $callback));
  302. }
  303. return new static(array_filter($this->items));
  304. }
  305. /**
  306. * 根据字段条件过滤数组中的元素
  307. *
  308. * @param string $field 字段名
  309. * @param mixed $operator 操作符
  310. * @param mixed $value 数据
  311. * @return static<TKey, TValue>
  312. */
  313. public function where(string $field, $operator, $value = null)
  314. {
  315. if (is_null($value)) {
  316. $value = $operator;
  317. $operator = '=';
  318. }
  319. return $this->filter(function ($data) use ($field, $operator, $value) {
  320. if (strpos($field, '.')) {
  321. [$field, $relation] = explode('.', $field);
  322. $result = $data[$field][$relation] ?? null;
  323. } else {
  324. $result = $data[$field] ?? null;
  325. }
  326. switch (strtolower($operator)) {
  327. case '===':
  328. return $result === $value;
  329. case '!==':
  330. return $result !== $value;
  331. case '!=':
  332. case '<>':
  333. return $result != $value;
  334. case '>':
  335. return $result > $value;
  336. case '>=':
  337. return $result >= $value;
  338. case '<':
  339. return $result < $value;
  340. case '<=':
  341. return $result <= $value;
  342. case 'like':
  343. return is_string($result) && false !== strpos($result, $value);
  344. case 'not like':
  345. return is_string($result) && false === strpos($result, $value);
  346. case 'in':
  347. return is_scalar($result) && in_array($result, $value, true);
  348. case 'not in':
  349. return is_scalar($result) && !in_array($result, $value, true);
  350. case 'between':
  351. [$min, $max] = is_string($value) ? explode(',', $value) : $value;
  352. return is_scalar($result) && $result >= $min && $result <= $max;
  353. case 'not between':
  354. [$min, $max] = is_string($value) ? explode(',', $value) : $value;
  355. return is_scalar($result) && $result > $max || $result < $min;
  356. case '==':
  357. case '=':
  358. default:
  359. return $result == $value;
  360. }
  361. });
  362. }
  363. /**
  364. * LIKE过滤
  365. *
  366. * @param string $field 字段名
  367. * @param string $value 数据
  368. * @return static<TKey, TValue>
  369. */
  370. public function whereLike(string $field, string $value)
  371. {
  372. return $this->where($field, 'like', $value);
  373. }
  374. /**
  375. * NOT LIKE过滤
  376. *
  377. * @param string $field 字段名
  378. * @param string $value 数据
  379. * @return static<TKey, TValue>
  380. */
  381. public function whereNotLike(string $field, string $value)
  382. {
  383. return $this->where($field, 'not like', $value);
  384. }
  385. /**
  386. * IN过滤
  387. *
  388. * @param string $field 字段名
  389. * @param array $value 数据
  390. * @return static<TKey, TValue>
  391. */
  392. public function whereIn(string $field, array $value)
  393. {
  394. return $this->where($field, 'in', $value);
  395. }
  396. /**
  397. * NOT IN过滤
  398. *
  399. * @param string $field 字段名
  400. * @param array $value 数据
  401. * @return static<TKey, TValue>
  402. */
  403. public function whereNotIn(string $field, array $value)
  404. {
  405. return $this->where($field, 'not in', $value);
  406. }
  407. /**
  408. * BETWEEN 过滤
  409. *
  410. * @param string $field 字段名
  411. * @param mixed $value 数据
  412. * @return static<TKey, TValue>
  413. */
  414. public function whereBetween(string $field, $value)
  415. {
  416. return $this->where($field, 'between', $value);
  417. }
  418. /**
  419. * NOT BETWEEN 过滤
  420. *
  421. * @param string $field 字段名
  422. * @param mixed $value 数据
  423. * @return static<TKey, TValue>
  424. */
  425. public function whereNotBetween(string $field, $value)
  426. {
  427. return $this->where($field, 'not between', $value);
  428. }
  429. /**
  430. * 返回数据中指定的一列
  431. *
  432. * @param string|null $columnKey 键名
  433. * @param string|null $indexKey 作为索引值的列
  434. * @return array
  435. */
  436. public function column(?string $columnKey, ?string $indexKey = null)
  437. {
  438. return array_column($this->items, $columnKey, $indexKey);
  439. }
  440. /**
  441. * 对数组排序
  442. *
  443. * @param callable|null $callback 回调
  444. * @return static<TKey, TValue>
  445. */
  446. public function sort(?callable $callback = null)
  447. {
  448. $items = $this->items;
  449. $callback = $callback ?: function ($a, $b) {
  450. return $a == $b ? 0 : (($a < $b) ? -1 : 1);
  451. };
  452. uasort($items, $callback);
  453. return new static($items);
  454. }
  455. /**
  456. * 指定字段排序
  457. *
  458. * @param string $field 排序字段
  459. * @param string $order 排序
  460. * @return $this
  461. */
  462. public function order(string $field, string $order = 'asc')
  463. {
  464. return $this->sort(function ($a, $b) use ($field, $order) {
  465. $fieldA = $a[$field] ?? null;
  466. $fieldB = $b[$field] ?? null;
  467. return 'desc' == strtolower($order) ? ($fieldB <=> $fieldA) : ($fieldA <=> $fieldB);
  468. });
  469. }
  470. /**
  471. * 将数组打乱
  472. *
  473. * @return static<TKey, TValue>
  474. */
  475. public function shuffle()
  476. {
  477. $items = $this->items;
  478. shuffle($items);
  479. return new static($items);
  480. }
  481. /**
  482. * 获取第一个单元数据
  483. *
  484. * @param callable|null $callback
  485. * @param null $default
  486. * @return TValue
  487. */
  488. public function first(?callable $callback = null, $default = null)
  489. {
  490. return Arr::first($this->items, $callback, $default);
  491. }
  492. /**
  493. * 获取最后一个单元数据
  494. *
  495. * @param callable|null $callback
  496. * @param null $default
  497. * @return TValue
  498. */
  499. public function last(?callable $callback = null, $default = null)
  500. {
  501. return Arr::last($this->items, $callback, $default);
  502. }
  503. /**
  504. * 截取数组
  505. *
  506. * @param int $offset 起始位置
  507. * @param int|null $length 截取长度
  508. * @param bool $preserveKeys preserveKeys
  509. * @return static<TKey, TValue>
  510. */
  511. public function slice(int $offset, ?int $length = null, bool $preserveKeys = false)
  512. {
  513. return new static(array_slice($this->items, $offset, $length, $preserveKeys));
  514. }
  515. /**
  516. * @param TKey $key
  517. * @return bool
  518. */
  519. #[\ReturnTypeWillChange]
  520. public function offsetExists($offset) : bool
  521. {
  522. return array_key_exists($offset, $this->items);
  523. }
  524. /**
  525. * @param TKey $offset
  526. * @return TValue
  527. */
  528. #[\ReturnTypeWillChange]
  529. public function offsetGet($offset)
  530. {
  531. return $this->items[$offset];
  532. }
  533. /**
  534. * @param TKey|null $offset
  535. * @param TValue $value
  536. * @return void
  537. */
  538. #[\ReturnTypeWillChange]
  539. public function offsetSet($offset, $value)
  540. {
  541. if (is_null($offset)) {
  542. $this->items[] = $value;
  543. } else {
  544. $this->items[$offset] = $value;
  545. }
  546. }
  547. /**
  548. * @param TKey $offset
  549. * @return void
  550. */
  551. #[\ReturnTypeWillChange]
  552. public function offsetUnset($offset)
  553. {
  554. unset($this->items[$offset]);
  555. }
  556. //Countable
  557. public function count(): int
  558. {
  559. return count($this->items);
  560. }
  561. /**
  562. * @return ArrayIterator<TKey, TValue>
  563. */
  564. #[\ReturnTypeWillChange]
  565. public function getIterator(): Traversable
  566. {
  567. return new ArrayIterator($this->items);
  568. }
  569. //JsonSerializable
  570. #[\ReturnTypeWillChange]
  571. public function jsonSerialize()
  572. {
  573. return $this->toArray();
  574. }
  575. /**
  576. * 转换当前数据集为JSON字符串
  577. *
  578. * @param integer $options json参数
  579. * @return string
  580. */
  581. public function toJson(int $options = JSON_UNESCAPED_UNICODE): string
  582. {
  583. return json_encode($this->toArray(), $options);
  584. }
  585. public function __toString()
  586. {
  587. return $this->toJson();
  588. }
  589. /**
  590. * 转换成数组
  591. *
  592. * @param mixed $items 数据
  593. * @return array
  594. */
  595. protected function convertToArray($items): array
  596. {
  597. if ($items instanceof self) {
  598. return $items->all();
  599. }
  600. return (array) $items;
  601. }
  602. }