CollectionTest.php 69 KB

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