CollectionTest.php 79 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  5. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  6. *
  7. * Licensed under The MIT License
  8. * For full copyright and license information, please see the LICENSE.txt
  9. * Redistributions of files must retain the above copyright notice.
  10. *
  11. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  12. * @link https://cakephp.org CakePHP(tm) Project
  13. * @since 3.0.0
  14. * @license https://opensource.org/licenses/mit-license.php MIT License
  15. */
  16. namespace Cake\Test\TestCase\Collection;
  17. use ArrayIterator;
  18. use ArrayObject;
  19. use Cake\Collection\Collection;
  20. use Cake\Collection\Iterator\BufferedIterator;
  21. use Cake\ORM\Entity;
  22. use Cake\TestSuite\TestCase;
  23. use CallbackFilterIterator;
  24. use DateInterval;
  25. use DatePeriod;
  26. use DateTime;
  27. use Exception;
  28. use Generator;
  29. use InvalidArgumentException;
  30. use LogicException;
  31. use NoRewindIterator;
  32. use stdClass;
  33. use TestApp\Collection\CountableIterator;
  34. use TestApp\Collection\TestCollection;
  35. use function Cake\Collection\collection;
  36. /**
  37. * Collection Test
  38. *
  39. * @coversDefaultClass \Cake\Collection\Collection
  40. */
  41. class CollectionTest extends TestCase
  42. {
  43. /**
  44. * Tests that it is possible to convert an array into a collection
  45. */
  46. public function testArrayIsWrapped(): void
  47. {
  48. $items = [1, 2, 3];
  49. $collection = new Collection($items);
  50. $this->assertEquals($items, iterator_to_array($collection));
  51. }
  52. /**
  53. * Provider for average tests
  54. *
  55. * @return array
  56. */
  57. public static function avgProvider(): array
  58. {
  59. $items = [1, 2, 3];
  60. return [
  61. 'array' => [$items],
  62. 'iterator' => [self::yieldItems($items)],
  63. ];
  64. }
  65. /**
  66. * Tests the avg method
  67. *
  68. * @dataProvider avgProvider
  69. */
  70. public function testAvg(iterable $items): void
  71. {
  72. $collection = new Collection($items);
  73. $this->assertSame(2, $collection->avg());
  74. $items = [['foo' => 1], ['foo' => 2], ['foo' => 3]];
  75. $collection = new Collection($items);
  76. $this->assertSame(2, $collection->avg('foo'));
  77. }
  78. /**
  79. * Tests the avg method when on an empty collection
  80. */
  81. public function testAvgWithEmptyCollection(): void
  82. {
  83. $collection = new Collection([]);
  84. $this->assertNull($collection->avg());
  85. $collection = new Collection([null, null]);
  86. $this->assertSame(0, $collection->avg());
  87. }
  88. /**
  89. * Provider for average tests with use of a matcher
  90. *
  91. * @return array
  92. */
  93. public static function avgWithMatcherProvider(): array
  94. {
  95. $items = [['foo' => 1], ['foo' => 2], ['foo' => 3]];
  96. return [
  97. 'array' => [$items],
  98. 'iterator' => [self::yieldItems($items)],
  99. ];
  100. }
  101. /**
  102. * ests the avg method
  103. *
  104. * @dataProvider avgWithMatcherProvider
  105. */
  106. public function testAvgWithMatcher(iterable $items): void
  107. {
  108. $collection = new Collection($items);
  109. $this->assertSame(2, $collection->avg('foo'));
  110. }
  111. /**
  112. * Provider for some median tests
  113. *
  114. * @return array
  115. */
  116. public static function medianProvider(): array
  117. {
  118. $items = [5, 2, 4];
  119. return [
  120. 'array' => [$items],
  121. 'iterator' => [self::yieldItems($items)],
  122. ];
  123. }
  124. /**
  125. * Tests the median method
  126. *
  127. * @dataProvider medianProvider
  128. */
  129. public function testMedian(iterable $items): void
  130. {
  131. $collection = new Collection($items);
  132. $this->assertSame(4, $collection->median());
  133. }
  134. /**
  135. * Tests the median method when on an empty collection
  136. */
  137. public function testMedianWithEmptyCollection(): void
  138. {
  139. $collection = new Collection([]);
  140. $this->assertNull($collection->median());
  141. $collection = new Collection([null, null]);
  142. $this->assertSame(0, $collection->median());
  143. }
  144. /**
  145. * Tests the median method
  146. *
  147. * @dataProvider simpleProvider
  148. */
  149. public function testMedianEven(iterable $items): void
  150. {
  151. $collection = new Collection($items);
  152. $this->assertSame(2.5, $collection->median());
  153. }
  154. /**
  155. * Provider for median tests with use of a matcher
  156. *
  157. * @return array
  158. */
  159. public static function medianWithMatcherProvider(): array
  160. {
  161. $items = [
  162. ['invoice' => ['total' => 400]],
  163. ['invoice' => ['total' => 500]],
  164. ['invoice' => ['total' => 200]],
  165. ['invoice' => ['total' => 100]],
  166. ['invoice' => ['total' => 333]],
  167. ];
  168. return [
  169. 'array' => [$items],
  170. 'iterator' => [self::yieldItems($items)],
  171. ];
  172. }
  173. /**
  174. * Tests the median method
  175. *
  176. * @dataProvider medianWithMatcherProvider
  177. */
  178. public function testMedianWithMatcher(iterable $items): void
  179. {
  180. $this->assertSame(333, (new Collection($items))->median('invoice.total'));
  181. }
  182. /**
  183. * Tests that it is possible to convert an iterator into a collection
  184. */
  185. public function testIteratorIsWrapped(): void
  186. {
  187. $items = new ArrayObject([1, 2, 3]);
  188. $collection = new Collection($items);
  189. $this->assertEquals(iterator_to_array($items), iterator_to_array($collection));
  190. }
  191. /**
  192. * Test running a method over all elements in the collection
  193. */
  194. public function testEach(): void
  195. {
  196. $items = ['a' => 1, 'b' => 2, 'c' => 3];
  197. $collection = new Collection($items);
  198. $results = [];
  199. $collection->each(function ($value, $key) use (&$results): void {
  200. $results[] = [$key => $value];
  201. });
  202. $this->assertSame([['a' => 1], ['b' => 2], ['c' => 3]], $results);
  203. }
  204. public static function filterProvider(): array
  205. {
  206. $items = [1, 2, 0, 3, false, 4, null, 5, ''];
  207. return [
  208. 'array' => [$items],
  209. 'iterator' => [self::yieldItems($items)],
  210. ];
  211. }
  212. /**
  213. * Test filter() with no callback.
  214. *
  215. * @dataProvider filterProvider
  216. */
  217. public function testFilterNoCallback(iterable $items): void
  218. {
  219. $collection = new Collection($items);
  220. $result = $collection->filter()->toArray();
  221. $expected = [1, 2, 3, 4, 5];
  222. $this->assertSame($expected, array_values($result));
  223. }
  224. /**
  225. * Tests that it is possible to chain filter() as it returns a collection object
  226. */
  227. public function testFilterChaining(): void
  228. {
  229. $items = ['a' => 1, 'b' => 2, 'c' => 3];
  230. $collection = new Collection($items);
  231. $filtered = $collection->filter(function ($value, $key, $iterator) {
  232. return $value > 2;
  233. });
  234. $this->assertInstanceOf(Collection::class, $filtered);
  235. $results = [];
  236. $filtered->each(function ($value, $key) use (&$results): void {
  237. $results[] = [$key => $value];
  238. });
  239. $this->assertSame([['c' => 3]], $results);
  240. }
  241. /**
  242. * Tests reject
  243. */
  244. public function testReject(): void
  245. {
  246. $collection = new Collection([]);
  247. $result = $collection->reject(function ($v) {
  248. return false;
  249. });
  250. $this->assertSame([], iterator_to_array($result));
  251. $this->assertInstanceOf('Cake\Collection\Collection', $result);
  252. $collection = new Collection(['a' => null, 'b' => 2, 'c' => false]);
  253. $result = $collection->reject();
  254. $this->assertEquals(['a' => null, 'c' => false], iterator_to_array($result));
  255. $items = ['a' => 1, 'b' => 2, 'c' => 3];
  256. $collection = new Collection($items);
  257. $result = $collection->reject(function ($v, $k, $items) use ($collection) {
  258. $this->assertSame($collection->getInnerIterator(), $items);
  259. return $v > 2;
  260. });
  261. $this->assertEquals(['a' => 1, 'b' => 2], iterator_to_array($result));
  262. }
  263. /**
  264. * Tests every when the callback returns true for all elements
  265. */
  266. public function testEveryReturnTrue(): void
  267. {
  268. $items = ['a' => 1, 'b' => 2, 'c' => 3];
  269. $collection = new Collection($items);
  270. $results = [];
  271. $this->assertTrue($collection->every(function ($value, $key) use (&$results) {
  272. $results[] = [$key => $value];
  273. return true;
  274. }));
  275. $this->assertSame([['a' => 1], ['b' => 2], ['c' => 3]], $results);
  276. }
  277. /**
  278. * Tests every when the callback returns false for one of the elements
  279. */
  280. public function testEveryReturnFalse(): void
  281. {
  282. $items = ['a' => 1, 'b' => 2, 'c' => 3];
  283. $collection = new Collection($items);
  284. $results = [];
  285. $this->assertFalse($collection->every(function ($value, $key) use (&$results) {
  286. $results[] = [$key => $value];
  287. return $key !== 'b';
  288. }));
  289. $this->assertSame([['a' => 1], ['b' => 2]], $results);
  290. }
  291. /**
  292. * Tests some() when one of the calls return true
  293. */
  294. public function testSomeReturnTrue(): void
  295. {
  296. $collection = new Collection([]);
  297. $result = $collection->some(function ($v) {
  298. return true;
  299. });
  300. $this->assertFalse($result);
  301. $items = ['a' => 1, 'b' => 2, 'c' => 3];
  302. $collection = new Collection($items);
  303. $results = [];
  304. $this->assertTrue($collection->some(function ($value, $key) use (&$results) {
  305. $results[] = [$key => $value];
  306. return $key === 'b';
  307. }));
  308. $this->assertSame([['a' => 1], ['b' => 2]], $results);
  309. }
  310. /**
  311. * Tests some() when none of the calls return true
  312. */
  313. public function testSomeReturnFalse(): void
  314. {
  315. $items = ['a' => 1, 'b' => 2, 'c' => 3];
  316. $collection = new Collection($items);
  317. $results = [];
  318. $this->assertFalse($collection->some(function ($value, $key) use (&$results) {
  319. $results[] = [$key => $value];
  320. return false;
  321. }));
  322. $this->assertSame([['a' => 1], ['b' => 2], ['c' => 3]], $results);
  323. }
  324. /**
  325. * Tests contains
  326. */
  327. public function testContains(): void
  328. {
  329. $collection = new Collection([]);
  330. $this->assertFalse($collection->contains('a'));
  331. $items = ['a' => 1, 'b' => 2, 'c' => 3];
  332. $collection = new Collection($items);
  333. $this->assertTrue($collection->contains(2));
  334. $this->assertTrue($collection->contains(1));
  335. $this->assertFalse($collection->contains(10));
  336. $this->assertFalse($collection->contains('2'));
  337. }
  338. /**
  339. * Provider for some simple tests
  340. *
  341. * @return array
  342. */
  343. public static function simpleProvider(): array
  344. {
  345. $items = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4];
  346. return [
  347. 'array' => [$items],
  348. 'iterator' => [self::yieldItems($items)],
  349. ];
  350. }
  351. /**
  352. * Tests map
  353. *
  354. * @dataProvider simpleProvider
  355. */
  356. public function testMap(iterable $items): void
  357. {
  358. $collection = new Collection($items);
  359. $map = $collection->map(function ($v, $k, $it) use ($collection) {
  360. $this->assertSame($collection->getInnerIterator(), $it);
  361. return $v * $v;
  362. });
  363. $this->assertInstanceOf('Cake\Collection\Iterator\ReplaceIterator', $map);
  364. $this->assertEquals(['a' => 1, 'b' => 4, 'c' => 9, 'd' => 16], iterator_to_array($map));
  365. }
  366. /**
  367. * Tests reduce with initial value
  368. *
  369. * @dataProvider simpleProvider
  370. */
  371. public function testReduceWithInitialValue(iterable $items): void
  372. {
  373. $collection = new Collection($items);
  374. $this->assertSame(20, $collection->reduce(function ($reduction, $value, $key) {
  375. return $value + $reduction;
  376. }, 10));
  377. }
  378. /**
  379. * Tests reduce without initial value
  380. *
  381. * @dataProvider simpleProvider
  382. */
  383. public function testReduceWithoutInitialValue(iterable $items): void
  384. {
  385. $collection = new Collection($items);
  386. $this->assertSame(10, $collection->reduce(function ($reduction, $value, $key) {
  387. return $value + $reduction;
  388. }));
  389. }
  390. /**
  391. * Provider for some extract tests
  392. *
  393. * @return array
  394. */
  395. public static function extractProvider(): array
  396. {
  397. $items = [['a' => ['b' => ['c' => 1]]], 2];
  398. return [
  399. 'array' => [$items],
  400. 'iterator' => [self::yieldItems($items)],
  401. ];
  402. }
  403. /**
  404. * Tests extract
  405. *
  406. * @dataProvider extractProvider
  407. */
  408. public function testExtract(iterable $items): void
  409. {
  410. $collection = new Collection($items);
  411. $map = $collection->extract('a.b.c');
  412. $this->assertInstanceOf('Cake\Collection\Iterator\ExtractIterator', $map);
  413. $this->assertEquals([1, null], iterator_to_array($map));
  414. }
  415. /**
  416. * Provider for some sort tests
  417. *
  418. * @return array
  419. */
  420. public static function sortProvider(): array
  421. {
  422. $items = [
  423. ['a' => ['b' => ['c' => 4]]],
  424. ['a' => ['b' => ['c' => 10]]],
  425. ['a' => ['b' => ['c' => 6]]],
  426. ];
  427. return [
  428. 'array' => [$items],
  429. 'iterator' => [self::yieldItems($items)],
  430. ];
  431. }
  432. /**
  433. * Tests sort
  434. *
  435. * @dataProvider sortProvider
  436. */
  437. public function testSortString(iterable $items): void
  438. {
  439. $collection = new Collection($items);
  440. $map = $collection->sortBy('a.b.c');
  441. $this->assertInstanceOf('Cake\Collection\Collection', $map);
  442. $expected = [
  443. ['a' => ['b' => ['c' => 10]]],
  444. ['a' => ['b' => ['c' => 6]]],
  445. ['a' => ['b' => ['c' => 4]]],
  446. ];
  447. $this->assertEquals($expected, $map->toList());
  448. }
  449. /**
  450. * Tests max
  451. *
  452. * @dataProvider sortProvider
  453. */
  454. public function testMax(iterable $items): void
  455. {
  456. $collection = new Collection($items);
  457. $this->assertEquals(['a' => ['b' => ['c' => 10]]], $collection->max('a.b.c'));
  458. }
  459. /**
  460. * Tests max
  461. *
  462. * @dataProvider sortProvider
  463. */
  464. public function testMaxCallback(iterable $items): void
  465. {
  466. $collection = new Collection($items);
  467. $callback = function ($e) {
  468. return $e['a']['b']['c'] * -1;
  469. };
  470. $this->assertEquals(['a' => ['b' => ['c' => 4]]], $collection->max($callback));
  471. }
  472. /**
  473. * Tests max
  474. *
  475. * @dataProvider sortProvider
  476. */
  477. public function testMaxCallable(iterable $items): void
  478. {
  479. $collection = new Collection($items);
  480. $this->assertEquals(['a' => ['b' => ['c' => 4]]], $collection->max(function ($e) {
  481. return $e['a']['b']['c'] * -1;
  482. }));
  483. }
  484. /**
  485. * Test max with a collection of Entities
  486. */
  487. public function testMaxWithEntities(): void
  488. {
  489. $collection = new Collection([
  490. new Entity(['id' => 1, 'count' => 18]),
  491. new Entity(['id' => 2, 'count' => 9]),
  492. new Entity(['id' => 3, 'count' => 42]),
  493. new Entity(['id' => 4, 'count' => 4]),
  494. new Entity(['id' => 5, 'count' => 22]),
  495. ]);
  496. $expected = new Entity(['id' => 3, 'count' => 42]);
  497. $this->assertEquals($expected, $collection->max('count'));
  498. }
  499. /**
  500. * Tests min
  501. *
  502. * @dataProvider sortProvider
  503. */
  504. public function testMin(iterable $items): void
  505. {
  506. $collection = new Collection($items);
  507. $this->assertEquals(['a' => ['b' => ['c' => 4]]], $collection->min('a.b.c'));
  508. }
  509. /**
  510. * Test min with a collection of Entities
  511. */
  512. public function testMinWithEntities(): void
  513. {
  514. $collection = new Collection([
  515. new Entity(['id' => 1, 'count' => 18]),
  516. new Entity(['id' => 2, 'count' => 9]),
  517. new Entity(['id' => 3, 'count' => 42]),
  518. new Entity(['id' => 4, 'count' => 4]),
  519. new Entity(['id' => 5, 'count' => 22]),
  520. ]);
  521. $expected = new Entity(['id' => 4, 'count' => 4]);
  522. $this->assertEquals($expected, $collection->min('count'));
  523. }
  524. /**
  525. * Provider for some groupBy tests
  526. *
  527. * @return array
  528. */
  529. public static function groupByProvider(): array
  530. {
  531. $items = [
  532. ['id' => 1, 'name' => 'foo', 'parent_id' => 10],
  533. ['id' => 2, 'name' => 'bar', 'parent_id' => 11],
  534. ['id' => 3, 'name' => 'baz', 'parent_id' => 10],
  535. ];
  536. return [
  537. 'array' => [$items],
  538. 'iterator' => [self::yieldItems($items)],
  539. ];
  540. }
  541. /**
  542. * Tests groupBy
  543. *
  544. * @dataProvider groupByProvider
  545. */
  546. public function testGroupBy(iterable $items): void
  547. {
  548. $collection = new Collection($items);
  549. $grouped = $collection->groupBy('parent_id');
  550. $expected = [
  551. 10 => [
  552. ['id' => 1, 'name' => 'foo', 'parent_id' => 10],
  553. ['id' => 3, 'name' => 'baz', 'parent_id' => 10],
  554. ],
  555. 11 => [
  556. ['id' => 2, 'name' => 'bar', 'parent_id' => 11],
  557. ],
  558. ];
  559. $this->assertEquals($expected, iterator_to_array($grouped));
  560. $this->assertInstanceOf('Cake\Collection\Collection', $grouped);
  561. }
  562. /**
  563. * Tests groupBy
  564. *
  565. * @dataProvider groupByProvider
  566. */
  567. public function testGroupByCallback(iterable $items): void
  568. {
  569. $collection = new Collection($items);
  570. $expected = [
  571. 10 => [
  572. ['id' => 1, 'name' => 'foo', 'parent_id' => 10],
  573. ['id' => 3, 'name' => 'baz', 'parent_id' => 10],
  574. ],
  575. 11 => [
  576. ['id' => 2, 'name' => 'bar', 'parent_id' => 11],
  577. ],
  578. ];
  579. $grouped = $collection->groupBy(function ($element) {
  580. return $element['parent_id'];
  581. });
  582. $this->assertEquals($expected, iterator_to_array($grouped));
  583. }
  584. /**
  585. * Tests grouping by a deep key
  586. */
  587. public function testGroupByDeepKey(): void
  588. {
  589. $items = [
  590. ['id' => 1, 'name' => 'foo', 'thing' => ['parent_id' => 10]],
  591. ['id' => 2, 'name' => 'bar', 'thing' => ['parent_id' => 11]],
  592. ['id' => 3, 'name' => 'baz', 'thing' => ['parent_id' => 10]],
  593. ];
  594. $collection = new Collection($items);
  595. $grouped = $collection->groupBy('thing.parent_id');
  596. $expected = [
  597. 10 => [
  598. ['id' => 1, 'name' => 'foo', 'thing' => ['parent_id' => 10]],
  599. ['id' => 3, 'name' => 'baz', 'thing' => ['parent_id' => 10]],
  600. ],
  601. 11 => [
  602. ['id' => 2, 'name' => 'bar', 'thing' => ['parent_id' => 11]],
  603. ],
  604. ];
  605. $this->assertEquals($expected, iterator_to_array($grouped));
  606. }
  607. /**
  608. * Tests passing an invalid path to groupBy.
  609. */
  610. public function testGroupByInvalidPath(): void
  611. {
  612. $items = [
  613. ['id' => 1, 'name' => 'foo'],
  614. ['id' => 2, 'name' => 'bar'],
  615. ['id' => 3, 'name' => 'baz'],
  616. ];
  617. $collection = new Collection($items);
  618. $this->expectException(InvalidArgumentException::class);
  619. $this->expectExceptionMessage('Cannot group by path that does not exist or contains a null value.');
  620. $collection->groupBy('missing');
  621. }
  622. /**
  623. * Provider for some indexBy tests
  624. *
  625. * @return array
  626. */
  627. public static function indexByProvider(): array
  628. {
  629. $items = [
  630. ['id' => 1, 'name' => 'foo', 'parent_id' => 10],
  631. ['id' => 2, 'name' => 'bar', 'parent_id' => 11],
  632. ['id' => 3, 'name' => 'baz', 'parent_id' => 10],
  633. ];
  634. return [
  635. 'array' => [$items],
  636. 'iterator' => [self::yieldItems($items)],
  637. ];
  638. }
  639. /**
  640. * Tests indexBy
  641. *
  642. * @dataProvider indexByProvider
  643. */
  644. public function testIndexBy(iterable $items): void
  645. {
  646. $collection = new Collection($items);
  647. $grouped = $collection->indexBy('id');
  648. $expected = [
  649. 1 => ['id' => 1, 'name' => 'foo', 'parent_id' => 10],
  650. 3 => ['id' => 3, 'name' => 'baz', 'parent_id' => 10],
  651. 2 => ['id' => 2, 'name' => 'bar', 'parent_id' => 11],
  652. ];
  653. $this->assertEquals($expected, iterator_to_array($grouped));
  654. $this->assertInstanceOf('Cake\Collection\Collection', $grouped);
  655. }
  656. /**
  657. * Tests indexBy
  658. *
  659. * @dataProvider indexByProvider
  660. */
  661. public function testIndexByCallback(iterable $items): void
  662. {
  663. $collection = new Collection($items);
  664. $grouped = $collection->indexBy(function ($element) {
  665. return $element['id'];
  666. });
  667. $expected = [
  668. 1 => ['id' => 1, 'name' => 'foo', 'parent_id' => 10],
  669. 3 => ['id' => 3, 'name' => 'baz', 'parent_id' => 10],
  670. 2 => ['id' => 2, 'name' => 'bar', 'parent_id' => 11],
  671. ];
  672. $this->assertEquals($expected, iterator_to_array($grouped));
  673. }
  674. /**
  675. * Tests indexBy with a deep property
  676. */
  677. public function testIndexByDeep(): void
  678. {
  679. $items = [
  680. ['id' => 1, 'name' => 'foo', 'thing' => ['parent_id' => 10]],
  681. ['id' => 2, 'name' => 'bar', 'thing' => ['parent_id' => 11]],
  682. ['id' => 3, 'name' => 'baz', 'thing' => ['parent_id' => 10]],
  683. ];
  684. $collection = new Collection($items);
  685. $grouped = $collection->indexBy('thing.parent_id');
  686. $expected = [
  687. 10 => ['id' => 3, 'name' => 'baz', 'thing' => ['parent_id' => 10]],
  688. 11 => ['id' => 2, 'name' => 'bar', 'thing' => ['parent_id' => 11]],
  689. ];
  690. $this->assertEquals($expected, iterator_to_array($grouped));
  691. }
  692. /**
  693. * Tests passing an invalid path to indexBy.
  694. */
  695. public function testIndexByInvalidPath(): void
  696. {
  697. $items = [
  698. ['id' => 1, 'name' => 'foo'],
  699. ['id' => 2, 'name' => 'bar'],
  700. ['id' => 3, 'name' => 'baz'],
  701. ];
  702. $collection = new Collection($items);
  703. $this->expectException(InvalidArgumentException::class);
  704. $this->expectExceptionMessage('Cannot index by path that does not exist or contains a null value');
  705. $collection->indexBy('missing');
  706. }
  707. /**
  708. * Tests passing an invalid path to indexBy.
  709. */
  710. public function testIndexByInvalidPathCallback(): void
  711. {
  712. $items = [
  713. ['id' => 1, 'name' => 'foo'],
  714. ['id' => 2, 'name' => 'bar'],
  715. ['id' => 3, 'name' => 'baz'],
  716. ];
  717. $collection = new Collection($items);
  718. $this->expectException(InvalidArgumentException::class);
  719. $this->expectExceptionMessage('Cannot index by path that does not exist or contains a null value');
  720. $collection->indexBy(function ($e) {
  721. return null;
  722. });
  723. }
  724. /**
  725. * Tests countBy
  726. *
  727. * @dataProvider groupByProvider
  728. */
  729. public function testCountBy(iterable $items): void
  730. {
  731. $collection = new Collection($items);
  732. $grouped = $collection->countBy('parent_id');
  733. $expected = [
  734. 10 => 2,
  735. 11 => 1,
  736. ];
  737. $result = iterator_to_array($grouped);
  738. $this->assertInstanceOf('Cake\Collection\Collection', $grouped);
  739. $this->assertEquals($expected, $result);
  740. }
  741. /**
  742. * Tests countBy
  743. *
  744. * @dataProvider groupByProvider
  745. */
  746. public function testCountByCallback(iterable $items): void
  747. {
  748. $expected = [
  749. 10 => 2,
  750. 11 => 1,
  751. ];
  752. $collection = new Collection($items);
  753. $grouped = $collection->countBy(function ($element) {
  754. return $element['parent_id'];
  755. });
  756. $this->assertEquals($expected, iterator_to_array($grouped));
  757. }
  758. /**
  759. * Tests shuffle
  760. *
  761. * @dataProvider simpleProvider
  762. */
  763. public function testShuffle(iterable $data): void
  764. {
  765. $collection = (new Collection($data))->shuffle();
  766. $result = $collection->toArray();
  767. $this->assertCount(4, $result);
  768. $this->assertContains(1, $result);
  769. $this->assertContains(2, $result);
  770. $this->assertContains(3, $result);
  771. $this->assertContains(4, $result);
  772. }
  773. /**
  774. * Tests shuffle with duplicate keys.
  775. */
  776. public function testShuffleDuplicateKeys(): void
  777. {
  778. $collection = (new Collection(['a' => 1]))->append(['a' => 2])->shuffle();
  779. $result = $collection->toArray();
  780. $this->assertCount(2, $result);
  781. $this->assertEquals([0, 1], array_keys($result));
  782. $this->assertContainsEquals(1, $result);
  783. $this->assertContainsEquals(2, $result);
  784. }
  785. /**
  786. * Tests sample
  787. *
  788. * @dataProvider simpleProvider
  789. */
  790. public function testSample(iterable $data): void
  791. {
  792. $result = (new Collection($data))->sample(2)->toArray();
  793. $this->assertCount(2, $result);
  794. foreach ($result as $number) {
  795. $this->assertContains($number, [1, 2, 3, 4]);
  796. }
  797. }
  798. /**
  799. * Tests the sample() method with a traversable non-iterator
  800. */
  801. public function testSampleWithTraversableNonIterator(): void
  802. {
  803. $collection = new Collection($this->datePeriod('2017-01-01', '2017-01-07'));
  804. $result = $collection->sample(3)->toList();
  805. $list = [
  806. '2017-01-01',
  807. '2017-01-02',
  808. '2017-01-03',
  809. '2017-01-04',
  810. '2017-01-05',
  811. '2017-01-06',
  812. ];
  813. $this->assertCount(3, $result);
  814. foreach ($result as $date) {
  815. $this->assertContains($date->format('Y-m-d'), $list);
  816. }
  817. }
  818. /**
  819. * Test toArray method
  820. */
  821. public function testToArray(): void
  822. {
  823. $data = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4];
  824. $collection = new Collection($data);
  825. $this->assertEquals($data, $collection->toArray());
  826. }
  827. /**
  828. * Test toList method
  829. *
  830. * @dataProvider simpleProvider
  831. */
  832. public function testToList(iterable $data): void
  833. {
  834. $collection = new Collection($data);
  835. $this->assertEquals([1, 2, 3, 4], $collection->toList());
  836. }
  837. /**
  838. * Test JSON encoding
  839. */
  840. public function testToJson(): void
  841. {
  842. $data = [1, 2, 3, 4];
  843. $collection = new Collection($data);
  844. $this->assertEquals(json_encode($data), json_encode($collection));
  845. }
  846. /**
  847. * Tests that Count returns the number of elements
  848. *
  849. * @dataProvider simpleProvider
  850. */
  851. public function testCollectionCount(iterable $list): void
  852. {
  853. $list = (new Collection($list))->buffered();
  854. $collection = new Collection($list);
  855. $this->assertSame(8, $collection->append($list)->count());
  856. }
  857. /**
  858. * Tests that countKeys returns the number of unique keys
  859. *
  860. * @dataProvider simpleProvider
  861. */
  862. public function testCollectionCountKeys(iterable $list): void
  863. {
  864. $list = (new Collection($list))->buffered();
  865. $collection = new Collection($list);
  866. $this->assertSame(4, $collection->append($list)->countKeys());
  867. }
  868. /**
  869. * Tests take method
  870. */
  871. public function testTake(): void
  872. {
  873. $data = [1, 2, 3, 4];
  874. $collection = new Collection($data);
  875. $taken = $collection->take(2);
  876. $this->assertEquals([1, 2], $taken->toArray());
  877. $taken = $collection->take(3);
  878. $this->assertEquals([1, 2, 3], $taken->toArray());
  879. $taken = $collection->take(500);
  880. $this->assertEquals([1, 2, 3, 4], $taken->toArray());
  881. $taken = $collection->take(1);
  882. $this->assertEquals([1], $taken->toArray());
  883. $taken = $collection->take();
  884. $this->assertEquals([1], $taken->toArray());
  885. $taken = $collection->take(2, 2);
  886. $this->assertEquals([2 => 3, 3 => 4], $taken->toArray());
  887. }
  888. /**
  889. * Tests the take() method with a traversable non-iterator
  890. */
  891. public function testTakeWithTraversableNonIterator(): void
  892. {
  893. $collection = new Collection($this->datePeriod('2017-01-01', '2017-01-07'));
  894. $result = $collection->take(3, 1)->toList();
  895. $expected = [
  896. new DateTime('2017-01-02'),
  897. new DateTime('2017-01-03'),
  898. new DateTime('2017-01-04'),
  899. ];
  900. $this->assertEquals($expected, $result);
  901. }
  902. /**
  903. * Tests match
  904. */
  905. public function testMatch(): void
  906. {
  907. $items = [
  908. ['id' => 1, 'name' => 'foo', 'thing' => ['parent_id' => 10]],
  909. ['id' => 2, 'name' => 'bar', 'thing' => ['parent_id' => 11]],
  910. ['id' => 3, 'name' => 'baz', 'thing' => ['parent_id' => 10]],
  911. ];
  912. $collection = new Collection($items);
  913. $matched = $collection->match(['thing.parent_id' => 10, 'name' => 'baz']);
  914. $this->assertEquals([2 => $items[2]], $matched->toArray());
  915. $matched = $collection->match(['thing.parent_id' => 10]);
  916. $this->assertEquals(
  917. [0 => $items[0], 2 => $items[2]],
  918. $matched->toArray()
  919. );
  920. $matched = $collection->match(['thing.parent_id' => 500]);
  921. $this->assertEquals([], $matched->toArray());
  922. $matched = $collection->match(['parent_id' => 10, 'name' => 'baz']);
  923. $this->assertEquals([], $matched->toArray());
  924. }
  925. /**
  926. * Tests firstMatch
  927. */
  928. public function testFirstMatch(): void
  929. {
  930. $items = [
  931. ['id' => 1, 'name' => 'foo', 'thing' => ['parent_id' => 10]],
  932. ['id' => 2, 'name' => 'bar', 'thing' => ['parent_id' => 11]],
  933. ['id' => 3, 'name' => 'baz', 'thing' => ['parent_id' => 10]],
  934. ];
  935. $collection = new Collection($items);
  936. $matched = $collection->firstMatch(['thing.parent_id' => 10]);
  937. $this->assertEquals(
  938. ['id' => 1, 'name' => 'foo', 'thing' => ['parent_id' => 10]],
  939. $matched
  940. );
  941. $matched = $collection->firstMatch(['thing.parent_id' => 10, 'name' => 'baz']);
  942. $this->assertEquals(
  943. ['id' => 3, 'name' => 'baz', 'thing' => ['parent_id' => 10]],
  944. $matched
  945. );
  946. }
  947. /**
  948. * Tests the append method
  949. */
  950. public function testAppend(): void
  951. {
  952. $collection = new Collection([1, 2, 3]);
  953. $combined = $collection->append([4, 5, 6]);
  954. $this->assertEquals([1, 2, 3, 4, 5, 6], $combined->toArray(false));
  955. $collection = new Collection(['a' => 1, 'b' => 2]);
  956. $combined = $collection->append(['c' => 3, 'a' => 4]);
  957. $this->assertEquals(['a' => 4, 'b' => 2, 'c' => 3], $combined->toArray());
  958. }
  959. /**
  960. * Tests the appendItem method
  961. */
  962. public function testAppendItem(): void
  963. {
  964. $collection = new Collection([1, 2, 3]);
  965. $combined = $collection->appendItem(4);
  966. $this->assertEquals([1, 2, 3, 4], $combined->toArray(false));
  967. $collection = new Collection(['a' => 1, 'b' => 2]);
  968. $combined = $collection->appendItem(3, 'c');
  969. $combined = $combined->appendItem(4, 'a');
  970. $this->assertEquals(['a' => 4, 'b' => 2, 'c' => 3], $combined->toArray());
  971. }
  972. /**
  973. * Tests the prepend method
  974. */
  975. public function testPrepend(): void
  976. {
  977. $collection = new Collection([1, 2, 3]);
  978. $combined = $collection->prepend(['a']);
  979. $this->assertEquals(['a', 1, 2, 3], $combined->toList());
  980. $collection = new Collection(['c' => 3, 'd' => 4]);
  981. $combined = $collection->prepend(['a' => 1, 'b' => 2]);
  982. $this->assertEquals(['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4], $combined->toArray());
  983. }
  984. /**
  985. * Tests prependItem method
  986. */
  987. public function testPrependItem(): void
  988. {
  989. $collection = new Collection([1, 2, 3]);
  990. $combined = $collection->prependItem('a');
  991. $this->assertEquals(['a', 1, 2, 3], $combined->toList());
  992. $collection = new Collection(['c' => 3, 'd' => 4]);
  993. $combined = $collection->prependItem(2, 'b');
  994. $combined = $combined->prependItem(1, 'a');
  995. $this->assertEquals(['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4], $combined->toArray());
  996. }
  997. /**
  998. * Tests prependItem method
  999. */
  1000. public function testPrependItemPreserveKeys(): void
  1001. {
  1002. $collection = new Collection([1, 2, 3]);
  1003. $combined = $collection->prependItem('a');
  1004. $this->assertEquals(['a', 1, 2, 3], $combined->toList());
  1005. $collection = new Collection(['c' => 3, 'd' => 4]);
  1006. $combined = $collection->prependItem(2, 'b');
  1007. $combined = $combined->prependItem(1, 'a');
  1008. $this->assertEquals(['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4], $combined->toArray());
  1009. }
  1010. /**
  1011. * Tests the append method with iterator
  1012. */
  1013. public function testAppendIterator(): void
  1014. {
  1015. $collection = new Collection([1, 2, 3]);
  1016. $iterator = new ArrayIterator([4, 5, 6]);
  1017. $combined = $collection->append($iterator);
  1018. $this->assertEquals([1, 2, 3, 4, 5, 6], $combined->toList());
  1019. }
  1020. public function testAppendNotCollectionInstance(): void
  1021. {
  1022. $collection = new TestCollection([1, 2, 3]);
  1023. $combined = $collection->append([4, 5, 6]);
  1024. $this->assertEquals([1, 2, 3, 4, 5, 6], $combined->toList());
  1025. }
  1026. /**
  1027. * Tests that by calling compile internal iteration operations are not done
  1028. * more than once
  1029. */
  1030. public function testCompile(): void
  1031. {
  1032. $items = ['a' => 1, 'b' => 2, 'c' => 3];
  1033. $collection = new Collection($items);
  1034. $results = [];
  1035. $compiled = $collection
  1036. ->map(function ($value, $key) use (&$results) {
  1037. $results[] = [$key => $value];
  1038. return $value + 3;
  1039. })
  1040. ->compile();
  1041. $this->assertSame(['a' => 4, 'b' => 5, 'c' => 6], $compiled->toArray());
  1042. $this->assertSame(['a' => 4, 'b' => 5, 'c' => 6], $compiled->toArray());
  1043. $this->assertSame([['a' => 1], ['b' => 2], ['c' => 3]], $results);
  1044. }
  1045. /**
  1046. * Tests converting a non rewindable iterator into a rewindable one using
  1047. * the buffered method.
  1048. */
  1049. public function testBuffered(): void
  1050. {
  1051. $items = new NoRewindIterator(new ArrayIterator(['a' => 4, 'b' => 5, 'c' => 6]));
  1052. $buffered = (new Collection($items))->buffered();
  1053. $this->assertEquals(['a' => 4, 'b' => 5, 'c' => 6], $buffered->toArray());
  1054. $this->assertEquals(['a' => 4, 'b' => 5, 'c' => 6], $buffered->toArray());
  1055. }
  1056. public function testBufferedIterator(): void
  1057. {
  1058. $data = [
  1059. ['myField' => '1'],
  1060. ['myField' => '2'],
  1061. ['myField' => '3'],
  1062. ];
  1063. $buffered = (new Collection($data))->buffered();
  1064. // Check going forwards
  1065. $this->assertNotEmpty($buffered->firstMatch(['myField' => '1']));
  1066. $this->assertNotEmpty($buffered->firstMatch(['myField' => '2']));
  1067. $this->assertNotEmpty($buffered->firstMatch(['myField' => '3']));
  1068. // And backwards.
  1069. $this->assertNotEmpty($buffered->firstMatch(['myField' => '3']));
  1070. $this->assertNotEmpty($buffered->firstMatch(['myField' => '2']));
  1071. $this->assertNotEmpty($buffered->firstMatch(['myField' => '1']));
  1072. }
  1073. /**
  1074. * Tests the combine method
  1075. */
  1076. public function testCombine(): void
  1077. {
  1078. $items = [
  1079. ['id' => 1, 'name' => 'foo', 'parent' => 'a'],
  1080. ['id' => 2, 'name' => 'bar', 'parent' => 'b'],
  1081. ['id' => 3, 'name' => 'baz', 'parent' => 'a'],
  1082. ];
  1083. $collection = (new Collection($items))->combine('id', 'name');
  1084. $expected = [1 => 'foo', 2 => 'bar', 3 => 'baz'];
  1085. $this->assertEquals($expected, $collection->toArray());
  1086. $expected = ['foo' => 1, 'bar' => 2, 'baz' => 3];
  1087. $collection = (new Collection($items))->combine('name', 'id');
  1088. $this->assertEquals($expected, $collection->toArray());
  1089. $collection = (new Collection($items))->combine('id', 'name', 'parent');
  1090. $expected = ['a' => [1 => 'foo', 3 => 'baz'], 'b' => [2 => 'bar']];
  1091. $this->assertEquals($expected, $collection->toArray());
  1092. $expected = [
  1093. '0-1' => ['foo-0-1' => '0-1-foo'],
  1094. '1-2' => ['bar-1-2' => '1-2-bar'],
  1095. '2-3' => ['baz-2-3' => '2-3-baz'],
  1096. ];
  1097. $collection = (new Collection($items))->combine(
  1098. function ($value, $key) {
  1099. return $value['name'] . '-' . $key;
  1100. },
  1101. function ($value, $key) {
  1102. return $key . '-' . $value['name'];
  1103. },
  1104. function ($value, $key) {
  1105. return $key . '-' . $value['id'];
  1106. }
  1107. );
  1108. $this->assertEquals($expected, $collection->toArray());
  1109. $collection = (new Collection($items))->combine('id', 'crazy');
  1110. $this->assertEquals([1 => null, 2 => null, 3 => null], $collection->toArray());
  1111. }
  1112. /**
  1113. * Tests the nest method with only one level
  1114. */
  1115. public function testNest(): void
  1116. {
  1117. $items = [
  1118. ['id' => 1, 'parent_id' => null],
  1119. ['id' => 2, 'parent_id' => 1],
  1120. ['id' => 3, 'parent_id' => 1],
  1121. ['id' => 4, 'parent_id' => 1],
  1122. ['id' => 5, 'parent_id' => 6],
  1123. ['id' => 6, 'parent_id' => null],
  1124. ['id' => 7, 'parent_id' => 1],
  1125. ['id' => 8, 'parent_id' => 6],
  1126. ['id' => 9, 'parent_id' => 6],
  1127. ['id' => 10, 'parent_id' => 6],
  1128. ];
  1129. $collection = (new Collection($items))->nest('id', 'parent_id');
  1130. $expected = [
  1131. [
  1132. 'id' => 1,
  1133. 'parent_id' => null,
  1134. 'children' => [
  1135. ['id' => 2, 'parent_id' => 1, 'children' => []],
  1136. ['id' => 3, 'parent_id' => 1, 'children' => []],
  1137. ['id' => 4, 'parent_id' => 1, 'children' => []],
  1138. ['id' => 7, 'parent_id' => 1, 'children' => []],
  1139. ],
  1140. ],
  1141. [
  1142. 'id' => 6,
  1143. 'parent_id' => null,
  1144. 'children' => [
  1145. ['id' => 5, 'parent_id' => 6, 'children' => []],
  1146. ['id' => 8, 'parent_id' => 6, 'children' => []],
  1147. ['id' => 9, 'parent_id' => 6, 'children' => []],
  1148. ['id' => 10, 'parent_id' => 6, 'children' => []],
  1149. ],
  1150. ],
  1151. ];
  1152. $this->assertEquals($expected, $collection->toArray());
  1153. }
  1154. /**
  1155. * Tests the nest method with alternate nesting key
  1156. */
  1157. public function testNestAlternateNestingKey(): void
  1158. {
  1159. $items = [
  1160. ['id' => 1, 'parent_id' => null],
  1161. ['id' => 2, 'parent_id' => 1],
  1162. ['id' => 3, 'parent_id' => 1],
  1163. ['id' => 4, 'parent_id' => 1],
  1164. ['id' => 5, 'parent_id' => 6],
  1165. ['id' => 6, 'parent_id' => null],
  1166. ['id' => 7, 'parent_id' => 1],
  1167. ['id' => 8, 'parent_id' => 6],
  1168. ['id' => 9, 'parent_id' => 6],
  1169. ['id' => 10, 'parent_id' => 6],
  1170. ];
  1171. $collection = (new Collection($items))->nest('id', 'parent_id', 'nodes');
  1172. $expected = [
  1173. [
  1174. 'id' => 1,
  1175. 'parent_id' => null,
  1176. 'nodes' => [
  1177. ['id' => 2, 'parent_id' => 1, 'nodes' => []],
  1178. ['id' => 3, 'parent_id' => 1, 'nodes' => []],
  1179. ['id' => 4, 'parent_id' => 1, 'nodes' => []],
  1180. ['id' => 7, 'parent_id' => 1, 'nodes' => []],
  1181. ],
  1182. ],
  1183. [
  1184. 'id' => 6,
  1185. 'parent_id' => null,
  1186. 'nodes' => [
  1187. ['id' => 5, 'parent_id' => 6, 'nodes' => []],
  1188. ['id' => 8, 'parent_id' => 6, 'nodes' => []],
  1189. ['id' => 9, 'parent_id' => 6, 'nodes' => []],
  1190. ['id' => 10, 'parent_id' => 6, 'nodes' => []],
  1191. ],
  1192. ],
  1193. ];
  1194. $this->assertEquals($expected, $collection->toArray());
  1195. }
  1196. /**
  1197. * Tests the nest method with more than one level
  1198. */
  1199. public function testNestMultiLevel(): void
  1200. {
  1201. $items = [
  1202. ['id' => 1, 'parent_id' => null],
  1203. ['id' => 2, 'parent_id' => 1],
  1204. ['id' => 3, 'parent_id' => 2],
  1205. ['id' => 4, 'parent_id' => 2],
  1206. ['id' => 5, 'parent_id' => 3],
  1207. ['id' => 6, 'parent_id' => null],
  1208. ['id' => 7, 'parent_id' => 3],
  1209. ['id' => 8, 'parent_id' => 4],
  1210. ['id' => 9, 'parent_id' => 6],
  1211. ['id' => 10, 'parent_id' => 6],
  1212. ];
  1213. $collection = (new Collection($items))->nest('id', 'parent_id', 'nodes');
  1214. $expected = [
  1215. [
  1216. 'id' => 1,
  1217. 'parent_id' => null,
  1218. 'nodes' => [
  1219. [
  1220. 'id' => 2,
  1221. 'parent_id' => 1,
  1222. 'nodes' => [
  1223. [
  1224. 'id' => 3,
  1225. 'parent_id' => 2,
  1226. 'nodes' => [
  1227. ['id' => 5, 'parent_id' => 3, 'nodes' => []],
  1228. ['id' => 7, 'parent_id' => 3, 'nodes' => []],
  1229. ],
  1230. ],
  1231. [
  1232. 'id' => 4,
  1233. 'parent_id' => 2,
  1234. 'nodes' => [
  1235. ['id' => 8, 'parent_id' => 4, 'nodes' => []],
  1236. ],
  1237. ],
  1238. ],
  1239. ],
  1240. ],
  1241. ],
  1242. [
  1243. 'id' => 6,
  1244. 'parent_id' => null,
  1245. 'nodes' => [
  1246. ['id' => 9, 'parent_id' => 6, 'nodes' => []],
  1247. ['id' => 10, 'parent_id' => 6, 'nodes' => []],
  1248. ],
  1249. ],
  1250. ];
  1251. $this->assertEquals($expected, $collection->toArray());
  1252. }
  1253. /**
  1254. * Tests the nest method with more than one level
  1255. */
  1256. public function testNestMultiLevelAlternateNestingKey(): void
  1257. {
  1258. $items = [
  1259. ['id' => 1, 'parent_id' => null],
  1260. ['id' => 2, 'parent_id' => 1],
  1261. ['id' => 3, 'parent_id' => 2],
  1262. ['id' => 4, 'parent_id' => 2],
  1263. ['id' => 5, 'parent_id' => 3],
  1264. ['id' => 6, 'parent_id' => null],
  1265. ['id' => 7, 'parent_id' => 3],
  1266. ['id' => 8, 'parent_id' => 4],
  1267. ['id' => 9, 'parent_id' => 6],
  1268. ['id' => 10, 'parent_id' => 6],
  1269. ];
  1270. $collection = (new Collection($items))->nest('id', 'parent_id');
  1271. $expected = [
  1272. [
  1273. 'id' => 1,
  1274. 'parent_id' => null,
  1275. 'children' => [
  1276. [
  1277. 'id' => 2,
  1278. 'parent_id' => 1,
  1279. 'children' => [
  1280. [
  1281. 'id' => 3,
  1282. 'parent_id' => 2,
  1283. 'children' => [
  1284. ['id' => 5, 'parent_id' => 3, 'children' => []],
  1285. ['id' => 7, 'parent_id' => 3, 'children' => []],
  1286. ],
  1287. ],
  1288. [
  1289. 'id' => 4,
  1290. 'parent_id' => 2,
  1291. 'children' => [
  1292. ['id' => 8, 'parent_id' => 4, 'children' => []],
  1293. ],
  1294. ],
  1295. ],
  1296. ],
  1297. ],
  1298. ],
  1299. [
  1300. 'id' => 6,
  1301. 'parent_id' => null,
  1302. 'children' => [
  1303. ['id' => 9, 'parent_id' => 6, 'children' => []],
  1304. ['id' => 10, 'parent_id' => 6, 'children' => []],
  1305. ],
  1306. ],
  1307. ];
  1308. $this->assertEquals($expected, $collection->toArray());
  1309. }
  1310. /**
  1311. * Tests the nest method with more than one level
  1312. */
  1313. public function testNestObjects(): void
  1314. {
  1315. $items = [
  1316. new ArrayObject(['id' => 1, 'parent_id' => null]),
  1317. new ArrayObject(['id' => 2, 'parent_id' => 1]),
  1318. new ArrayObject(['id' => 3, 'parent_id' => 2]),
  1319. new ArrayObject(['id' => 4, 'parent_id' => 2]),
  1320. new ArrayObject(['id' => 5, 'parent_id' => 3]),
  1321. new ArrayObject(['id' => 6, 'parent_id' => null]),
  1322. new ArrayObject(['id' => 7, 'parent_id' => 3]),
  1323. new ArrayObject(['id' => 8, 'parent_id' => 4]),
  1324. new ArrayObject(['id' => 9, 'parent_id' => 6]),
  1325. new ArrayObject(['id' => 10, 'parent_id' => 6]),
  1326. ];
  1327. $collection = (new Collection($items))->nest('id', 'parent_id');
  1328. $expected = [
  1329. new ArrayObject([
  1330. 'id' => 1,
  1331. 'parent_id' => null,
  1332. 'children' => [
  1333. new ArrayObject([
  1334. 'id' => 2,
  1335. 'parent_id' => 1,
  1336. 'children' => [
  1337. new ArrayObject([
  1338. 'id' => 3,
  1339. 'parent_id' => 2,
  1340. 'children' => [
  1341. new ArrayObject(['id' => 5, 'parent_id' => 3, 'children' => []]),
  1342. new ArrayObject(['id' => 7, 'parent_id' => 3, 'children' => []]),
  1343. ],
  1344. ]),
  1345. new ArrayObject([
  1346. 'id' => 4,
  1347. 'parent_id' => 2,
  1348. 'children' => [
  1349. new ArrayObject(['id' => 8, 'parent_id' => 4, 'children' => []]),
  1350. ],
  1351. ]),
  1352. ],
  1353. ]),
  1354. ],
  1355. ]),
  1356. new ArrayObject([
  1357. 'id' => 6,
  1358. 'parent_id' => null,
  1359. 'children' => [
  1360. new ArrayObject(['id' => 9, 'parent_id' => 6, 'children' => []]),
  1361. new ArrayObject(['id' => 10, 'parent_id' => 6, 'children' => []]),
  1362. ],
  1363. ]),
  1364. ];
  1365. $this->assertEquals($expected, $collection->toArray());
  1366. }
  1367. /**
  1368. * Tests the nest method with more than one level
  1369. */
  1370. public function testNestObjectsAlternateNestingKey(): void
  1371. {
  1372. $items = [
  1373. new ArrayObject(['id' => 1, 'parent_id' => null]),
  1374. new ArrayObject(['id' => 2, 'parent_id' => 1]),
  1375. new ArrayObject(['id' => 3, 'parent_id' => 2]),
  1376. new ArrayObject(['id' => 4, 'parent_id' => 2]),
  1377. new ArrayObject(['id' => 5, 'parent_id' => 3]),
  1378. new ArrayObject(['id' => 6, 'parent_id' => null]),
  1379. new ArrayObject(['id' => 7, 'parent_id' => 3]),
  1380. new ArrayObject(['id' => 8, 'parent_id' => 4]),
  1381. new ArrayObject(['id' => 9, 'parent_id' => 6]),
  1382. new ArrayObject(['id' => 10, 'parent_id' => 6]),
  1383. ];
  1384. $collection = (new Collection($items))->nest('id', 'parent_id', 'nodes');
  1385. $expected = [
  1386. new ArrayObject([
  1387. 'id' => 1,
  1388. 'parent_id' => null,
  1389. 'nodes' => [
  1390. new ArrayObject([
  1391. 'id' => 2,
  1392. 'parent_id' => 1,
  1393. 'nodes' => [
  1394. new ArrayObject([
  1395. 'id' => 3,
  1396. 'parent_id' => 2,
  1397. 'nodes' => [
  1398. new ArrayObject(['id' => 5, 'parent_id' => 3, 'nodes' => []]),
  1399. new ArrayObject(['id' => 7, 'parent_id' => 3, 'nodes' => []]),
  1400. ],
  1401. ]),
  1402. new ArrayObject([
  1403. 'id' => 4,
  1404. 'parent_id' => 2,
  1405. 'nodes' => [
  1406. new ArrayObject(['id' => 8, 'parent_id' => 4, 'nodes' => []]),
  1407. ],
  1408. ]),
  1409. ],
  1410. ]),
  1411. ],
  1412. ]),
  1413. new ArrayObject([
  1414. 'id' => 6,
  1415. 'parent_id' => null,
  1416. 'nodes' => [
  1417. new ArrayObject(['id' => 9, 'parent_id' => 6, 'nodes' => []]),
  1418. new ArrayObject(['id' => 10, 'parent_id' => 6, 'nodes' => []]),
  1419. ],
  1420. ]),
  1421. ];
  1422. $this->assertEquals($expected, $collection->toArray());
  1423. }
  1424. /**
  1425. * Tests insert
  1426. */
  1427. public function testInsert(): void
  1428. {
  1429. $items = [['a' => 1], ['b' => 2]];
  1430. $collection = new Collection($items);
  1431. $iterator = $collection->insert('c', [3, 4]);
  1432. $this->assertInstanceOf('Cake\Collection\Iterator\InsertIterator', $iterator);
  1433. $this->assertEquals(
  1434. [['a' => 1, 'c' => 3], ['b' => 2, 'c' => 4]],
  1435. iterator_to_array($iterator)
  1436. );
  1437. }
  1438. /**
  1439. * Provider for testing each of the directions for listNested
  1440. *
  1441. * @return array
  1442. */
  1443. public static function nestedListProvider(): array
  1444. {
  1445. return [
  1446. ['desc', [1, 2, 3, 5, 7, 4, 8, 6, 9, 10]],
  1447. ['asc', [5, 7, 3, 8, 4, 2, 1, 9, 10, 6]],
  1448. ['leaves', [5, 7, 8, 9, 10]],
  1449. ];
  1450. }
  1451. /**
  1452. * Tests the listNested method with the default 'children' nesting key
  1453. *
  1454. * @dataProvider nestedListProvider
  1455. */
  1456. public function testListNested(string $dir, array $expected): void
  1457. {
  1458. $items = [
  1459. ['id' => 1, 'parent_id' => null],
  1460. ['id' => 2, 'parent_id' => 1],
  1461. ['id' => 3, 'parent_id' => 2],
  1462. ['id' => 4, 'parent_id' => 2],
  1463. ['id' => 5, 'parent_id' => 3],
  1464. ['id' => 6, 'parent_id' => null],
  1465. ['id' => 7, 'parent_id' => 3],
  1466. ['id' => 8, 'parent_id' => 4],
  1467. ['id' => 9, 'parent_id' => 6],
  1468. ['id' => 10, 'parent_id' => 6],
  1469. ];
  1470. $collection = (new Collection($items))->nest('id', 'parent_id')->listNested($dir);
  1471. $this->assertEquals($expected, $collection->extract('id')->toArray(false));
  1472. }
  1473. /**
  1474. * Tests the listNested spacer output.
  1475. */
  1476. public function testListNestedSpacer(): void
  1477. {
  1478. $items = [
  1479. ['id' => 1, 'parent_id' => null, 'name' => 'Birds'],
  1480. ['id' => 2, 'parent_id' => 1, 'name' => 'Land Birds'],
  1481. ['id' => 3, 'parent_id' => 1, 'name' => 'Eagle'],
  1482. ['id' => 4, 'parent_id' => 1, 'name' => 'Seagull'],
  1483. ['id' => 5, 'parent_id' => 6, 'name' => 'Clown Fish'],
  1484. ['id' => 6, 'parent_id' => null, 'name' => 'Fish'],
  1485. ];
  1486. $collection = (new Collection($items))->nest('id', 'parent_id')->listNested();
  1487. $expected = [
  1488. 'Birds',
  1489. '---Land Birds',
  1490. '---Eagle',
  1491. '---Seagull',
  1492. 'Fish',
  1493. '---Clown Fish',
  1494. ];
  1495. $this->assertSame($expected, $collection->printer('name', 'id', '---')->toList());
  1496. }
  1497. /**
  1498. * Tests using listNested with a different nesting key
  1499. */
  1500. public function testListNestedCustomKey(): void
  1501. {
  1502. $items = [
  1503. ['id' => 1, 'stuff' => [['id' => 2, 'stuff' => [['id' => 3]]]]],
  1504. ['id' => 4, 'stuff' => [['id' => 5]]],
  1505. ];
  1506. $collection = (new Collection($items))->listNested('desc', 'stuff');
  1507. $this->assertEquals(range(1, 5), $collection->extract('id')->toArray(false));
  1508. }
  1509. /**
  1510. * Tests flattening the collection using a custom callable function
  1511. */
  1512. public function testListNestedWithCallable(): void
  1513. {
  1514. $items = [
  1515. ['id' => 1, 'stuff' => [['id' => 2, 'stuff' => [['id' => 3]]]]],
  1516. ['id' => 4, 'stuff' => [['id' => 5]]],
  1517. ];
  1518. $collection = (new Collection($items))->listNested('desc', function ($item) {
  1519. return $item['stuff'] ?? [];
  1520. });
  1521. $this->assertEquals(range(1, 5), $collection->extract('id')->toArray(false));
  1522. }
  1523. /**
  1524. * Provider for sumOf tests
  1525. *
  1526. * @return array
  1527. */
  1528. public static function sumOfProvider(): array
  1529. {
  1530. $items = [
  1531. ['invoice' => ['total' => 100]],
  1532. ['invoice' => ['total' => 200]],
  1533. ];
  1534. $floatItems = [
  1535. ['invoice' => ['total' => 100.0]],
  1536. ['invoice' => ['total' => 200.0]],
  1537. ];
  1538. return [
  1539. 'array' => [$items, 300],
  1540. 'iterator' => [self::yieldItems($items), 300],
  1541. 'floatArray' => [$floatItems, 300.0],
  1542. 'floatIterator' => [self::yieldItems($floatItems), 300.0],
  1543. ];
  1544. }
  1545. /**
  1546. * Tests the sumOf method
  1547. *
  1548. * @dataProvider sumOfProvider
  1549. * @param float|int $expected
  1550. */
  1551. public function testSumOf(iterable $items, $expected): void
  1552. {
  1553. $this->assertEquals($expected, (new Collection($items))->sumOf('invoice.total'));
  1554. }
  1555. /**
  1556. * Tests the sumOf method
  1557. *
  1558. * @dataProvider sumOfProvider
  1559. * @param float|int $expected
  1560. */
  1561. public function testSumOfCallable(iterable $items, $expected): void
  1562. {
  1563. $sum = (new Collection($items))->sumOf(function ($v) {
  1564. return $v['invoice']['total'];
  1565. });
  1566. $this->assertEquals($expected, $sum);
  1567. }
  1568. /**
  1569. * Tests the stopWhen method with a callable
  1570. *
  1571. * @dataProvider simpleProvider
  1572. */
  1573. public function testStopWhenCallable(iterable $items): void
  1574. {
  1575. $collection = (new Collection($items))->stopWhen(function ($v) {
  1576. return $v > 3;
  1577. });
  1578. $this->assertEquals(['a' => 1, 'b' => 2, 'c' => 3], $collection->toArray());
  1579. }
  1580. /**
  1581. * Tests the stopWhen method with a matching array
  1582. */
  1583. public function testStopWhenWithArray(): void
  1584. {
  1585. $items = [
  1586. ['foo' => 'bar'],
  1587. ['foo' => 'baz'],
  1588. ['foo' => 'foo'],
  1589. ];
  1590. $collection = (new Collection($items))->stopWhen(['foo' => 'baz']);
  1591. $this->assertEquals([['foo' => 'bar']], $collection->toArray());
  1592. }
  1593. /**
  1594. * Tests the unfold method
  1595. */
  1596. public function testUnfold(): void
  1597. {
  1598. $items = [
  1599. [1, 2, 3, 4],
  1600. [5, 6],
  1601. [7, 8],
  1602. ];
  1603. $collection = (new Collection($items))->unfold();
  1604. $this->assertEquals(range(1, 8), $collection->toArray(false));
  1605. $items = [
  1606. [1, 2],
  1607. new Collection([3, 4]),
  1608. ];
  1609. $collection = (new Collection($items))->unfold();
  1610. $this->assertEquals(range(1, 4), $collection->toArray(false));
  1611. }
  1612. /**
  1613. * Tests the unfold method with empty levels
  1614. */
  1615. public function testUnfoldEmptyLevels(): void
  1616. {
  1617. $items = [[], [1, 2], []];
  1618. $collection = (new Collection($items))->unfold();
  1619. $this->assertEquals(range(1, 2), $collection->toArray(false));
  1620. $items = [];
  1621. $collection = (new Collection($items))->unfold();
  1622. $this->assertEmpty($collection->toArray(false));
  1623. }
  1624. /**
  1625. * Tests the unfold when passing a callable
  1626. */
  1627. public function testUnfoldWithCallable(): void
  1628. {
  1629. $items = [1, 2, 3];
  1630. $collection = (new Collection($items))->unfold(function ($item) {
  1631. return range($item, $item * 2);
  1632. });
  1633. $expected = [1, 2, 2, 3, 4, 3, 4, 5, 6];
  1634. $this->assertEquals($expected, $collection->toArray(false));
  1635. }
  1636. /**
  1637. * Tests the through() method
  1638. */
  1639. public function testThrough(): void
  1640. {
  1641. $items = [1, 2, 3];
  1642. $collection = (new Collection($items))->through(function ($collection) {
  1643. return $collection->append($collection->toList());
  1644. });
  1645. $this->assertEquals([1, 2, 3, 1, 2, 3], $collection->toList());
  1646. }
  1647. /**
  1648. * Tests the through method when it returns an array
  1649. */
  1650. public function testThroughReturnArray(): void
  1651. {
  1652. $items = [1, 2, 3];
  1653. $collection = (new Collection($items))->through(function ($collection) {
  1654. $list = $collection->toList();
  1655. return array_merge($list, $list);
  1656. });
  1657. $this->assertEquals([1, 2, 3, 1, 2, 3], $collection->toList());
  1658. }
  1659. /**
  1660. * Tests that the sortBy method does not die when something that is not a
  1661. * collection is passed
  1662. */
  1663. public function testComplexSortBy(): void
  1664. {
  1665. $results = collection([3, 7])
  1666. ->unfold(function ($value) {
  1667. return [
  1668. ['sorting' => $value * 2],
  1669. ['sorting' => $value * 2],
  1670. ];
  1671. })
  1672. ->sortBy('sorting')
  1673. ->extract('sorting')
  1674. ->toList();
  1675. $this->assertEquals([14, 14, 6, 6], $results);
  1676. }
  1677. /**
  1678. * Tests __debugInfo() or debug() usage
  1679. */
  1680. public function testDebug(): void
  1681. {
  1682. $items = [1, 2, 3];
  1683. $collection = new Collection($items);
  1684. $result = $collection->__debugInfo();
  1685. $expected = [
  1686. 'count' => 3,
  1687. ];
  1688. $this->assertSame($expected, $result);
  1689. // Calling it again will rewind
  1690. $result = $collection->__debugInfo();
  1691. $expected = [
  1692. 'count' => 3,
  1693. ];
  1694. $this->assertSame($expected, $result);
  1695. // Make sure it also works with non rewindable iterators
  1696. $iterator = new NoRewindIterator(new ArrayIterator($items));
  1697. $collection = new Collection($iterator);
  1698. $result = $collection->__debugInfo();
  1699. $expected = [
  1700. 'count' => 3,
  1701. ];
  1702. $this->assertSame($expected, $result);
  1703. // Calling it again will in this case not rewind
  1704. $result = $collection->__debugInfo();
  1705. $expected = [
  1706. 'count' => 0,
  1707. ];
  1708. $this->assertSame($expected, $result);
  1709. $filter = function ($value) {
  1710. throw new Exception('filter exception');
  1711. };
  1712. $iterator = new CallbackFilterIterator(new ArrayIterator($items), $filter);
  1713. $collection = new Collection($iterator);
  1714. $result = $collection->__debugInfo();
  1715. $expected = [
  1716. 'count' => 'An exception occurred while getting count',
  1717. ];
  1718. $this->assertSame($expected, $result);
  1719. }
  1720. /**
  1721. * Tests the isEmpty() method
  1722. */
  1723. public function testIsEmpty(): void
  1724. {
  1725. $collection = new Collection([1, 2, 3]);
  1726. $this->assertFalse($collection->isEmpty());
  1727. $collection = $collection->map(function () {
  1728. return null;
  1729. });
  1730. $this->assertFalse($collection->isEmpty());
  1731. $collection = $collection->filter();
  1732. $this->assertTrue($collection->isEmpty());
  1733. }
  1734. /**
  1735. * Tests the isEmpty() method does not consume data
  1736. * from buffered iterators.
  1737. */
  1738. public function testIsEmptyDoesNotConsume(): void
  1739. {
  1740. $array = new ArrayIterator([1, 2, 3]);
  1741. $inner = new BufferedIterator($array);
  1742. $collection = new Collection($inner);
  1743. $this->assertFalse($collection->isEmpty());
  1744. $this->assertCount(3, $collection->toArray());
  1745. }
  1746. /**
  1747. * Tests the zip() method
  1748. */
  1749. public function testZip(): void
  1750. {
  1751. $collection = new Collection([1, 2]);
  1752. $zipped = $collection->zip([3, 4]);
  1753. $this->assertEquals([[1, 3], [2, 4]], $zipped->toList());
  1754. $collection = new Collection([1, 2]);
  1755. $zipped = $collection->zip([3]);
  1756. $this->assertEquals([[1, 3]], $zipped->toList());
  1757. $collection = new Collection([1, 2]);
  1758. $zipped = $collection->zip([3, 4], [5, 6], [7, 8], [9, 10, 11]);
  1759. $this->assertEquals([
  1760. [1, 3, 5, 7, 9],
  1761. [2, 4, 6, 8, 10],
  1762. ], $zipped->toList());
  1763. }
  1764. /**
  1765. * Tests the zipWith() method
  1766. */
  1767. public function testZipWith(): void
  1768. {
  1769. $collection = new Collection([1, 2]);
  1770. $zipped = $collection->zipWith([3, 4], function ($a, $b) {
  1771. return $a * $b;
  1772. });
  1773. $this->assertEquals([3, 8], $zipped->toList());
  1774. $zipped = $collection->zipWith([3, 4], [5, 6, 7], function (...$args) {
  1775. return array_sum($args);
  1776. });
  1777. $this->assertEquals([9, 12], $zipped->toList());
  1778. }
  1779. /**
  1780. * Tests the skip() method
  1781. */
  1782. public function testSkip(): void
  1783. {
  1784. $collection = new Collection([1, 2, 3, 4, 5]);
  1785. $this->assertEquals([3, 4, 5], $collection->skip(2)->toList());
  1786. $this->assertEquals([1, 2, 3, 4, 5], $collection->skip(0)->toList());
  1787. $this->assertEquals([4, 5], $collection->skip(3)->toList());
  1788. $this->assertEquals([5], $collection->skip(4)->toList());
  1789. }
  1790. /**
  1791. * Test skip() with an overflow
  1792. */
  1793. public function testSkipOverflow(): void
  1794. {
  1795. $collection = new Collection([1, 2, 3]);
  1796. $this->assertEquals([], $collection->skip(3)->toArray());
  1797. $this->assertEquals([], $collection->skip(4)->toArray());
  1798. }
  1799. /**
  1800. * Tests the skip() method with a traversable non-iterator
  1801. */
  1802. public function testSkipWithTraversableNonIterator(): void
  1803. {
  1804. $collection = new Collection($this->datePeriod('2017-01-01', '2017-01-07'));
  1805. $result = $collection->skip(3)->toList();
  1806. $expected = [
  1807. new DateTime('2017-01-04'),
  1808. new DateTime('2017-01-05'),
  1809. new DateTime('2017-01-06'),
  1810. ];
  1811. $this->assertEquals($expected, $result);
  1812. }
  1813. /**
  1814. * Tests the first() method with a traversable non-iterator
  1815. */
  1816. public function testFirstWithTraversableNonIterator(): void
  1817. {
  1818. $collection = new Collection($this->datePeriod('2017-01-01', '2017-01-07'));
  1819. $date = $collection->first();
  1820. $this->assertInstanceOf('DateTime', $date);
  1821. $this->assertSame('2017-01-01', $date->format('Y-m-d'));
  1822. }
  1823. /**
  1824. * Tests the last() method
  1825. */
  1826. public function testLast(): void
  1827. {
  1828. $collection = new Collection([1, 2, 3]);
  1829. $this->assertSame(3, $collection->last());
  1830. $collection = $collection->map(function ($e) {
  1831. return $e * 2;
  1832. });
  1833. $this->assertSame(6, $collection->last());
  1834. }
  1835. /**
  1836. * Tests the last() method when on an empty collection
  1837. */
  1838. public function testLastWithEmptyCollection(): void
  1839. {
  1840. $collection = new Collection([]);
  1841. $this->assertNull($collection->last());
  1842. }
  1843. /**
  1844. * Tests the last() method with a countable object
  1845. */
  1846. public function testLastWithCountable(): void
  1847. {
  1848. $collection = new Collection(new ArrayObject([1, 2, 3]));
  1849. $this->assertSame(3, $collection->last());
  1850. }
  1851. /**
  1852. * Tests the last() method with an empty countable object
  1853. */
  1854. public function testLastWithEmptyCountable(): void
  1855. {
  1856. $collection = new Collection(new ArrayObject([]));
  1857. $this->assertNull($collection->last());
  1858. }
  1859. /**
  1860. * Tests the last() method with a non-rewindable iterator
  1861. */
  1862. public function testLastWithNonRewindableIterator(): void
  1863. {
  1864. $iterator = new NoRewindIterator(new ArrayIterator([1, 2, 3]));
  1865. $collection = new Collection($iterator);
  1866. $this->assertSame(3, $collection->last());
  1867. }
  1868. /**
  1869. * Tests the last() method with a traversable non-iterator
  1870. */
  1871. public function testLastWithTraversableNonIterator(): void
  1872. {
  1873. $collection = new Collection($this->datePeriod('2017-01-01', '2017-01-07'));
  1874. $date = $collection->last();
  1875. $this->assertInstanceOf('DateTime', $date);
  1876. $this->assertSame('2017-01-06', $date->format('Y-m-d'));
  1877. }
  1878. /**
  1879. * Tests the takeLast() method
  1880. *
  1881. * @dataProvider simpleProvider
  1882. * @param iterable $data The data to test with.
  1883. * @covers ::takeLast
  1884. */
  1885. public function testLastN($data): void
  1886. {
  1887. $collection = new Collection($data);
  1888. $result = $collection->takeLast(3)->toArray();
  1889. $expected = ['b' => 2, 'c' => 3, 'd' => 4];
  1890. $this->assertEquals($expected, $result);
  1891. }
  1892. /**
  1893. * Tests the takeLast() method with overflow
  1894. *
  1895. * @dataProvider simpleProvider
  1896. * @param iterable $data The data to test with.
  1897. * @covers ::takeLast
  1898. */
  1899. public function testLastNtWithOverflow($data): void
  1900. {
  1901. $collection = new Collection($data);
  1902. $result = $collection->takeLast(10)->toArray();
  1903. $expected = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4];
  1904. $this->assertEquals($expected, $result);
  1905. }
  1906. /**
  1907. * Tests the takeLast() with an odd numbers collection
  1908. *
  1909. * @dataProvider simpleProvider
  1910. * @param iterable $data The data to test with.
  1911. * @covers ::takeLast
  1912. */
  1913. public function testLastNtWithOddData($data): void
  1914. {
  1915. $collection = new Collection($data);
  1916. $result = $collection->take(3)->takeLast(2)->toArray();
  1917. $expected = ['b' => 2, 'c' => 3];
  1918. $this->assertEquals($expected, $result);
  1919. }
  1920. /**
  1921. * Tests the takeLast() with countable collection
  1922. *
  1923. * @covers ::takeLast
  1924. */
  1925. public function testLastNtWithCountable(): void
  1926. {
  1927. $rangeZeroToFive = range(0, 5);
  1928. $collection = new Collection(new CountableIterator($rangeZeroToFive));
  1929. $result = $collection->takeLast(2)->toList();
  1930. $this->assertEquals([4, 5], $result);
  1931. $collection = new Collection(new CountableIterator($rangeZeroToFive));
  1932. $result = $collection->takeLast(1)->toList();
  1933. $this->assertEquals([5], $result);
  1934. }
  1935. /**
  1936. * Tests the takeLast() with countable collection
  1937. *
  1938. * @dataProvider simpleProvider
  1939. * @param iterable $data The data to test with.
  1940. * @covers ::takeLast
  1941. */
  1942. public function testLastNtWithNegative($data): void
  1943. {
  1944. $collection = new Collection($data);
  1945. $this->expectException(InvalidArgumentException::class);
  1946. $this->expectExceptionMessage('The takeLast method requires a number greater than 0.');
  1947. $collection->takeLast(-1)->toArray();
  1948. }
  1949. /**
  1950. * Tests sumOf with no parameters
  1951. */
  1952. public function testSumOfWithIdentity(): void
  1953. {
  1954. $collection = new Collection([1, 2, 3]);
  1955. $this->assertSame(6, $collection->sumOf());
  1956. $collection = new Collection(['a' => 1, 'b' => 4, 'c' => 6]);
  1957. $this->assertSame(11, $collection->sumOf());
  1958. }
  1959. /**
  1960. * Tests using extract with the {*} notation
  1961. */
  1962. public function testUnfoldedExtract(): void
  1963. {
  1964. $items = [
  1965. ['comments' => [['id' => 1], ['id' => 2]]],
  1966. ['comments' => [['id' => 3], ['id' => 4]]],
  1967. ['comments' => [['id' => 7], ['nope' => 8]]],
  1968. ];
  1969. $extracted = (new Collection($items))->extract('comments.{*}.id');
  1970. $this->assertEquals([1, 2, 3, 4, 7, null], $extracted->toArray());
  1971. $items = [
  1972. [
  1973. 'comments' => [
  1974. [
  1975. 'voters' => [['id' => 1], ['id' => 2]],
  1976. ],
  1977. ],
  1978. ],
  1979. [
  1980. 'comments' => [
  1981. [
  1982. 'voters' => [['id' => 3], ['id' => 4]],
  1983. ],
  1984. ],
  1985. ],
  1986. [
  1987. 'comments' => [
  1988. [
  1989. 'voters' => [['id' => 5], ['nope' => 'fail'], ['id' => 6]],
  1990. ],
  1991. ],
  1992. ],
  1993. [
  1994. 'comments' => [
  1995. [
  1996. 'not_voters' => [['id' => 5]],
  1997. ],
  1998. ],
  1999. ],
  2000. ['not_comments' => []],
  2001. ];
  2002. $extracted = (new Collection($items))->extract('comments.{*}.voters.{*}.id');
  2003. $expected = [1, 2, 3, 4, 5, null, 6];
  2004. $this->assertEquals($expected, $extracted->toArray());
  2005. $this->assertEquals($expected, $extracted->toList());
  2006. }
  2007. /**
  2008. * Tests serializing a simple collection
  2009. */
  2010. public function testSerializeSimpleCollection(): void
  2011. {
  2012. $collection = new Collection([1, 2, 3]);
  2013. $serialized = serialize($collection);
  2014. $unserialized = unserialize($serialized);
  2015. $this->assertEquals($collection->toList(), $unserialized->toList());
  2016. $this->assertEquals($collection->toArray(), $unserialized->toArray());
  2017. }
  2018. /**
  2019. * Tests serialization when using append
  2020. */
  2021. public function testSerializeWithAppendIterators(): void
  2022. {
  2023. $collection = new Collection([1, 2, 3]);
  2024. $collection = $collection->append(['a' => 4, 'b' => 5, 'c' => 6]);
  2025. $serialized = serialize($collection);
  2026. $unserialized = unserialize($serialized);
  2027. $this->assertEquals($collection->toList(), $unserialized->toList());
  2028. $this->assertEquals($collection->toArray(), $unserialized->toArray());
  2029. }
  2030. /**
  2031. * Tests serialization when using nested iterators
  2032. */
  2033. public function testSerializeWithNestedIterators(): void
  2034. {
  2035. $collection = new Collection([1, 2, 3]);
  2036. $collection = $collection->map(function ($e) {
  2037. return $e * 3;
  2038. });
  2039. $collection = $collection->groupBy(function ($e) {
  2040. return $e % 2;
  2041. });
  2042. $serialized = serialize($collection);
  2043. $unserialized = unserialize($serialized);
  2044. $this->assertEquals($collection->toList(), $unserialized->toList());
  2045. $this->assertEquals($collection->toArray(), $unserialized->toArray());
  2046. }
  2047. /**
  2048. * Tests serializing a zip() call
  2049. */
  2050. public function testSerializeWithZipIterator(): void
  2051. {
  2052. $collection = new Collection([4, 5]);
  2053. $collection = $collection->zip([1, 2]);
  2054. $serialized = serialize($collection);
  2055. $unserialized = unserialize($serialized);
  2056. $this->assertEquals($collection->toList(), $unserialized->toList());
  2057. }
  2058. /**
  2059. * Provider for some chunk tests
  2060. *
  2061. * @return array
  2062. */
  2063. public static function chunkProvider(): array
  2064. {
  2065. $items = range(1, 10);
  2066. return [
  2067. 'array' => [$items],
  2068. 'iterator' => [self::yieldItems($items)],
  2069. ];
  2070. }
  2071. /**
  2072. * Tests the chunk method with exact chunks
  2073. *
  2074. * @dataProvider chunkProvider
  2075. */
  2076. public function testChunk(iterable $items): void
  2077. {
  2078. $collection = new Collection($items);
  2079. $chunked = $collection->chunk(2)->toList();
  2080. $expected = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]];
  2081. $this->assertEquals($expected, $chunked);
  2082. }
  2083. /**
  2084. * Tests the chunk method with overflowing chunk size
  2085. */
  2086. public function testChunkOverflow(): void
  2087. {
  2088. $collection = new Collection(range(1, 11));
  2089. $chunked = $collection->chunk(2)->toList();
  2090. $expected = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11]];
  2091. $this->assertEquals($expected, $chunked);
  2092. }
  2093. /**
  2094. * Tests the chunk method with non-scalar items
  2095. */
  2096. public function testChunkNested(): void
  2097. {
  2098. $collection = new Collection([1, 2, 3, [4, 5], 6, [7, [8, 9], 10], 11]);
  2099. $chunked = $collection->chunk(2)->toList();
  2100. $expected = [[1, 2], [3, [4, 5]], [6, [7, [8, 9], 10]], [11]];
  2101. $this->assertEquals($expected, $chunked);
  2102. }
  2103. /**
  2104. * Tests the chunkWithKeys method with exact chunks
  2105. */
  2106. public function testChunkWithKeys(): void
  2107. {
  2108. $collection = new Collection(['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6]);
  2109. $chunked = $collection->chunkWithKeys(2)->toList();
  2110. $expected = [['a' => 1, 'b' => 2], ['c' => 3, 'd' => 4], ['e' => 5, 'f' => 6]];
  2111. $this->assertEquals($expected, $chunked);
  2112. }
  2113. /**
  2114. * Tests the chunkWithKeys method with overflowing chunk size
  2115. */
  2116. public function testChunkWithKeysOverflow(): void
  2117. {
  2118. $collection = new Collection(['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6, 'g' => 7]);
  2119. $chunked = $collection->chunkWithKeys(2)->toList();
  2120. $expected = [['a' => 1, 'b' => 2], ['c' => 3, 'd' => 4], ['e' => 5, 'f' => 6], ['g' => 7]];
  2121. $this->assertEquals($expected, $chunked);
  2122. }
  2123. /**
  2124. * Tests the chunkWithKeys method with non-scalar items
  2125. */
  2126. public function testChunkWithKeysNested(): void
  2127. {
  2128. $collection = new Collection(['a' => 1, 'b' => 2, 'c' => 3, 'd' => [4, 5], 'e' => 6, 'f' => [7, [8, 9], 10], 'g' => 11]);
  2129. $chunked = $collection->chunkWithKeys(2)->toList();
  2130. $expected = [['a' => 1, 'b' => 2], ['c' => 3, 'd' => [4, 5]], ['e' => 6, 'f' => [7, [8, 9], 10]], ['g' => 11]];
  2131. $this->assertEquals($expected, $chunked);
  2132. }
  2133. /**
  2134. * Tests the chunkWithKeys method without preserving keys
  2135. */
  2136. public function testChunkWithKeysNoPreserveKeys(): void
  2137. {
  2138. $collection = new Collection(['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6, 'g' => 7]);
  2139. $chunked = $collection->chunkWithKeys(2, false)->toList();
  2140. $expected = [[0 => 1, 1 => 2], [0 => 3, 1 => 4], [0 => 5, 1 => 6], [0 => 7]];
  2141. $this->assertEquals($expected, $chunked);
  2142. }
  2143. /**
  2144. * Tests cartesianProduct
  2145. */
  2146. public function testCartesianProduct(): void
  2147. {
  2148. $collection = new Collection([]);
  2149. $result = $collection->cartesianProduct();
  2150. $expected = [];
  2151. $this->assertEquals($expected, $result->toList());
  2152. $collection = new Collection([['A', 'B', 'C'], [1, 2, 3]]);
  2153. $result = $collection->cartesianProduct();
  2154. $expected = [
  2155. ['A', 1],
  2156. ['A', 2],
  2157. ['A', 3],
  2158. ['B', 1],
  2159. ['B', 2],
  2160. ['B', 3],
  2161. ['C', 1],
  2162. ['C', 2],
  2163. ['C', 3],
  2164. ];
  2165. $this->assertEquals($expected, $result->toList());
  2166. $collection = new Collection([[1, 2, 3], ['A', 'B', 'C'], ['a', 'b', 'c']]);
  2167. $result = $collection->cartesianProduct(function ($value) {
  2168. return [strval($value[0]) . $value[1] . $value[2]];
  2169. }, function ($value) {
  2170. return $value[0] >= 2;
  2171. });
  2172. $expected = [
  2173. ['2Aa'],
  2174. ['2Ab'],
  2175. ['2Ac'],
  2176. ['2Ba'],
  2177. ['2Bb'],
  2178. ['2Bc'],
  2179. ['2Ca'],
  2180. ['2Cb'],
  2181. ['2Cc'],
  2182. ['3Aa'],
  2183. ['3Ab'],
  2184. ['3Ac'],
  2185. ['3Ba'],
  2186. ['3Bb'],
  2187. ['3Bc'],
  2188. ['3Ca'],
  2189. ['3Cb'],
  2190. ['3Cc'],
  2191. ];
  2192. $this->assertEquals($expected, $result->toList());
  2193. $collection = new Collection([['1', '2', '3', '4'], ['A', 'B', 'C'], ['name', 'surname', 'telephone']]);
  2194. $result = $collection->cartesianProduct(function ($value) {
  2195. return [$value[0] => [$value[1] => $value[2]]];
  2196. }, function ($value) {
  2197. return $value[2] !== 'surname';
  2198. });
  2199. $expected = [
  2200. [1 => ['A' => 'name']],
  2201. [1 => ['A' => 'telephone']],
  2202. [1 => ['B' => 'name']],
  2203. [1 => ['B' => 'telephone']],
  2204. [1 => ['C' => 'name']],
  2205. [1 => ['C' => 'telephone']],
  2206. [2 => ['A' => 'name']],
  2207. [2 => ['A' => 'telephone']],
  2208. [2 => ['B' => 'name']],
  2209. [2 => ['B' => 'telephone']],
  2210. [2 => ['C' => 'name']],
  2211. [2 => ['C' => 'telephone']],
  2212. [3 => ['A' => 'name']],
  2213. [3 => ['A' => 'telephone']],
  2214. [3 => ['B' => 'name']],
  2215. [3 => ['B' => 'telephone']],
  2216. [3 => ['C' => 'name']],
  2217. [3 => ['C' => 'telephone']],
  2218. [4 => ['A' => 'name']],
  2219. [4 => ['A' => 'telephone']],
  2220. [4 => ['B' => 'name']],
  2221. [4 => ['B' => 'telephone']],
  2222. [4 => ['C' => 'name']],
  2223. [4 => ['C' => 'telephone']],
  2224. ];
  2225. $this->assertEquals($expected, $result->toList());
  2226. $collection = new Collection([
  2227. [
  2228. 'name1' => 'alex',
  2229. 'name2' => 'kostas',
  2230. 0 => 'leon',
  2231. ],
  2232. [
  2233. 'val1' => 'alex@example.com',
  2234. 24 => 'kostas@example.com',
  2235. 'val2' => 'leon@example.com',
  2236. ],
  2237. ]);
  2238. $result = $collection->cartesianProduct();
  2239. $expected = [
  2240. ['alex', 'alex@example.com'],
  2241. ['alex', 'kostas@example.com'],
  2242. ['alex', 'leon@example.com'],
  2243. ['kostas', 'alex@example.com'],
  2244. ['kostas', 'kostas@example.com'],
  2245. ['kostas', 'leon@example.com'],
  2246. ['leon', 'alex@example.com'],
  2247. ['leon', 'kostas@example.com'],
  2248. ['leon', 'leon@example.com'],
  2249. ];
  2250. $this->assertEquals($expected, $result->toList());
  2251. }
  2252. /**
  2253. * Tests that an exception is thrown if the cartesian product is called with multidimensional arrays
  2254. */
  2255. public function testCartesianProductMultidimensionalArray(): void
  2256. {
  2257. $this->expectException(LogicException::class);
  2258. $collection = new Collection([
  2259. [
  2260. 'names' => [
  2261. 'alex', 'kostas', 'leon',
  2262. ],
  2263. ],
  2264. [
  2265. 'locations' => [
  2266. 'crete', 'london', 'paris',
  2267. ],
  2268. ],
  2269. ]);
  2270. $collection->cartesianProduct();
  2271. }
  2272. public function testTranspose(): void
  2273. {
  2274. $collection = new Collection([
  2275. ['Products', '2012', '2013', '2014'],
  2276. ['Product A', '200', '100', '50'],
  2277. ['Product B', '300', '200', '100'],
  2278. ['Product C', '400', '300', '200'],
  2279. ['Product D', '500', '400', '300'],
  2280. ]);
  2281. $transposed = $collection->transpose();
  2282. $expected = [
  2283. ['Products', 'Product A', 'Product B', 'Product C', 'Product D'],
  2284. ['2012', '200', '300', '400', '500'],
  2285. ['2013', '100', '200', '300', '400'],
  2286. ['2014', '50', '100', '200', '300'],
  2287. ];
  2288. $this->assertEquals($expected, $transposed->toList());
  2289. }
  2290. /**
  2291. * Tests that provided arrays do not have even length
  2292. */
  2293. public function testTransposeUnEvenLengthShouldThrowException(): void
  2294. {
  2295. $this->expectException(LogicException::class);
  2296. $collection = new Collection([
  2297. ['Products', '2012', '2013', '2014'],
  2298. ['Product A', '200', '100', '50'],
  2299. ['Product B', '300'],
  2300. ['Product C', '400', '300'],
  2301. ]);
  2302. $collection->transpose();
  2303. }
  2304. /**
  2305. * Yields all the elements as passed
  2306. *
  2307. * @param iterable $items the elements to be yielded
  2308. * @return \Generator<array>
  2309. */
  2310. protected static function yieldItems(iterable $items): Generator
  2311. {
  2312. foreach ($items as $k => $v) {
  2313. yield $k => $v;
  2314. }
  2315. }
  2316. /**
  2317. * Create a DatePeriod object.
  2318. *
  2319. * @param string $start Start date
  2320. * @param string $end End date
  2321. */
  2322. protected function datePeriod($start, $end): DatePeriod
  2323. {
  2324. return new DatePeriod(new DateTime($start), new DateInterval('P1D'), new DateTime($end));
  2325. }
  2326. /**
  2327. * Tests that elements in a lazy collection are not fetched immediately.
  2328. */
  2329. public function testLazy(): void
  2330. {
  2331. $items = ['a' => 1, 'b' => 2, 'c' => 3];
  2332. $collection = (new Collection($items))->lazy();
  2333. $callable = $this->getMockBuilder(stdClass::class)
  2334. ->addMethods(['__invoke'])
  2335. ->getMock();
  2336. $callable->expects($this->never())->method('__invoke');
  2337. $collection->filter($callable)->filter($callable);
  2338. }
  2339. }