CollectionTest.php 75 KB

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