CollectionTest.php 66 KB

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