CollectionTest.php 79 KB

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