CollectionTest.php 67 KB

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