CollectionTest.php 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516
  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. * Tests the sample() method with a traversable non-iterator
  838. *
  839. * @return void
  840. */
  841. public function testSampleWithTraversableNonIterator()
  842. {
  843. $collection = new Collection($this->datePeriod('2017-01-01', '2017-01-07'));
  844. $result = $collection->sample(3)->toList();
  845. $list = [
  846. '2017-01-01',
  847. '2017-01-02',
  848. '2017-01-03',
  849. '2017-01-04',
  850. '2017-01-05',
  851. '2017-01-06',
  852. ];
  853. $this->assertCount(3, $result);
  854. foreach ($result as $date) {
  855. $this->assertContains($date->format('Y-m-d'), $list);
  856. }
  857. }
  858. /**
  859. * Test toArray method
  860. *
  861. * @return void
  862. */
  863. public function testToArray()
  864. {
  865. $data = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4];
  866. $collection = new Collection($data);
  867. $this->assertEquals($data, $collection->toArray());
  868. }
  869. /**
  870. * Test toList method
  871. *
  872. * @dataProvider simpleProvider
  873. * @return void
  874. */
  875. public function testToList($data)
  876. {
  877. $collection = new Collection($data);
  878. $this->assertEquals([1, 2, 3, 4], $collection->toList());
  879. }
  880. /**
  881. * Test json encoding
  882. *
  883. * @return void
  884. */
  885. public function testToJson()
  886. {
  887. $data = [1, 2, 3, 4];
  888. $collection = new Collection($data);
  889. $this->assertEquals(json_encode($data), json_encode($collection));
  890. }
  891. /**
  892. * Tests that only arrays and Traversables are allowed in the constructor
  893. *
  894. * @expectedException \InvalidArgumentException
  895. * @expectedExceptionMessage Only an array or \Traversable is allowed for Collection
  896. * @return void
  897. */
  898. public function testInvalidConstructorArgument()
  899. {
  900. new Collection('Derp');
  901. }
  902. /**
  903. * Tests that issuing a count will throw an exception
  904. *
  905. * @expectedException \BadMethodCallException
  906. * @expectedExceptionMessage Call to undefined method Cake\Collection\Collection::count()
  907. * @return void
  908. */
  909. public function testCollectionCount()
  910. {
  911. $data = [1, 2, 3, 4];
  912. $collection = new Collection($data);
  913. $collection->count();
  914. }
  915. /**
  916. * Tests take method
  917. *
  918. * @return void
  919. */
  920. public function testTake()
  921. {
  922. $data = [1, 2, 3, 4];
  923. $collection = new Collection($data);
  924. $taken = $collection->take(2);
  925. $this->assertEquals([1, 2], $taken->toArray());
  926. $taken = $collection->take(3);
  927. $this->assertEquals([1, 2, 3], $taken->toArray());
  928. $taken = $collection->take(500);
  929. $this->assertEquals([1, 2, 3, 4], $taken->toArray());
  930. $taken = $collection->take(1);
  931. $this->assertEquals([1], $taken->toArray());
  932. $taken = $collection->take();
  933. $this->assertEquals([1], $taken->toArray());
  934. $taken = $collection->take(2, 2);
  935. $this->assertEquals([2 => 3, 3 => 4], $taken->toArray());
  936. }
  937. /**
  938. * Tests the take() method with a traversable non-iterator
  939. *
  940. * @return void
  941. */
  942. public function testTakeWithTraversableNonIterator()
  943. {
  944. $collection = new Collection($this->datePeriod('2017-01-01', '2017-01-07'));
  945. $result = $collection->take(3, 1)->toList();
  946. $expected = [
  947. new \DateTime('2017-01-02'),
  948. new \DateTime('2017-01-03'),
  949. new \DateTime('2017-01-04'),
  950. ];
  951. $this->assertEquals($expected, $result);
  952. }
  953. /**
  954. * Tests match
  955. *
  956. * @return void
  957. */
  958. public function testMatch()
  959. {
  960. $items = [
  961. ['id' => 1, 'name' => 'foo', 'thing' => ['parent_id' => 10]],
  962. ['id' => 2, 'name' => 'bar', 'thing' => ['parent_id' => 11]],
  963. ['id' => 3, 'name' => 'baz', 'thing' => ['parent_id' => 10]],
  964. ];
  965. $collection = new Collection($items);
  966. $matched = $collection->match(['thing.parent_id' => 10, 'name' => 'baz']);
  967. $this->assertEquals([2 => $items[2]], $matched->toArray());
  968. $matched = $collection->match(['thing.parent_id' => 10]);
  969. $this->assertEquals(
  970. [0 => $items[0], 2 => $items[2]],
  971. $matched->toArray()
  972. );
  973. $matched = $collection->match(['thing.parent_id' => 500]);
  974. $this->assertEquals([], $matched->toArray());
  975. $matched = $collection->match(['parent_id' => 10, 'name' => 'baz']);
  976. $this->assertEquals([], $matched->toArray());
  977. }
  978. /**
  979. * Tests firstMatch
  980. *
  981. * @return void
  982. */
  983. public function testFirstMatch()
  984. {
  985. $items = [
  986. ['id' => 1, 'name' => 'foo', 'thing' => ['parent_id' => 10]],
  987. ['id' => 2, 'name' => 'bar', 'thing' => ['parent_id' => 11]],
  988. ['id' => 3, 'name' => 'baz', 'thing' => ['parent_id' => 10]],
  989. ];
  990. $collection = new Collection($items);
  991. $matched = $collection->firstMatch(['thing.parent_id' => 10]);
  992. $this->assertEquals(
  993. ['id' => 1, 'name' => 'foo', 'thing' => ['parent_id' => 10]],
  994. $matched
  995. );
  996. $matched = $collection->firstMatch(['thing.parent_id' => 10, 'name' => 'baz']);
  997. $this->assertEquals(
  998. ['id' => 3, 'name' => 'baz', 'thing' => ['parent_id' => 10]],
  999. $matched
  1000. );
  1001. }
  1002. /**
  1003. * Tests the append method
  1004. *
  1005. * @return void
  1006. */
  1007. public function testAppend()
  1008. {
  1009. $collection = new Collection([1, 2, 3]);
  1010. $combined = $collection->append([4, 5, 6]);
  1011. $this->assertEquals([1, 2, 3, 4, 5, 6], $combined->toArray(false));
  1012. $collection = new Collection(['a' => 1, 'b' => 2]);
  1013. $combined = $collection->append(['c' => 3, 'a' => 4]);
  1014. $this->assertEquals(['a' => 4, 'b' => 2, 'c' => 3], $combined->toArray());
  1015. }
  1016. /**
  1017. * Tests the append method with iterator
  1018. */
  1019. public function testAppendIterator()
  1020. {
  1021. $collection = new Collection([1, 2, 3]);
  1022. $iterator = new ArrayIterator([4, 5, 6]);
  1023. $combined = $collection->append($iterator);
  1024. $this->assertEquals([1, 2, 3, 4, 5, 6], $combined->toList());
  1025. }
  1026. public function testAppendNotCollectionInstance()
  1027. {
  1028. $collection = new TestCollection([1, 2, 3]);
  1029. $combined = $collection->append([4, 5, 6]);
  1030. $this->assertEquals([1, 2, 3, 4, 5, 6], $combined->toList());
  1031. }
  1032. /**
  1033. * Tests that by calling compile internal iteration operations are not done
  1034. * more than once
  1035. *
  1036. * @return void
  1037. */
  1038. public function testCompile()
  1039. {
  1040. $items = ['a' => 1, 'b' => 2, 'c' => 3];
  1041. $collection = new Collection($items);
  1042. $callable = $this->getMockBuilder(\StdClass::class)
  1043. ->setMethods(['__invoke'])
  1044. ->getMock();
  1045. $callable->expects($this->at(0))
  1046. ->method('__invoke')
  1047. ->with(1, 'a')
  1048. ->will($this->returnValue(4));
  1049. $callable->expects($this->at(1))
  1050. ->method('__invoke')
  1051. ->with(2, 'b')
  1052. ->will($this->returnValue(5));
  1053. $callable->expects($this->at(2))
  1054. ->method('__invoke')
  1055. ->with(3, 'c')
  1056. ->will($this->returnValue(6));
  1057. $compiled = $collection->map($callable)->compile();
  1058. $this->assertEquals(['a' => 4, 'b' => 5, 'c' => 6], $compiled->toArray());
  1059. $this->assertEquals(['a' => 4, 'b' => 5, 'c' => 6], $compiled->toArray());
  1060. }
  1061. /**
  1062. * Tests converting a non rewindable iterator into a rewindable one using
  1063. * the buffered method.
  1064. *
  1065. * @return void
  1066. */
  1067. public function testBuffered()
  1068. {
  1069. $items = new NoRewindIterator(new ArrayIterator(['a' => 4, 'b' => 5, 'c' => 6]));
  1070. $buffered = (new Collection($items))->buffered();
  1071. $this->assertEquals(['a' => 4, 'b' => 5, 'c' => 6], $buffered->toArray());
  1072. $this->assertEquals(['a' => 4, 'b' => 5, 'c' => 6], $buffered->toArray());
  1073. }
  1074. /**
  1075. * Tests the combine method
  1076. *
  1077. * @return void
  1078. */
  1079. public function testCombine()
  1080. {
  1081. $items = [
  1082. ['id' => 1, 'name' => 'foo', 'parent' => 'a'],
  1083. ['id' => 2, 'name' => 'bar', 'parent' => 'b'],
  1084. ['id' => 3, 'name' => 'baz', 'parent' => 'a']
  1085. ];
  1086. $collection = (new Collection($items))->combine('id', 'name');
  1087. $expected = [1 => 'foo', 2 => 'bar', 3 => 'baz'];
  1088. $this->assertEquals($expected, $collection->toArray());
  1089. $expected = ['foo' => 1, 'bar' => 2, 'baz' => 3];
  1090. $collection = (new Collection($items))->combine('name', 'id');
  1091. $this->assertEquals($expected, $collection->toArray());
  1092. $collection = (new Collection($items))->combine('id', 'name', 'parent');
  1093. $expected = ['a' => [1 => 'foo', 3 => 'baz'], 'b' => [2 => 'bar']];
  1094. $this->assertEquals($expected, $collection->toArray());
  1095. $expected = [
  1096. '0-1' => ['foo-0-1' => '0-1-foo'],
  1097. '1-2' => ['bar-1-2' => '1-2-bar'],
  1098. '2-3' => ['baz-2-3' => '2-3-baz']
  1099. ];
  1100. $collection = (new Collection($items))->combine(
  1101. function ($value, $key) {
  1102. return $value['name'] . '-' . $key;
  1103. },
  1104. function ($value, $key) {
  1105. return $key . '-' . $value['name'];
  1106. },
  1107. function ($value, $key) {
  1108. return $key . '-' . $value['id'];
  1109. }
  1110. );
  1111. $this->assertEquals($expected, $collection->toArray());
  1112. $collection = (new Collection($items))->combine('id', 'crazy');
  1113. $this->assertEquals([1 => null, 2 => null, 3 => null], $collection->toArray());
  1114. }
  1115. /**
  1116. * Tests the nest method with only one level
  1117. *
  1118. * @return void
  1119. */
  1120. public function testNest()
  1121. {
  1122. $items = [
  1123. ['id' => 1, 'parent_id' => null],
  1124. ['id' => 2, 'parent_id' => 1],
  1125. ['id' => 3, 'parent_id' => 1],
  1126. ['id' => 4, 'parent_id' => 1],
  1127. ['id' => 5, 'parent_id' => 6],
  1128. ['id' => 6, 'parent_id' => null],
  1129. ['id' => 7, 'parent_id' => 1],
  1130. ['id' => 8, 'parent_id' => 6],
  1131. ['id' => 9, 'parent_id' => 6],
  1132. ['id' => 10, 'parent_id' => 6]
  1133. ];
  1134. $collection = (new Collection($items))->nest('id', 'parent_id');
  1135. $expected = [
  1136. [
  1137. 'id' => 1,
  1138. 'parent_id' => null,
  1139. 'children' => [
  1140. ['id' => 2, 'parent_id' => 1, 'children' => []],
  1141. ['id' => 3, 'parent_id' => 1, 'children' => []],
  1142. ['id' => 4, 'parent_id' => 1, 'children' => []],
  1143. ['id' => 7, 'parent_id' => 1, 'children' => []]
  1144. ]
  1145. ],
  1146. [
  1147. 'id' => 6,
  1148. 'parent_id' => null,
  1149. 'children' => [
  1150. ['id' => 5, 'parent_id' => 6, 'children' => []],
  1151. ['id' => 8, 'parent_id' => 6, 'children' => []],
  1152. ['id' => 9, 'parent_id' => 6, 'children' => []],
  1153. ['id' => 10, 'parent_id' => 6, 'children' => []]
  1154. ]
  1155. ]
  1156. ];
  1157. $this->assertEquals($expected, $collection->toArray());
  1158. }
  1159. /**
  1160. * Tests the nest method with alternate nesting key
  1161. *
  1162. * @return void
  1163. */
  1164. public function testNestAlternateNestingKey()
  1165. {
  1166. $items = [
  1167. ['id' => 1, 'parent_id' => null],
  1168. ['id' => 2, 'parent_id' => 1],
  1169. ['id' => 3, 'parent_id' => 1],
  1170. ['id' => 4, 'parent_id' => 1],
  1171. ['id' => 5, 'parent_id' => 6],
  1172. ['id' => 6, 'parent_id' => null],
  1173. ['id' => 7, 'parent_id' => 1],
  1174. ['id' => 8, 'parent_id' => 6],
  1175. ['id' => 9, 'parent_id' => 6],
  1176. ['id' => 10, 'parent_id' => 6]
  1177. ];
  1178. $collection = (new Collection($items))->nest('id', 'parent_id', 'nodes');
  1179. $expected = [
  1180. [
  1181. 'id' => 1,
  1182. 'parent_id' => null,
  1183. 'nodes' => [
  1184. ['id' => 2, 'parent_id' => 1, 'nodes' => []],
  1185. ['id' => 3, 'parent_id' => 1, 'nodes' => []],
  1186. ['id' => 4, 'parent_id' => 1, 'nodes' => []],
  1187. ['id' => 7, 'parent_id' => 1, 'nodes' => []]
  1188. ]
  1189. ],
  1190. [
  1191. 'id' => 6,
  1192. 'parent_id' => null,
  1193. 'nodes' => [
  1194. ['id' => 5, 'parent_id' => 6, 'nodes' => []],
  1195. ['id' => 8, 'parent_id' => 6, 'nodes' => []],
  1196. ['id' => 9, 'parent_id' => 6, 'nodes' => []],
  1197. ['id' => 10, 'parent_id' => 6, 'nodes' => []]
  1198. ]
  1199. ]
  1200. ];
  1201. $this->assertEquals($expected, $collection->toArray());
  1202. }
  1203. /**
  1204. * Tests the nest method with more than one level
  1205. *
  1206. * @return void
  1207. */
  1208. public function testNestMultiLevel()
  1209. {
  1210. $items = [
  1211. ['id' => 1, 'parent_id' => null],
  1212. ['id' => 2, 'parent_id' => 1],
  1213. ['id' => 3, 'parent_id' => 2],
  1214. ['id' => 4, 'parent_id' => 2],
  1215. ['id' => 5, 'parent_id' => 3],
  1216. ['id' => 6, 'parent_id' => null],
  1217. ['id' => 7, 'parent_id' => 3],
  1218. ['id' => 8, 'parent_id' => 4],
  1219. ['id' => 9, 'parent_id' => 6],
  1220. ['id' => 10, 'parent_id' => 6]
  1221. ];
  1222. $collection = (new Collection($items))->nest('id', 'parent_id', 'nodes');
  1223. $expected = [
  1224. [
  1225. 'id' => 1,
  1226. 'parent_id' => null,
  1227. 'nodes' => [
  1228. [
  1229. 'id' => 2,
  1230. 'parent_id' => 1,
  1231. 'nodes' => [
  1232. [
  1233. 'id' => 3,
  1234. 'parent_id' => 2,
  1235. 'nodes' => [
  1236. ['id' => 5, 'parent_id' => 3, 'nodes' => []],
  1237. ['id' => 7, 'parent_id' => 3, 'nodes' => []]
  1238. ]
  1239. ],
  1240. [
  1241. 'id' => 4,
  1242. 'parent_id' => 2,
  1243. 'nodes' => [
  1244. ['id' => 8, 'parent_id' => 4, 'nodes' => []]
  1245. ]
  1246. ]
  1247. ]
  1248. ]
  1249. ]
  1250. ],
  1251. [
  1252. 'id' => 6,
  1253. 'parent_id' => null,
  1254. 'nodes' => [
  1255. ['id' => 9, 'parent_id' => 6, 'nodes' => []],
  1256. ['id' => 10, 'parent_id' => 6, 'nodes' => []]
  1257. ]
  1258. ]
  1259. ];
  1260. $this->assertEquals($expected, $collection->toArray());
  1261. }
  1262. /**
  1263. * Tests the nest method with more than one level
  1264. *
  1265. * @return void
  1266. */
  1267. public function testNestMultiLevelAlternateNestingKey()
  1268. {
  1269. $items = [
  1270. ['id' => 1, 'parent_id' => null],
  1271. ['id' => 2, 'parent_id' => 1],
  1272. ['id' => 3, 'parent_id' => 2],
  1273. ['id' => 4, 'parent_id' => 2],
  1274. ['id' => 5, 'parent_id' => 3],
  1275. ['id' => 6, 'parent_id' => null],
  1276. ['id' => 7, 'parent_id' => 3],
  1277. ['id' => 8, 'parent_id' => 4],
  1278. ['id' => 9, 'parent_id' => 6],
  1279. ['id' => 10, 'parent_id' => 6]
  1280. ];
  1281. $collection = (new Collection($items))->nest('id', 'parent_id');
  1282. $expected = [
  1283. [
  1284. 'id' => 1,
  1285. 'parent_id' => null,
  1286. 'children' => [
  1287. [
  1288. 'id' => 2,
  1289. 'parent_id' => 1,
  1290. 'children' => [
  1291. [
  1292. 'id' => 3,
  1293. 'parent_id' => 2,
  1294. 'children' => [
  1295. ['id' => 5, 'parent_id' => 3, 'children' => []],
  1296. ['id' => 7, 'parent_id' => 3, 'children' => []]
  1297. ]
  1298. ],
  1299. [
  1300. 'id' => 4,
  1301. 'parent_id' => 2,
  1302. 'children' => [
  1303. ['id' => 8, 'parent_id' => 4, 'children' => []]
  1304. ]
  1305. ]
  1306. ]
  1307. ]
  1308. ]
  1309. ],
  1310. [
  1311. 'id' => 6,
  1312. 'parent_id' => null,
  1313. 'children' => [
  1314. ['id' => 9, 'parent_id' => 6, 'children' => []],
  1315. ['id' => 10, 'parent_id' => 6, 'children' => []]
  1316. ]
  1317. ]
  1318. ];
  1319. $this->assertEquals($expected, $collection->toArray());
  1320. }
  1321. /**
  1322. * Tests the nest method with more than one level
  1323. *
  1324. * @return void
  1325. */
  1326. public function testNestObjects()
  1327. {
  1328. $items = [
  1329. new ArrayObject(['id' => 1, 'parent_id' => null]),
  1330. new ArrayObject(['id' => 2, 'parent_id' => 1]),
  1331. new ArrayObject(['id' => 3, 'parent_id' => 2]),
  1332. new ArrayObject(['id' => 4, 'parent_id' => 2]),
  1333. new ArrayObject(['id' => 5, 'parent_id' => 3]),
  1334. new ArrayObject(['id' => 6, 'parent_id' => null]),
  1335. new ArrayObject(['id' => 7, 'parent_id' => 3]),
  1336. new ArrayObject(['id' => 8, 'parent_id' => 4]),
  1337. new ArrayObject(['id' => 9, 'parent_id' => 6]),
  1338. new ArrayObject(['id' => 10, 'parent_id' => 6])
  1339. ];
  1340. $collection = (new Collection($items))->nest('id', 'parent_id');
  1341. $expected = [
  1342. new ArrayObject([
  1343. 'id' => 1,
  1344. 'parent_id' => null,
  1345. 'children' => [
  1346. new ArrayObject([
  1347. 'id' => 2,
  1348. 'parent_id' => 1,
  1349. 'children' => [
  1350. new ArrayObject([
  1351. 'id' => 3,
  1352. 'parent_id' => 2,
  1353. 'children' => [
  1354. new ArrayObject(['id' => 5, 'parent_id' => 3, 'children' => []]),
  1355. new ArrayObject(['id' => 7, 'parent_id' => 3, 'children' => []])
  1356. ]
  1357. ]),
  1358. new ArrayObject([
  1359. 'id' => 4,
  1360. 'parent_id' => 2,
  1361. 'children' => [
  1362. new ArrayObject(['id' => 8, 'parent_id' => 4, 'children' => []])
  1363. ]
  1364. ])
  1365. ]
  1366. ])
  1367. ]
  1368. ]),
  1369. new ArrayObject([
  1370. 'id' => 6,
  1371. 'parent_id' => null,
  1372. 'children' => [
  1373. new ArrayObject(['id' => 9, 'parent_id' => 6, 'children' => []]),
  1374. new ArrayObject(['id' => 10, 'parent_id' => 6, 'children' => []])
  1375. ]
  1376. ])
  1377. ];
  1378. $this->assertEquals($expected, $collection->toArray());
  1379. }
  1380. /**
  1381. * Tests the nest method with more than one level
  1382. *
  1383. * @return void
  1384. */
  1385. public function testNestObjectsAlternateNestingKey()
  1386. {
  1387. $items = [
  1388. new ArrayObject(['id' => 1, 'parent_id' => null]),
  1389. new ArrayObject(['id' => 2, 'parent_id' => 1]),
  1390. new ArrayObject(['id' => 3, 'parent_id' => 2]),
  1391. new ArrayObject(['id' => 4, 'parent_id' => 2]),
  1392. new ArrayObject(['id' => 5, 'parent_id' => 3]),
  1393. new ArrayObject(['id' => 6, 'parent_id' => null]),
  1394. new ArrayObject(['id' => 7, 'parent_id' => 3]),
  1395. new ArrayObject(['id' => 8, 'parent_id' => 4]),
  1396. new ArrayObject(['id' => 9, 'parent_id' => 6]),
  1397. new ArrayObject(['id' => 10, 'parent_id' => 6])
  1398. ];
  1399. $collection = (new Collection($items))->nest('id', 'parent_id', 'nodes');
  1400. $expected = [
  1401. new ArrayObject([
  1402. 'id' => 1,
  1403. 'parent_id' => null,
  1404. 'nodes' => [
  1405. new ArrayObject([
  1406. 'id' => 2,
  1407. 'parent_id' => 1,
  1408. 'nodes' => [
  1409. new ArrayObject([
  1410. 'id' => 3,
  1411. 'parent_id' => 2,
  1412. 'nodes' => [
  1413. new ArrayObject(['id' => 5, 'parent_id' => 3, 'nodes' => []]),
  1414. new ArrayObject(['id' => 7, 'parent_id' => 3, 'nodes' => []])
  1415. ]
  1416. ]),
  1417. new ArrayObject([
  1418. 'id' => 4,
  1419. 'parent_id' => 2,
  1420. 'nodes' => [
  1421. new ArrayObject(['id' => 8, 'parent_id' => 4, 'nodes' => []])
  1422. ]
  1423. ])
  1424. ]
  1425. ])
  1426. ]
  1427. ]),
  1428. new ArrayObject([
  1429. 'id' => 6,
  1430. 'parent_id' => null,
  1431. 'nodes' => [
  1432. new ArrayObject(['id' => 9, 'parent_id' => 6, 'nodes' => []]),
  1433. new ArrayObject(['id' => 10, 'parent_id' => 6, 'nodes' => []])
  1434. ]
  1435. ])
  1436. ];
  1437. $this->assertEquals($expected, $collection->toArray());
  1438. }
  1439. /**
  1440. * Tests insert
  1441. *
  1442. * @return void
  1443. */
  1444. public function testInsert()
  1445. {
  1446. $items = [['a' => 1], ['b' => 2]];
  1447. $collection = new Collection($items);
  1448. $iterator = $collection->insert('c', [3, 4]);
  1449. $this->assertInstanceOf('Cake\Collection\Iterator\InsertIterator', $iterator);
  1450. $this->assertEquals(
  1451. [['a' => 1, 'c' => 3], ['b' => 2, 'c' => 4]],
  1452. iterator_to_array($iterator)
  1453. );
  1454. }
  1455. /**
  1456. * Provider for testing each of the directions for listNested
  1457. *
  1458. * @return void
  1459. */
  1460. public function nestedListProvider()
  1461. {
  1462. return [
  1463. ['desc', [1, 2, 3, 5, 7, 4, 8, 6, 9, 10]],
  1464. ['asc', [5, 7, 3, 8, 4, 2, 1, 9, 10, 6]],
  1465. ['leaves', [5, 7, 8, 9, 10]]
  1466. ];
  1467. }
  1468. /**
  1469. * Tests the listNested method with the default 'children' nesting key
  1470. *
  1471. * @dataProvider nestedListProvider
  1472. * @return void
  1473. */
  1474. public function testListNested($dir, $expected)
  1475. {
  1476. $items = [
  1477. ['id' => 1, 'parent_id' => null],
  1478. ['id' => 2, 'parent_id' => 1],
  1479. ['id' => 3, 'parent_id' => 2],
  1480. ['id' => 4, 'parent_id' => 2],
  1481. ['id' => 5, 'parent_id' => 3],
  1482. ['id' => 6, 'parent_id' => null],
  1483. ['id' => 7, 'parent_id' => 3],
  1484. ['id' => 8, 'parent_id' => 4],
  1485. ['id' => 9, 'parent_id' => 6],
  1486. ['id' => 10, 'parent_id' => 6]
  1487. ];
  1488. $collection = (new Collection($items))->nest('id', 'parent_id')->listNested($dir);
  1489. $this->assertEquals($expected, $collection->extract('id')->toArray(false));
  1490. }
  1491. /**
  1492. * Tests using listNested with a different nesting key
  1493. *
  1494. * @return void
  1495. */
  1496. public function testListNestedCustomKey()
  1497. {
  1498. $items = [
  1499. ['id' => 1, 'stuff' => [['id' => 2, 'stuff' => [['id' => 3]]]]],
  1500. ['id' => 4, 'stuff' => [['id' => 5]]]
  1501. ];
  1502. $collection = (new Collection($items))->listNested('desc', 'stuff');
  1503. $this->assertEquals(range(1, 5), $collection->extract('id')->toArray(false));
  1504. }
  1505. /**
  1506. * Tests flattening the collection using a custom callable function
  1507. *
  1508. * @return void
  1509. */
  1510. public function testListNestedWithCallable()
  1511. {
  1512. $items = [
  1513. ['id' => 1, 'stuff' => [['id' => 2, 'stuff' => [['id' => 3]]]]],
  1514. ['id' => 4, 'stuff' => [['id' => 5]]]
  1515. ];
  1516. $collection = (new Collection($items))->listNested('desc', function ($item) {
  1517. return isset($item['stuff']) ? $item['stuff'] : [];
  1518. });
  1519. $this->assertEquals(range(1, 5), $collection->extract('id')->toArray(false));
  1520. }
  1521. /**
  1522. * Provider for sumOf tests
  1523. *
  1524. * @return array
  1525. */
  1526. public function sumOfProvider()
  1527. {
  1528. $items = [
  1529. ['invoice' => ['total' => 100]],
  1530. ['invoice' => ['total' => 200]]
  1531. ];
  1532. return [
  1533. 'array' => [$items],
  1534. 'iterator' => [$this->yieldItems($items)]
  1535. ];
  1536. }
  1537. /**
  1538. * Tests the sumOf method
  1539. *
  1540. * @dataProvider sumOfProvider
  1541. * @return void
  1542. */
  1543. public function testSumOf($items)
  1544. {
  1545. $this->assertEquals(300, (new Collection($items))->sumOf('invoice.total'));
  1546. }
  1547. /**
  1548. * Tests the sumOf method
  1549. *
  1550. * @dataProvider sumOfProvider
  1551. * @return void
  1552. */
  1553. public function testSumOfCallable($items)
  1554. {
  1555. $sum = (new Collection($items))->sumOf(function ($v) {
  1556. return $v['invoice']['total'] * 2;
  1557. });
  1558. $this->assertEquals(600, $sum);
  1559. }
  1560. /**
  1561. * Tests the stopWhen method with a callable
  1562. *
  1563. * @dataProvider simpleProvider
  1564. * @return void
  1565. */
  1566. public function testStopWhenCallable($items)
  1567. {
  1568. $collection = (new Collection($items))->stopWhen(function ($v) {
  1569. return $v > 3;
  1570. });
  1571. $this->assertEquals(['a' => 1, 'b' => 2, 'c' => 3], $collection->toArray());
  1572. }
  1573. /**
  1574. * Tests the stopWhen method with a matching array
  1575. *
  1576. * @return void
  1577. */
  1578. public function testStopWhenWithArray()
  1579. {
  1580. $items = [
  1581. ['foo' => 'bar'],
  1582. ['foo' => 'baz'],
  1583. ['foo' => 'foo']
  1584. ];
  1585. $collection = (new Collection($items))->stopWhen(['foo' => 'baz']);
  1586. $this->assertEquals([['foo' => 'bar']], $collection->toArray());
  1587. }
  1588. /**
  1589. * Tests the unfold method
  1590. *
  1591. * @return void
  1592. */
  1593. public function testUnfold()
  1594. {
  1595. $items = [
  1596. [1, 2, 3, 4],
  1597. [5, 6],
  1598. [7, 8]
  1599. ];
  1600. $collection = (new Collection($items))->unfold();
  1601. $this->assertEquals(range(1, 8), $collection->toArray(false));
  1602. $items = [
  1603. [1, 2],
  1604. new Collection([3, 4])
  1605. ];
  1606. $collection = (new Collection($items))->unfold();
  1607. $this->assertEquals(range(1, 4), $collection->toArray(false));
  1608. }
  1609. /**
  1610. * Tests the unfold method with empty levels
  1611. *
  1612. * @return void
  1613. */
  1614. public function testUnfoldEmptyLevels()
  1615. {
  1616. $items = [[], [1, 2], []];
  1617. $collection = (new Collection($items))->unfold();
  1618. $this->assertEquals(range(1, 2), $collection->toArray(false));
  1619. $items = [];
  1620. $collection = (new Collection($items))->unfold();
  1621. $this->assertEmpty($collection->toArray(false));
  1622. }
  1623. /**
  1624. * Tests the unfold when passing a callable
  1625. *
  1626. * @return void
  1627. */
  1628. public function testUnfoldWithCallable()
  1629. {
  1630. $items = [1, 2, 3];
  1631. $collection = (new Collection($items))->unfold(function ($item) {
  1632. return range($item, $item * 2);
  1633. });
  1634. $expected = [1, 2, 2, 3, 4, 3, 4, 5, 6];
  1635. $this->assertEquals($expected, $collection->toArray(false));
  1636. }
  1637. /**
  1638. * Tests the through() method
  1639. *
  1640. * @return void
  1641. */
  1642. public function testThrough()
  1643. {
  1644. $items = [1, 2, 3];
  1645. $collection = (new Collection($items))->through(function ($collection) {
  1646. return $collection->append($collection->toList());
  1647. });
  1648. $this->assertEquals([1, 2, 3, 1, 2, 3], $collection->toList());
  1649. }
  1650. /**
  1651. * Tests the through method when it returns an array
  1652. *
  1653. * @return void
  1654. */
  1655. public function testThroughReturnArray()
  1656. {
  1657. $items = [1, 2, 3];
  1658. $collection = (new Collection($items))->through(function ($collection) {
  1659. $list = $collection->toList();
  1660. return array_merge($list, $list);
  1661. });
  1662. $this->assertEquals([1, 2, 3, 1, 2, 3], $collection->toList());
  1663. }
  1664. /**
  1665. * Tests that the sortBy method does not die when something that is not a
  1666. * collection is passed
  1667. *
  1668. * @return void
  1669. */
  1670. public function testComplexSortBy()
  1671. {
  1672. $results = collection([3, 7])
  1673. ->unfold(function ($value) {
  1674. return [
  1675. ['sorting' => $value * 2],
  1676. ['sorting' => $value * 2]
  1677. ];
  1678. })
  1679. ->sortBy('sorting')
  1680. ->extract('sorting')
  1681. ->toList();
  1682. $this->assertEquals([14, 14, 6, 6], $results);
  1683. }
  1684. /**
  1685. * Tests __debugInfo() or debug() usage
  1686. *
  1687. * @return void
  1688. */
  1689. public function testDebug()
  1690. {
  1691. $items = [1, 2, 3];
  1692. $collection = new Collection($items);
  1693. $result = $collection->__debugInfo();
  1694. $expected = [
  1695. 'count' => 3,
  1696. ];
  1697. $this->assertSame($expected, $result);
  1698. // Calling it again will rewind
  1699. $result = $collection->__debugInfo();
  1700. $expected = [
  1701. 'count' => 3,
  1702. ];
  1703. $this->assertSame($expected, $result);
  1704. // Make sure it also works with non rewindable iterators
  1705. $iterator = new NoRewindIterator(new ArrayIterator($items));
  1706. $collection = new Collection($iterator);
  1707. $result = $collection->__debugInfo();
  1708. $expected = [
  1709. 'count' => 3,
  1710. ];
  1711. $this->assertSame($expected, $result);
  1712. // Calling it again will in this case not rewind
  1713. $result = $collection->__debugInfo();
  1714. $expected = [
  1715. 'count' => 0,
  1716. ];
  1717. $this->assertSame($expected, $result);
  1718. }
  1719. /**
  1720. * Tests the isEmpty() method
  1721. *
  1722. * @return void
  1723. */
  1724. public function testIsEmpty()
  1725. {
  1726. $collection = new Collection([1, 2, 3]);
  1727. $this->assertFalse($collection->isEmpty());
  1728. $collection = $collection->map(function () {
  1729. return null;
  1730. });
  1731. $this->assertFalse($collection->isEmpty());
  1732. $collection = $collection->filter();
  1733. $this->assertTrue($collection->isEmpty());
  1734. }
  1735. /**
  1736. * Tests the isEmpty() method does not consume data
  1737. * from buffered iterators.
  1738. *
  1739. * @return void
  1740. */
  1741. public function testIsEmptyDoesNotConsume()
  1742. {
  1743. $array = new \ArrayIterator([1, 2, 3]);
  1744. $inner = new \Cake\Collection\Iterator\BufferedIterator($array);
  1745. $collection = new Collection($inner);
  1746. $this->assertFalse($collection->isEmpty());
  1747. $this->assertCount(3, $collection->toArray());
  1748. }
  1749. /**
  1750. * Tests the zip() method
  1751. *
  1752. * @return void
  1753. */
  1754. public function testZip()
  1755. {
  1756. $collection = new Collection([1, 2]);
  1757. $zipped = $collection->zip([3, 4]);
  1758. $this->assertEquals([[1, 3], [2, 4]], $zipped->toList());
  1759. $collection = new Collection([1, 2]);
  1760. $zipped = $collection->zip([3]);
  1761. $this->assertEquals([[1, 3]], $zipped->toList());
  1762. $collection = new Collection([1, 2]);
  1763. $zipped = $collection->zip([3, 4], [5, 6], [7, 8], [9, 10, 11]);
  1764. $this->assertEquals([
  1765. [1, 3, 5, 7, 9],
  1766. [2, 4, 6, 8, 10]
  1767. ], $zipped->toList());
  1768. }
  1769. /**
  1770. * Tests the zipWith() method
  1771. *
  1772. * @return void
  1773. */
  1774. public function testZipWith()
  1775. {
  1776. $collection = new Collection([1, 2]);
  1777. $zipped = $collection->zipWith([3, 4], function ($a, $b) {
  1778. return $a * $b;
  1779. });
  1780. $this->assertEquals([3, 8], $zipped->toList());
  1781. $zipped = $collection->zipWith([3, 4], [5, 6, 7], function (...$args) {
  1782. return array_sum($args);
  1783. });
  1784. $this->assertEquals([9, 12], $zipped->toList());
  1785. }
  1786. /**
  1787. * Tests the skip() method
  1788. *
  1789. * @return void
  1790. */
  1791. public function testSkip()
  1792. {
  1793. $collection = new Collection([1, 2, 3, 4, 5]);
  1794. $this->assertEquals([3, 4, 5], $collection->skip(2)->toList());
  1795. $this->assertEquals([5], $collection->skip(4)->toList());
  1796. }
  1797. /**
  1798. * Tests the skip() method with a traversable non-iterator
  1799. *
  1800. * @return void
  1801. */
  1802. public function testSkipWithTraversableNonIterator()
  1803. {
  1804. $collection = new Collection($this->datePeriod('2017-01-01', '2017-01-07'));
  1805. $result = $collection->skip(3)->toList();
  1806. $expected = [
  1807. new \DateTime('2017-01-04'),
  1808. new \DateTime('2017-01-05'),
  1809. new \DateTime('2017-01-06'),
  1810. ];
  1811. $this->assertEquals($expected, $result);
  1812. }
  1813. /**
  1814. * Tests the first() method with a traversable non-iterator
  1815. *
  1816. * @return void
  1817. */
  1818. public function testFirstWithTraversableNonIterator()
  1819. {
  1820. $collection = new Collection($this->datePeriod('2017-01-01', '2017-01-07'));
  1821. $date = $collection->first();
  1822. $this->assertInstanceOf('DateTime', $date);
  1823. $this->assertEquals('2017-01-01', $date->format('Y-m-d'));
  1824. }
  1825. /**
  1826. * Tests the last() method
  1827. *
  1828. * @return void
  1829. */
  1830. public function testLast()
  1831. {
  1832. $collection = new Collection([1, 2, 3]);
  1833. $this->assertEquals(3, $collection->last());
  1834. $collection = $collection->map(function ($e) {
  1835. return $e * 2;
  1836. });
  1837. $this->assertEquals(6, $collection->last());
  1838. }
  1839. /**
  1840. * Tests the last() method when on an empty collection
  1841. *
  1842. * @return void
  1843. */
  1844. public function testLastWithEmptyCollection()
  1845. {
  1846. $collection = new Collection([]);
  1847. $this->assertNull($collection->last());
  1848. }
  1849. /**
  1850. * Tests the last() method with a countable object
  1851. *
  1852. * @return void
  1853. */
  1854. public function testLastWithCountable()
  1855. {
  1856. $collection = new Collection(new ArrayObject([1, 2, 3]));
  1857. $this->assertEquals(3, $collection->last());
  1858. }
  1859. /**
  1860. * Tests the last() method with an empty countable object
  1861. *
  1862. * @return void
  1863. */
  1864. public function testLastWithEmptyCountable()
  1865. {
  1866. $collection = new Collection(new ArrayObject([]));
  1867. $this->assertNull($collection->last());
  1868. }
  1869. /**
  1870. * Tests the last() method with a non-rewindable iterator
  1871. *
  1872. * @return void
  1873. */
  1874. public function testLastWithNonRewindableIterator()
  1875. {
  1876. $iterator = new NoRewindIterator(new ArrayIterator([1, 2, 3]));
  1877. $collection = new Collection($iterator);
  1878. $this->assertEquals(3, $collection->last());
  1879. }
  1880. /**
  1881. * Tests the last() method with a traversable non-iterator
  1882. *
  1883. * @return void
  1884. */
  1885. public function testLastWithTraversableNonIterator()
  1886. {
  1887. $collection = new Collection($this->datePeriod('2017-01-01', '2017-01-07'));
  1888. $date = $collection->last();
  1889. $this->assertInstanceOf('DateTime', $date);
  1890. $this->assertEquals('2017-01-06', $date->format('Y-m-d'));
  1891. }
  1892. /**
  1893. * Tests sumOf with no parameters
  1894. *
  1895. * @return void
  1896. */
  1897. public function testSumOfWithIdentity()
  1898. {
  1899. $collection = new Collection([1, 2, 3]);
  1900. $this->assertEquals(6, $collection->sumOf());
  1901. $collection = new Collection(['a' => 1, 'b' => 4, 'c' => 6]);
  1902. $this->assertEquals(11, $collection->sumOf());
  1903. }
  1904. /**
  1905. * Tests using extract with the {*} notation
  1906. *
  1907. * @return void
  1908. */
  1909. public function testUnfoldedExtract()
  1910. {
  1911. $items = [
  1912. ['comments' => [['id' => 1], ['id' => 2]]],
  1913. ['comments' => [['id' => 3], ['id' => 4]]],
  1914. ['comments' => [['id' => 7], ['nope' => 8]]],
  1915. ];
  1916. $extracted = (new Collection($items))->extract('comments.{*}.id');
  1917. $this->assertEquals([1, 2, 3, 4, 7, null], $extracted->toArray());
  1918. $items = [
  1919. [
  1920. 'comments' => [
  1921. [
  1922. 'voters' => [['id' => 1], ['id' => 2]]
  1923. ]
  1924. ]
  1925. ],
  1926. [
  1927. 'comments' => [
  1928. [
  1929. 'voters' => [['id' => 3], ['id' => 4]]
  1930. ]
  1931. ]
  1932. ],
  1933. [
  1934. 'comments' => [
  1935. [
  1936. 'voters' => [['id' => 5], ['nope' => 'fail'], ['id' => 6]]
  1937. ]
  1938. ]
  1939. ],
  1940. [
  1941. 'comments' => [
  1942. [
  1943. 'not_voters' => [['id' => 5]]
  1944. ]
  1945. ]
  1946. ],
  1947. ['not_comments' => []]
  1948. ];
  1949. $extracted = (new Collection($items))->extract('comments.{*}.voters.{*}.id');
  1950. $expected = [1, 2, 3, 4, 5, null, 6];
  1951. $this->assertEquals($expected, $extracted->toArray());
  1952. $this->assertEquals($expected, $extracted->toList());
  1953. }
  1954. /**
  1955. * Tests serializing a simple collection
  1956. *
  1957. * @return void
  1958. */
  1959. public function testSerializeSimpleCollection()
  1960. {
  1961. $collection = new Collection([1, 2, 3]);
  1962. $serialized = serialize($collection);
  1963. $unserialized = unserialize($serialized);
  1964. $this->assertEquals($collection->toList(), $unserialized->toList());
  1965. $this->assertEquals($collection->toArray(), $unserialized->toArray());
  1966. }
  1967. /**
  1968. * Tests serialization when using append
  1969. *
  1970. * @return void
  1971. */
  1972. public function testSerializeWithAppendIterators()
  1973. {
  1974. $collection = new Collection([1, 2, 3]);
  1975. $collection = $collection->append(['a' => 4, 'b' => 5, 'c' => 6]);
  1976. $serialized = serialize($collection);
  1977. $unserialized = unserialize($serialized);
  1978. $this->assertEquals($collection->toList(), $unserialized->toList());
  1979. $this->assertEquals($collection->toArray(), $unserialized->toArray());
  1980. }
  1981. /**
  1982. * Tests serialization when using nested iterators
  1983. *
  1984. * @return void
  1985. */
  1986. public function testSerializeWithNestedIterators()
  1987. {
  1988. $collection = new Collection([1, 2, 3]);
  1989. $collection = $collection->map(function ($e) {
  1990. return $e * 3;
  1991. });
  1992. $collection = $collection->groupBy(function ($e) {
  1993. return $e % 2;
  1994. });
  1995. $serialized = serialize($collection);
  1996. $unserialized = unserialize($serialized);
  1997. $this->assertEquals($collection->toList(), $unserialized->toList());
  1998. $this->assertEquals($collection->toArray(), $unserialized->toArray());
  1999. }
  2000. /**
  2001. * Tests serializing a zip() call
  2002. *
  2003. * @return void
  2004. */
  2005. public function testSerializeWithZipIterator()
  2006. {
  2007. $collection = new Collection([4, 5]);
  2008. $collection = $collection->zip([1, 2]);
  2009. $serialized = serialize($collection);
  2010. $unserialized = unserialize($serialized);
  2011. $this->assertEquals($collection->toList(), $unserialized->toList());
  2012. }
  2013. /**
  2014. * Provider for some chunk tests
  2015. *
  2016. * @return array
  2017. */
  2018. public function chunkProvider()
  2019. {
  2020. $items = range(1, 10);
  2021. return [
  2022. 'array' => [$items],
  2023. 'iterator' => [$this->yieldItems($items)]
  2024. ];
  2025. }
  2026. /**
  2027. * Tests the chunk method with exact chunks
  2028. *
  2029. * @dataProvider chunkProvider
  2030. * @return void
  2031. */
  2032. public function testChunk($items)
  2033. {
  2034. $collection = new Collection($items);
  2035. $chunked = $collection->chunk(2)->toList();
  2036. $expected = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]];
  2037. $this->assertEquals($expected, $chunked);
  2038. }
  2039. /**
  2040. * Tests the chunk method with overflowing chunk size
  2041. *
  2042. * @return void
  2043. */
  2044. public function testChunkOverflow()
  2045. {
  2046. $collection = new Collection(range(1, 11));
  2047. $chunked = $collection->chunk(2)->toList();
  2048. $expected = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11]];
  2049. $this->assertEquals($expected, $chunked);
  2050. }
  2051. /**
  2052. * Tests the chunk method with non-scalar items
  2053. *
  2054. * @return void
  2055. */
  2056. public function testChunkNested()
  2057. {
  2058. $collection = new Collection([1, 2, 3, [4, 5], 6, [7, [8, 9], 10], 11]);
  2059. $chunked = $collection->chunk(2)->toList();
  2060. $expected = [[1, 2], [3, [4, 5]], [6, [7, [8, 9], 10]], [11]];
  2061. $this->assertEquals($expected, $chunked);
  2062. }
  2063. /**
  2064. * Tests the chunkWithKeys method with exact chunks
  2065. *
  2066. * @return void
  2067. */
  2068. public function testChunkWithKeys()
  2069. {
  2070. $collection = new Collection(['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6]);
  2071. $chunked = $collection->chunkWithKeys(2)->toList();
  2072. $expected = [['a' => 1, 'b' => 2], ['c' => 3, 'd' => 4], ['e' => 5, 'f' => 6]];
  2073. $this->assertEquals($expected, $chunked);
  2074. }
  2075. /**
  2076. * Tests the chunkWithKeys method with overflowing chunk size
  2077. *
  2078. * @return void
  2079. */
  2080. public function testChunkWithKeysOverflow()
  2081. {
  2082. $collection = new Collection(['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6, 'g' => 7]);
  2083. $chunked = $collection->chunkWithKeys(2)->toList();
  2084. $expected = [['a' => 1, 'b' => 2], ['c' => 3, 'd' => 4], ['e' => 5, 'f' => 6], ['g' => 7]];
  2085. $this->assertEquals($expected, $chunked);
  2086. }
  2087. /**
  2088. * Tests the chunkWithKeys method with non-scalar items
  2089. *
  2090. * @return void
  2091. */
  2092. public function testChunkWithKeysNested()
  2093. {
  2094. $collection = new Collection(['a' => 1, 'b' => 2, 'c' => 3, 'd' => [4, 5], 'e' => 6, 'f' => [7, [8, 9], 10], 'g' => 11]);
  2095. $chunked = $collection->chunkWithKeys(2)->toList();
  2096. $expected = [['a' => 1, 'b' => 2], ['c' => 3, 'd' => [4, 5]], ['e' => 6, 'f' => [7, [8, 9], 10]], ['g' => 11]];
  2097. $this->assertEquals($expected, $chunked);
  2098. }
  2099. /**
  2100. * Tests the chunkWithKeys method without preserving keys
  2101. *
  2102. * @return void
  2103. */
  2104. public function testChunkWithKeysNoPreserveKeys()
  2105. {
  2106. $collection = new Collection(['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6, 'g' => 7]);
  2107. $chunked = $collection->chunkWithKeys(2, false)->toList();
  2108. $expected = [[0 => 1, 1 => 2], [0 => 3, 1 => 4], [0 => 5, 1 => 6], [0 => 7]];
  2109. $this->assertEquals($expected, $chunked);
  2110. }
  2111. /**
  2112. * Tests cartesianProduct
  2113. *
  2114. * @return void
  2115. */
  2116. public function testCartesianProduct()
  2117. {
  2118. $collection = new Collection([]);
  2119. $result = $collection->cartesianProduct();
  2120. $expected = [];
  2121. $this->assertEquals($expected, $result->toList());
  2122. $collection = new Collection([['A', 'B', 'C'], [1, 2, 3]]);
  2123. $result = $collection->cartesianProduct();
  2124. $expected = [
  2125. ['A', 1],
  2126. ['A', 2],
  2127. ['A', 3],
  2128. ['B', 1],
  2129. ['B', 2],
  2130. ['B', 3],
  2131. ['C', 1],
  2132. ['C', 2],
  2133. ['C', 3],
  2134. ];
  2135. $this->assertEquals($expected, $result->toList());
  2136. $collection = new Collection([[1, 2, 3], ['A', 'B', 'C'], ['a', 'b', 'c']]);
  2137. $result = $collection->cartesianProduct(function ($value) {
  2138. return [strval($value[0]) . $value[1] . $value[2]];
  2139. }, function ($value) {
  2140. return $value[0] >= 2;
  2141. });
  2142. $expected = [
  2143. ['2Aa'],
  2144. ['2Ab'],
  2145. ['2Ac'],
  2146. ['2Ba'],
  2147. ['2Bb'],
  2148. ['2Bc'],
  2149. ['2Ca'],
  2150. ['2Cb'],
  2151. ['2Cc'],
  2152. ['3Aa'],
  2153. ['3Ab'],
  2154. ['3Ac'],
  2155. ['3Ba'],
  2156. ['3Bb'],
  2157. ['3Bc'],
  2158. ['3Ca'],
  2159. ['3Cb'],
  2160. ['3Cc'],
  2161. ];
  2162. $this->assertEquals($expected, $result->toList());
  2163. $collection = new Collection([['1', '2', '3', '4'], ['A', 'B', 'C'], ['name', 'surname', 'telephone']]);
  2164. $result = $collection->cartesianProduct(function ($value) {
  2165. return [$value[0] => [$value[1] => $value[2]]];
  2166. }, function ($value) {
  2167. return $value[2] !== 'surname';
  2168. });
  2169. $expected = [
  2170. [1 => ['A' => 'name']],
  2171. [1 => ['A' => 'telephone']],
  2172. [1 => ['B' => 'name']],
  2173. [1 => ['B' => 'telephone']],
  2174. [1 => ['C' => 'name']],
  2175. [1 => ['C' => 'telephone']],
  2176. [2 => ['A' => 'name']],
  2177. [2 => ['A' => 'telephone']],
  2178. [2 => ['B' => 'name']],
  2179. [2 => ['B' => 'telephone']],
  2180. [2 => ['C' => 'name']],
  2181. [2 => ['C' => 'telephone']],
  2182. [3 => ['A' => 'name']],
  2183. [3 => ['A' => 'telephone']],
  2184. [3 => ['B' => 'name']],
  2185. [3 => ['B' => 'telephone']],
  2186. [3 => ['C' => 'name']],
  2187. [3 => ['C' => 'telephone']],
  2188. [4 => ['A' => 'name']],
  2189. [4 => ['A' => 'telephone']],
  2190. [4 => ['B' => 'name']],
  2191. [4 => ['B' => 'telephone']],
  2192. [4 => ['C' => 'name']],
  2193. [4 => ['C' => 'telephone']],
  2194. ];
  2195. $this->assertEquals($expected, $result->toList());
  2196. $collection = new Collection([
  2197. [
  2198. 'name1' => 'alex',
  2199. 'name2' => 'kostas',
  2200. 0 => 'leon',
  2201. ],
  2202. [
  2203. 'val1' => 'alex@example.com',
  2204. 24 => 'kostas@example.com',
  2205. 'val2' => 'leon@example.com',
  2206. ],
  2207. ]);
  2208. $result = $collection->cartesianProduct();
  2209. $expected = [
  2210. ['alex', 'alex@example.com'],
  2211. ['alex', 'kostas@example.com'],
  2212. ['alex', 'leon@example.com'],
  2213. ['kostas', 'alex@example.com'],
  2214. ['kostas', 'kostas@example.com'],
  2215. ['kostas', 'leon@example.com'],
  2216. ['leon', 'alex@example.com'],
  2217. ['leon', 'kostas@example.com'],
  2218. ['leon', 'leon@example.com'],
  2219. ];
  2220. $this->assertEquals($expected, $result->toList());
  2221. }
  2222. /**
  2223. * Tests that an exception is thrown if the cartesian product is called with multidimensional arrays
  2224. *
  2225. * @expectedException \LogicException
  2226. * @return void
  2227. */
  2228. public function testCartesianProductMultidimensionalArray()
  2229. {
  2230. $collection = new Collection([
  2231. [
  2232. 'names' => [
  2233. 'alex', 'kostas', 'leon'
  2234. ]
  2235. ],
  2236. [
  2237. 'locations' => [
  2238. 'crete', 'london', 'paris'
  2239. ]
  2240. ],
  2241. ]);
  2242. $result = $collection->cartesianProduct();
  2243. }
  2244. public function testTranspose()
  2245. {
  2246. $collection = new Collection([
  2247. ['Products', '2012', '2013', '2014'],
  2248. ['Product A', '200', '100', '50'],
  2249. ['Product B', '300', '200', '100'],
  2250. ['Product C', '400', '300', '200'],
  2251. ['Product D', '500', '400', '300'],
  2252. ]);
  2253. $transposed = $collection->transpose();
  2254. $expected = [
  2255. ['Products', 'Product A', 'Product B', 'Product C', 'Product D'],
  2256. ['2012', '200', '300', '400', '500'],
  2257. ['2013', '100', '200', '300', '400'],
  2258. ['2014', '50', '100', '200', '300'],
  2259. ];
  2260. $this->assertEquals($expected, $transposed->toList());
  2261. }
  2262. /**
  2263. * Tests that provided arrays do not have even length
  2264. *
  2265. * @expectedException \LogicException
  2266. * @return void
  2267. */
  2268. public function testTransposeUnEvenLengthShouldThrowException()
  2269. {
  2270. $collection = new Collection([
  2271. ['Products', '2012', '2013', '2014'],
  2272. ['Product A', '200', '100', '50'],
  2273. ['Product B', '300'],
  2274. ['Product C', '400', '300'],
  2275. ]);
  2276. $collection->transpose();
  2277. }
  2278. /**
  2279. * Yields all the elements as passed
  2280. *
  2281. * @param array $itmes the elements to be yielded
  2282. * @return void
  2283. */
  2284. protected function yieldItems(array $items)
  2285. {
  2286. foreach ($items as $k => $v) {
  2287. yield $k => $v;
  2288. }
  2289. }
  2290. /**
  2291. * Create a DatePeriod object.
  2292. *
  2293. * @param string $start Start date
  2294. * @param string $end End date
  2295. * @return \DatePeriod
  2296. */
  2297. protected function datePeriod($start, $end)
  2298. {
  2299. return new \DatePeriod(new \DateTime($start), new \DateInterval('P1D'), new \DateTime($end));
  2300. }
  2301. }