CollectionTest.php 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705
  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 appendItem method
  1046. */
  1047. public function testAppendItem()
  1048. {
  1049. $collection = new Collection([1, 2, 3]);
  1050. $combined = $collection->appendItem(4);
  1051. $this->assertEquals([1, 2, 3, 4], $combined->toArray(false));
  1052. $collection = new Collection(['a' => 1, 'b' => 2]);
  1053. $combined = $collection->appendItem(3, 'c');
  1054. $combined = $combined->appendItem(4, 'a');
  1055. $this->assertEquals(['a' => 4, 'b' => 2, 'c' => 3], $combined->toArray());
  1056. }
  1057. /**
  1058. * Tests the prepend method
  1059. */
  1060. public function testPrepend()
  1061. {
  1062. $collection = new Collection([1, 2, 3]);
  1063. $combined = $collection->prepend(['a']);
  1064. $this->assertEquals(['a', 1, 2, 3], $combined->toList());
  1065. $collection = new Collection(['c' => 3, 'd' => 4]);
  1066. $combined = $collection->prepend(['a' => 1, 'b' => 2]);
  1067. $this->assertEquals(['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4], $combined->toArray());
  1068. }
  1069. /**
  1070. * Tests prependItem method
  1071. */
  1072. public function testPrependItem()
  1073. {
  1074. $collection = new Collection([1, 2, 3]);
  1075. $combined = $collection->prependItem('a');
  1076. $this->assertEquals(['a', 1, 2, 3], $combined->toList());
  1077. $collection = new Collection(['c' => 3, 'd' => 4]);
  1078. $combined = $collection->prependItem(2, 'b');
  1079. $combined = $combined->prependItem(1, 'a');
  1080. $this->assertEquals(['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4], $combined->toArray());
  1081. }
  1082. /**
  1083. * Tests prependItem method
  1084. */
  1085. public function testPrependItemPreserveKeys()
  1086. {
  1087. $collection = new Collection([1, 2, 3]);
  1088. $combined = $collection->prependItem('a');
  1089. $this->assertEquals(['a', 1, 2, 3], $combined->toList());
  1090. $collection = new Collection(['c' => 3, 'd' => 4]);
  1091. $combined = $collection->prependItem(2, 'b');
  1092. $combined = $combined->prependItem(1, 'a');
  1093. $this->assertEquals(['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4], $combined->toArray());
  1094. }
  1095. /**
  1096. * Tests the append method with iterator
  1097. */
  1098. public function testAppendIterator()
  1099. {
  1100. $collection = new Collection([1, 2, 3]);
  1101. $iterator = new ArrayIterator([4, 5, 6]);
  1102. $combined = $collection->append($iterator);
  1103. $this->assertEquals([1, 2, 3, 4, 5, 6], $combined->toList());
  1104. }
  1105. public function testAppendNotCollectionInstance()
  1106. {
  1107. $collection = new TestCollection([1, 2, 3]);
  1108. $combined = $collection->append([4, 5, 6]);
  1109. $this->assertEquals([1, 2, 3, 4, 5, 6], $combined->toList());
  1110. }
  1111. /**
  1112. * Tests that by calling compile internal iteration operations are not done
  1113. * more than once
  1114. *
  1115. * @return void
  1116. */
  1117. public function testCompile()
  1118. {
  1119. $items = ['a' => 1, 'b' => 2, 'c' => 3];
  1120. $collection = new Collection($items);
  1121. $callable = $this->getMockBuilder(\StdClass::class)
  1122. ->setMethods(['__invoke'])
  1123. ->getMock();
  1124. $callable->expects($this->at(0))
  1125. ->method('__invoke')
  1126. ->with(1, 'a')
  1127. ->will($this->returnValue(4));
  1128. $callable->expects($this->at(1))
  1129. ->method('__invoke')
  1130. ->with(2, 'b')
  1131. ->will($this->returnValue(5));
  1132. $callable->expects($this->at(2))
  1133. ->method('__invoke')
  1134. ->with(3, 'c')
  1135. ->will($this->returnValue(6));
  1136. $compiled = $collection->map($callable)->compile();
  1137. $this->assertEquals(['a' => 4, 'b' => 5, 'c' => 6], $compiled->toArray());
  1138. $this->assertEquals(['a' => 4, 'b' => 5, 'c' => 6], $compiled->toArray());
  1139. }
  1140. /**
  1141. * Tests converting a non rewindable iterator into a rewindable one using
  1142. * the buffered method.
  1143. *
  1144. * @return void
  1145. */
  1146. public function testBuffered()
  1147. {
  1148. $items = new NoRewindIterator(new ArrayIterator(['a' => 4, 'b' => 5, 'c' => 6]));
  1149. $buffered = (new Collection($items))->buffered();
  1150. $this->assertEquals(['a' => 4, 'b' => 5, 'c' => 6], $buffered->toArray());
  1151. $this->assertEquals(['a' => 4, 'b' => 5, 'c' => 6], $buffered->toArray());
  1152. }
  1153. /**
  1154. * Tests the combine method
  1155. *
  1156. * @return void
  1157. */
  1158. public function testCombine()
  1159. {
  1160. $items = [
  1161. ['id' => 1, 'name' => 'foo', 'parent' => 'a'],
  1162. ['id' => 2, 'name' => 'bar', 'parent' => 'b'],
  1163. ['id' => 3, 'name' => 'baz', 'parent' => 'a']
  1164. ];
  1165. $collection = (new Collection($items))->combine('id', 'name');
  1166. $expected = [1 => 'foo', 2 => 'bar', 3 => 'baz'];
  1167. $this->assertEquals($expected, $collection->toArray());
  1168. $expected = ['foo' => 1, 'bar' => 2, 'baz' => 3];
  1169. $collection = (new Collection($items))->combine('name', 'id');
  1170. $this->assertEquals($expected, $collection->toArray());
  1171. $collection = (new Collection($items))->combine('id', 'name', 'parent');
  1172. $expected = ['a' => [1 => 'foo', 3 => 'baz'], 'b' => [2 => 'bar']];
  1173. $this->assertEquals($expected, $collection->toArray());
  1174. $expected = [
  1175. '0-1' => ['foo-0-1' => '0-1-foo'],
  1176. '1-2' => ['bar-1-2' => '1-2-bar'],
  1177. '2-3' => ['baz-2-3' => '2-3-baz']
  1178. ];
  1179. $collection = (new Collection($items))->combine(
  1180. function ($value, $key) {
  1181. return $value['name'] . '-' . $key;
  1182. },
  1183. function ($value, $key) {
  1184. return $key . '-' . $value['name'];
  1185. },
  1186. function ($value, $key) {
  1187. return $key . '-' . $value['id'];
  1188. }
  1189. );
  1190. $this->assertEquals($expected, $collection->toArray());
  1191. $collection = (new Collection($items))->combine('id', 'crazy');
  1192. $this->assertEquals([1 => null, 2 => null, 3 => null], $collection->toArray());
  1193. }
  1194. /**
  1195. * Tests the nest method with only one level
  1196. *
  1197. * @return void
  1198. */
  1199. public function testNest()
  1200. {
  1201. $items = [
  1202. ['id' => 1, 'parent_id' => null],
  1203. ['id' => 2, 'parent_id' => 1],
  1204. ['id' => 3, 'parent_id' => 1],
  1205. ['id' => 4, 'parent_id' => 1],
  1206. ['id' => 5, 'parent_id' => 6],
  1207. ['id' => 6, 'parent_id' => null],
  1208. ['id' => 7, 'parent_id' => 1],
  1209. ['id' => 8, 'parent_id' => 6],
  1210. ['id' => 9, 'parent_id' => 6],
  1211. ['id' => 10, 'parent_id' => 6]
  1212. ];
  1213. $collection = (new Collection($items))->nest('id', 'parent_id');
  1214. $expected = [
  1215. [
  1216. 'id' => 1,
  1217. 'parent_id' => null,
  1218. 'children' => [
  1219. ['id' => 2, 'parent_id' => 1, 'children' => []],
  1220. ['id' => 3, 'parent_id' => 1, 'children' => []],
  1221. ['id' => 4, 'parent_id' => 1, 'children' => []],
  1222. ['id' => 7, 'parent_id' => 1, 'children' => []]
  1223. ]
  1224. ],
  1225. [
  1226. 'id' => 6,
  1227. 'parent_id' => null,
  1228. 'children' => [
  1229. ['id' => 5, 'parent_id' => 6, 'children' => []],
  1230. ['id' => 8, 'parent_id' => 6, 'children' => []],
  1231. ['id' => 9, 'parent_id' => 6, 'children' => []],
  1232. ['id' => 10, 'parent_id' => 6, 'children' => []]
  1233. ]
  1234. ]
  1235. ];
  1236. $this->assertEquals($expected, $collection->toArray());
  1237. }
  1238. /**
  1239. * Tests the nest method with alternate nesting key
  1240. *
  1241. * @return void
  1242. */
  1243. public function testNestAlternateNestingKey()
  1244. {
  1245. $items = [
  1246. ['id' => 1, 'parent_id' => null],
  1247. ['id' => 2, 'parent_id' => 1],
  1248. ['id' => 3, 'parent_id' => 1],
  1249. ['id' => 4, 'parent_id' => 1],
  1250. ['id' => 5, 'parent_id' => 6],
  1251. ['id' => 6, 'parent_id' => null],
  1252. ['id' => 7, 'parent_id' => 1],
  1253. ['id' => 8, 'parent_id' => 6],
  1254. ['id' => 9, 'parent_id' => 6],
  1255. ['id' => 10, 'parent_id' => 6]
  1256. ];
  1257. $collection = (new Collection($items))->nest('id', 'parent_id', 'nodes');
  1258. $expected = [
  1259. [
  1260. 'id' => 1,
  1261. 'parent_id' => null,
  1262. 'nodes' => [
  1263. ['id' => 2, 'parent_id' => 1, 'nodes' => []],
  1264. ['id' => 3, 'parent_id' => 1, 'nodes' => []],
  1265. ['id' => 4, 'parent_id' => 1, 'nodes' => []],
  1266. ['id' => 7, 'parent_id' => 1, 'nodes' => []]
  1267. ]
  1268. ],
  1269. [
  1270. 'id' => 6,
  1271. 'parent_id' => null,
  1272. 'nodes' => [
  1273. ['id' => 5, 'parent_id' => 6, 'nodes' => []],
  1274. ['id' => 8, 'parent_id' => 6, 'nodes' => []],
  1275. ['id' => 9, 'parent_id' => 6, 'nodes' => []],
  1276. ['id' => 10, 'parent_id' => 6, 'nodes' => []]
  1277. ]
  1278. ]
  1279. ];
  1280. $this->assertEquals($expected, $collection->toArray());
  1281. }
  1282. /**
  1283. * Tests the nest method with more than one level
  1284. *
  1285. * @return void
  1286. */
  1287. public function testNestMultiLevel()
  1288. {
  1289. $items = [
  1290. ['id' => 1, 'parent_id' => null],
  1291. ['id' => 2, 'parent_id' => 1],
  1292. ['id' => 3, 'parent_id' => 2],
  1293. ['id' => 4, 'parent_id' => 2],
  1294. ['id' => 5, 'parent_id' => 3],
  1295. ['id' => 6, 'parent_id' => null],
  1296. ['id' => 7, 'parent_id' => 3],
  1297. ['id' => 8, 'parent_id' => 4],
  1298. ['id' => 9, 'parent_id' => 6],
  1299. ['id' => 10, 'parent_id' => 6]
  1300. ];
  1301. $collection = (new Collection($items))->nest('id', 'parent_id', 'nodes');
  1302. $expected = [
  1303. [
  1304. 'id' => 1,
  1305. 'parent_id' => null,
  1306. 'nodes' => [
  1307. [
  1308. 'id' => 2,
  1309. 'parent_id' => 1,
  1310. 'nodes' => [
  1311. [
  1312. 'id' => 3,
  1313. 'parent_id' => 2,
  1314. 'nodes' => [
  1315. ['id' => 5, 'parent_id' => 3, 'nodes' => []],
  1316. ['id' => 7, 'parent_id' => 3, 'nodes' => []]
  1317. ]
  1318. ],
  1319. [
  1320. 'id' => 4,
  1321. 'parent_id' => 2,
  1322. 'nodes' => [
  1323. ['id' => 8, 'parent_id' => 4, 'nodes' => []]
  1324. ]
  1325. ]
  1326. ]
  1327. ]
  1328. ]
  1329. ],
  1330. [
  1331. 'id' => 6,
  1332. 'parent_id' => null,
  1333. 'nodes' => [
  1334. ['id' => 9, 'parent_id' => 6, 'nodes' => []],
  1335. ['id' => 10, 'parent_id' => 6, 'nodes' => []]
  1336. ]
  1337. ]
  1338. ];
  1339. $this->assertEquals($expected, $collection->toArray());
  1340. }
  1341. /**
  1342. * Tests the nest method with more than one level
  1343. *
  1344. * @return void
  1345. */
  1346. public function testNestMultiLevelAlternateNestingKey()
  1347. {
  1348. $items = [
  1349. ['id' => 1, 'parent_id' => null],
  1350. ['id' => 2, 'parent_id' => 1],
  1351. ['id' => 3, 'parent_id' => 2],
  1352. ['id' => 4, 'parent_id' => 2],
  1353. ['id' => 5, 'parent_id' => 3],
  1354. ['id' => 6, 'parent_id' => null],
  1355. ['id' => 7, 'parent_id' => 3],
  1356. ['id' => 8, 'parent_id' => 4],
  1357. ['id' => 9, 'parent_id' => 6],
  1358. ['id' => 10, 'parent_id' => 6]
  1359. ];
  1360. $collection = (new Collection($items))->nest('id', 'parent_id');
  1361. $expected = [
  1362. [
  1363. 'id' => 1,
  1364. 'parent_id' => null,
  1365. 'children' => [
  1366. [
  1367. 'id' => 2,
  1368. 'parent_id' => 1,
  1369. 'children' => [
  1370. [
  1371. 'id' => 3,
  1372. 'parent_id' => 2,
  1373. 'children' => [
  1374. ['id' => 5, 'parent_id' => 3, 'children' => []],
  1375. ['id' => 7, 'parent_id' => 3, 'children' => []]
  1376. ]
  1377. ],
  1378. [
  1379. 'id' => 4,
  1380. 'parent_id' => 2,
  1381. 'children' => [
  1382. ['id' => 8, 'parent_id' => 4, 'children' => []]
  1383. ]
  1384. ]
  1385. ]
  1386. ]
  1387. ]
  1388. ],
  1389. [
  1390. 'id' => 6,
  1391. 'parent_id' => null,
  1392. 'children' => [
  1393. ['id' => 9, 'parent_id' => 6, 'children' => []],
  1394. ['id' => 10, 'parent_id' => 6, 'children' => []]
  1395. ]
  1396. ]
  1397. ];
  1398. $this->assertEquals($expected, $collection->toArray());
  1399. }
  1400. /**
  1401. * Tests the nest method with more than one level
  1402. *
  1403. * @return void
  1404. */
  1405. public function testNestObjects()
  1406. {
  1407. $items = [
  1408. new ArrayObject(['id' => 1, 'parent_id' => null]),
  1409. new ArrayObject(['id' => 2, 'parent_id' => 1]),
  1410. new ArrayObject(['id' => 3, 'parent_id' => 2]),
  1411. new ArrayObject(['id' => 4, 'parent_id' => 2]),
  1412. new ArrayObject(['id' => 5, 'parent_id' => 3]),
  1413. new ArrayObject(['id' => 6, 'parent_id' => null]),
  1414. new ArrayObject(['id' => 7, 'parent_id' => 3]),
  1415. new ArrayObject(['id' => 8, 'parent_id' => 4]),
  1416. new ArrayObject(['id' => 9, 'parent_id' => 6]),
  1417. new ArrayObject(['id' => 10, 'parent_id' => 6])
  1418. ];
  1419. $collection = (new Collection($items))->nest('id', 'parent_id');
  1420. $expected = [
  1421. new ArrayObject([
  1422. 'id' => 1,
  1423. 'parent_id' => null,
  1424. 'children' => [
  1425. new ArrayObject([
  1426. 'id' => 2,
  1427. 'parent_id' => 1,
  1428. 'children' => [
  1429. new ArrayObject([
  1430. 'id' => 3,
  1431. 'parent_id' => 2,
  1432. 'children' => [
  1433. new ArrayObject(['id' => 5, 'parent_id' => 3, 'children' => []]),
  1434. new ArrayObject(['id' => 7, 'parent_id' => 3, 'children' => []])
  1435. ]
  1436. ]),
  1437. new ArrayObject([
  1438. 'id' => 4,
  1439. 'parent_id' => 2,
  1440. 'children' => [
  1441. new ArrayObject(['id' => 8, 'parent_id' => 4, 'children' => []])
  1442. ]
  1443. ])
  1444. ]
  1445. ])
  1446. ]
  1447. ]),
  1448. new ArrayObject([
  1449. 'id' => 6,
  1450. 'parent_id' => null,
  1451. 'children' => [
  1452. new ArrayObject(['id' => 9, 'parent_id' => 6, 'children' => []]),
  1453. new ArrayObject(['id' => 10, 'parent_id' => 6, 'children' => []])
  1454. ]
  1455. ])
  1456. ];
  1457. $this->assertEquals($expected, $collection->toArray());
  1458. }
  1459. /**
  1460. * Tests the nest method with more than one level
  1461. *
  1462. * @return void
  1463. */
  1464. public function testNestObjectsAlternateNestingKey()
  1465. {
  1466. $items = [
  1467. new ArrayObject(['id' => 1, 'parent_id' => null]),
  1468. new ArrayObject(['id' => 2, 'parent_id' => 1]),
  1469. new ArrayObject(['id' => 3, 'parent_id' => 2]),
  1470. new ArrayObject(['id' => 4, 'parent_id' => 2]),
  1471. new ArrayObject(['id' => 5, 'parent_id' => 3]),
  1472. new ArrayObject(['id' => 6, 'parent_id' => null]),
  1473. new ArrayObject(['id' => 7, 'parent_id' => 3]),
  1474. new ArrayObject(['id' => 8, 'parent_id' => 4]),
  1475. new ArrayObject(['id' => 9, 'parent_id' => 6]),
  1476. new ArrayObject(['id' => 10, 'parent_id' => 6])
  1477. ];
  1478. $collection = (new Collection($items))->nest('id', 'parent_id', 'nodes');
  1479. $expected = [
  1480. new ArrayObject([
  1481. 'id' => 1,
  1482. 'parent_id' => null,
  1483. 'nodes' => [
  1484. new ArrayObject([
  1485. 'id' => 2,
  1486. 'parent_id' => 1,
  1487. 'nodes' => [
  1488. new ArrayObject([
  1489. 'id' => 3,
  1490. 'parent_id' => 2,
  1491. 'nodes' => [
  1492. new ArrayObject(['id' => 5, 'parent_id' => 3, 'nodes' => []]),
  1493. new ArrayObject(['id' => 7, 'parent_id' => 3, 'nodes' => []])
  1494. ]
  1495. ]),
  1496. new ArrayObject([
  1497. 'id' => 4,
  1498. 'parent_id' => 2,
  1499. 'nodes' => [
  1500. new ArrayObject(['id' => 8, 'parent_id' => 4, 'nodes' => []])
  1501. ]
  1502. ])
  1503. ]
  1504. ])
  1505. ]
  1506. ]),
  1507. new ArrayObject([
  1508. 'id' => 6,
  1509. 'parent_id' => null,
  1510. 'nodes' => [
  1511. new ArrayObject(['id' => 9, 'parent_id' => 6, 'nodes' => []]),
  1512. new ArrayObject(['id' => 10, 'parent_id' => 6, 'nodes' => []])
  1513. ]
  1514. ])
  1515. ];
  1516. $this->assertEquals($expected, $collection->toArray());
  1517. }
  1518. /**
  1519. * Tests insert
  1520. *
  1521. * @return void
  1522. */
  1523. public function testInsert()
  1524. {
  1525. $items = [['a' => 1], ['b' => 2]];
  1526. $collection = new Collection($items);
  1527. $iterator = $collection->insert('c', [3, 4]);
  1528. $this->assertInstanceOf('Cake\Collection\Iterator\InsertIterator', $iterator);
  1529. $this->assertEquals(
  1530. [['a' => 1, 'c' => 3], ['b' => 2, 'c' => 4]],
  1531. iterator_to_array($iterator)
  1532. );
  1533. }
  1534. /**
  1535. * Provider for testing each of the directions for listNested
  1536. *
  1537. * @return array
  1538. */
  1539. public function nestedListProvider()
  1540. {
  1541. return [
  1542. ['desc', [1, 2, 3, 5, 7, 4, 8, 6, 9, 10]],
  1543. ['asc', [5, 7, 3, 8, 4, 2, 1, 9, 10, 6]],
  1544. ['leaves', [5, 7, 8, 9, 10]]
  1545. ];
  1546. }
  1547. /**
  1548. * Tests the listNested method with the default 'children' nesting key
  1549. *
  1550. * @dataProvider nestedListProvider
  1551. * @return void
  1552. */
  1553. public function testListNested($dir, $expected)
  1554. {
  1555. $items = [
  1556. ['id' => 1, 'parent_id' => null],
  1557. ['id' => 2, 'parent_id' => 1],
  1558. ['id' => 3, 'parent_id' => 2],
  1559. ['id' => 4, 'parent_id' => 2],
  1560. ['id' => 5, 'parent_id' => 3],
  1561. ['id' => 6, 'parent_id' => null],
  1562. ['id' => 7, 'parent_id' => 3],
  1563. ['id' => 8, 'parent_id' => 4],
  1564. ['id' => 9, 'parent_id' => 6],
  1565. ['id' => 10, 'parent_id' => 6]
  1566. ];
  1567. $collection = (new Collection($items))->nest('id', 'parent_id')->listNested($dir);
  1568. $this->assertEquals($expected, $collection->extract('id')->toArray(false));
  1569. }
  1570. /**
  1571. * Tests using listNested with a different nesting key
  1572. *
  1573. * @return void
  1574. */
  1575. public function testListNestedCustomKey()
  1576. {
  1577. $items = [
  1578. ['id' => 1, 'stuff' => [['id' => 2, 'stuff' => [['id' => 3]]]]],
  1579. ['id' => 4, 'stuff' => [['id' => 5]]]
  1580. ];
  1581. $collection = (new Collection($items))->listNested('desc', 'stuff');
  1582. $this->assertEquals(range(1, 5), $collection->extract('id')->toArray(false));
  1583. }
  1584. /**
  1585. * Tests flattening the collection using a custom callable function
  1586. *
  1587. * @return void
  1588. */
  1589. public function testListNestedWithCallable()
  1590. {
  1591. $items = [
  1592. ['id' => 1, 'stuff' => [['id' => 2, 'stuff' => [['id' => 3]]]]],
  1593. ['id' => 4, 'stuff' => [['id' => 5]]]
  1594. ];
  1595. $collection = (new Collection($items))->listNested('desc', function ($item) {
  1596. return isset($item['stuff']) ? $item['stuff'] : [];
  1597. });
  1598. $this->assertEquals(range(1, 5), $collection->extract('id')->toArray(false));
  1599. }
  1600. /**
  1601. * Provider for sumOf tests
  1602. *
  1603. * @return array
  1604. */
  1605. public function sumOfProvider()
  1606. {
  1607. $items = [
  1608. ['invoice' => ['total' => 100]],
  1609. ['invoice' => ['total' => 200]]
  1610. ];
  1611. return [
  1612. 'array' => [$items],
  1613. 'iterator' => [$this->yieldItems($items)]
  1614. ];
  1615. }
  1616. /**
  1617. * Tests the sumOf method
  1618. *
  1619. * @dataProvider sumOfProvider
  1620. * @return void
  1621. */
  1622. public function testSumOf($items)
  1623. {
  1624. $this->assertEquals(300, (new Collection($items))->sumOf('invoice.total'));
  1625. }
  1626. /**
  1627. * Tests the sumOf method
  1628. *
  1629. * @dataProvider sumOfProvider
  1630. * @return void
  1631. */
  1632. public function testSumOfCallable($items)
  1633. {
  1634. $sum = (new Collection($items))->sumOf(function ($v) {
  1635. return $v['invoice']['total'] * 2;
  1636. });
  1637. $this->assertEquals(600, $sum);
  1638. }
  1639. /**
  1640. * Tests the stopWhen method with a callable
  1641. *
  1642. * @dataProvider simpleProvider
  1643. * @return void
  1644. */
  1645. public function testStopWhenCallable($items)
  1646. {
  1647. $collection = (new Collection($items))->stopWhen(function ($v) {
  1648. return $v > 3;
  1649. });
  1650. $this->assertEquals(['a' => 1, 'b' => 2, 'c' => 3], $collection->toArray());
  1651. }
  1652. /**
  1653. * Tests the stopWhen method with a matching array
  1654. *
  1655. * @return void
  1656. */
  1657. public function testStopWhenWithArray()
  1658. {
  1659. $items = [
  1660. ['foo' => 'bar'],
  1661. ['foo' => 'baz'],
  1662. ['foo' => 'foo']
  1663. ];
  1664. $collection = (new Collection($items))->stopWhen(['foo' => 'baz']);
  1665. $this->assertEquals([['foo' => 'bar']], $collection->toArray());
  1666. }
  1667. /**
  1668. * Tests the unfold method
  1669. *
  1670. * @return void
  1671. */
  1672. public function testUnfold()
  1673. {
  1674. $items = [
  1675. [1, 2, 3, 4],
  1676. [5, 6],
  1677. [7, 8]
  1678. ];
  1679. $collection = (new Collection($items))->unfold();
  1680. $this->assertEquals(range(1, 8), $collection->toArray(false));
  1681. $items = [
  1682. [1, 2],
  1683. new Collection([3, 4])
  1684. ];
  1685. $collection = (new Collection($items))->unfold();
  1686. $this->assertEquals(range(1, 4), $collection->toArray(false));
  1687. }
  1688. /**
  1689. * Tests the unfold method with empty levels
  1690. *
  1691. * @return void
  1692. */
  1693. public function testUnfoldEmptyLevels()
  1694. {
  1695. $items = [[], [1, 2], []];
  1696. $collection = (new Collection($items))->unfold();
  1697. $this->assertEquals(range(1, 2), $collection->toArray(false));
  1698. $items = [];
  1699. $collection = (new Collection($items))->unfold();
  1700. $this->assertEmpty($collection->toArray(false));
  1701. }
  1702. /**
  1703. * Tests the unfold when passing a callable
  1704. *
  1705. * @return void
  1706. */
  1707. public function testUnfoldWithCallable()
  1708. {
  1709. $items = [1, 2, 3];
  1710. $collection = (new Collection($items))->unfold(function ($item) {
  1711. return range($item, $item * 2);
  1712. });
  1713. $expected = [1, 2, 2, 3, 4, 3, 4, 5, 6];
  1714. $this->assertEquals($expected, $collection->toArray(false));
  1715. }
  1716. /**
  1717. * Tests the through() method
  1718. *
  1719. * @return void
  1720. */
  1721. public function testThrough()
  1722. {
  1723. $items = [1, 2, 3];
  1724. $collection = (new Collection($items))->through(function ($collection) {
  1725. return $collection->append($collection->toList());
  1726. });
  1727. $this->assertEquals([1, 2, 3, 1, 2, 3], $collection->toList());
  1728. }
  1729. /**
  1730. * Tests the through method when it returns an array
  1731. *
  1732. * @return void
  1733. */
  1734. public function testThroughReturnArray()
  1735. {
  1736. $items = [1, 2, 3];
  1737. $collection = (new Collection($items))->through(function ($collection) {
  1738. $list = $collection->toList();
  1739. return array_merge($list, $list);
  1740. });
  1741. $this->assertEquals([1, 2, 3, 1, 2, 3], $collection->toList());
  1742. }
  1743. /**
  1744. * Tests that the sortBy method does not die when something that is not a
  1745. * collection is passed
  1746. *
  1747. * @return void
  1748. */
  1749. public function testComplexSortBy()
  1750. {
  1751. $results = collection([3, 7])
  1752. ->unfold(function ($value) {
  1753. return [
  1754. ['sorting' => $value * 2],
  1755. ['sorting' => $value * 2]
  1756. ];
  1757. })
  1758. ->sortBy('sorting')
  1759. ->extract('sorting')
  1760. ->toList();
  1761. $this->assertEquals([14, 14, 6, 6], $results);
  1762. }
  1763. /**
  1764. * Tests __debugInfo() or debug() usage
  1765. *
  1766. * @return void
  1767. */
  1768. public function testDebug()
  1769. {
  1770. $items = [1, 2, 3];
  1771. $collection = new Collection($items);
  1772. $result = $collection->__debugInfo();
  1773. $expected = [
  1774. 'count' => 3,
  1775. ];
  1776. $this->assertSame($expected, $result);
  1777. // Calling it again will rewind
  1778. $result = $collection->__debugInfo();
  1779. $expected = [
  1780. 'count' => 3,
  1781. ];
  1782. $this->assertSame($expected, $result);
  1783. // Make sure it also works with non rewindable iterators
  1784. $iterator = new NoRewindIterator(new ArrayIterator($items));
  1785. $collection = new Collection($iterator);
  1786. $result = $collection->__debugInfo();
  1787. $expected = [
  1788. 'count' => 3,
  1789. ];
  1790. $this->assertSame($expected, $result);
  1791. // Calling it again will in this case not rewind
  1792. $result = $collection->__debugInfo();
  1793. $expected = [
  1794. 'count' => 0,
  1795. ];
  1796. $this->assertSame($expected, $result);
  1797. }
  1798. /**
  1799. * Tests the isEmpty() method
  1800. *
  1801. * @return void
  1802. */
  1803. public function testIsEmpty()
  1804. {
  1805. $collection = new Collection([1, 2, 3]);
  1806. $this->assertFalse($collection->isEmpty());
  1807. $collection = $collection->map(function () {
  1808. return null;
  1809. });
  1810. $this->assertFalse($collection->isEmpty());
  1811. $collection = $collection->filter();
  1812. $this->assertTrue($collection->isEmpty());
  1813. }
  1814. /**
  1815. * Tests the isEmpty() method does not consume data
  1816. * from buffered iterators.
  1817. *
  1818. * @return void
  1819. */
  1820. public function testIsEmptyDoesNotConsume()
  1821. {
  1822. $array = new \ArrayIterator([1, 2, 3]);
  1823. $inner = new \Cake\Collection\Iterator\BufferedIterator($array);
  1824. $collection = new Collection($inner);
  1825. $this->assertFalse($collection->isEmpty());
  1826. $this->assertCount(3, $collection->toArray());
  1827. }
  1828. /**
  1829. * Tests the zip() method
  1830. *
  1831. * @return void
  1832. */
  1833. public function testZip()
  1834. {
  1835. $collection = new Collection([1, 2]);
  1836. $zipped = $collection->zip([3, 4]);
  1837. $this->assertEquals([[1, 3], [2, 4]], $zipped->toList());
  1838. $collection = new Collection([1, 2]);
  1839. $zipped = $collection->zip([3]);
  1840. $this->assertEquals([[1, 3]], $zipped->toList());
  1841. $collection = new Collection([1, 2]);
  1842. $zipped = $collection->zip([3, 4], [5, 6], [7, 8], [9, 10, 11]);
  1843. $this->assertEquals([
  1844. [1, 3, 5, 7, 9],
  1845. [2, 4, 6, 8, 10]
  1846. ], $zipped->toList());
  1847. }
  1848. /**
  1849. * Tests the zipWith() method
  1850. *
  1851. * @return void
  1852. */
  1853. public function testZipWith()
  1854. {
  1855. $collection = new Collection([1, 2]);
  1856. $zipped = $collection->zipWith([3, 4], function ($a, $b) {
  1857. return $a * $b;
  1858. });
  1859. $this->assertEquals([3, 8], $zipped->toList());
  1860. $zipped = $collection->zipWith([3, 4], [5, 6, 7], function (...$args) {
  1861. return array_sum($args);
  1862. });
  1863. $this->assertEquals([9, 12], $zipped->toList());
  1864. }
  1865. /**
  1866. * Tests the skip() method
  1867. *
  1868. * @return void
  1869. */
  1870. public function testSkip()
  1871. {
  1872. $collection = new Collection([1, 2, 3, 4, 5]);
  1873. $this->assertEquals([3, 4, 5], $collection->skip(2)->toList());
  1874. $this->assertEquals([5], $collection->skip(4)->toList());
  1875. }
  1876. /**
  1877. * Tests the skip() method with a traversable non-iterator
  1878. *
  1879. * @return void
  1880. */
  1881. public function testSkipWithTraversableNonIterator()
  1882. {
  1883. $collection = new Collection($this->datePeriod('2017-01-01', '2017-01-07'));
  1884. $result = $collection->skip(3)->toList();
  1885. $expected = [
  1886. new \DateTime('2017-01-04'),
  1887. new \DateTime('2017-01-05'),
  1888. new \DateTime('2017-01-06'),
  1889. ];
  1890. $this->assertEquals($expected, $result);
  1891. }
  1892. /**
  1893. * Tests the first() method with a traversable non-iterator
  1894. *
  1895. * @return void
  1896. */
  1897. public function testFirstWithTraversableNonIterator()
  1898. {
  1899. $collection = new Collection($this->datePeriod('2017-01-01', '2017-01-07'));
  1900. $date = $collection->first();
  1901. $this->assertInstanceOf('DateTime', $date);
  1902. $this->assertEquals('2017-01-01', $date->format('Y-m-d'));
  1903. }
  1904. /**
  1905. * Tests the last() method
  1906. *
  1907. * @return void
  1908. */
  1909. public function testLast()
  1910. {
  1911. $collection = new Collection([1, 2, 3]);
  1912. $this->assertEquals(3, $collection->last());
  1913. $collection = $collection->map(function ($e) {
  1914. return $e * 2;
  1915. });
  1916. $this->assertEquals(6, $collection->last());
  1917. }
  1918. /**
  1919. * Tests the last() method when on an empty collection
  1920. *
  1921. * @return void
  1922. */
  1923. public function testLastWithEmptyCollection()
  1924. {
  1925. $collection = new Collection([]);
  1926. $this->assertNull($collection->last());
  1927. }
  1928. /**
  1929. * Tests the last() method with a countable object
  1930. *
  1931. * @return void
  1932. */
  1933. public function testLastWithCountable()
  1934. {
  1935. $collection = new Collection(new ArrayObject([1, 2, 3]));
  1936. $this->assertEquals(3, $collection->last());
  1937. }
  1938. /**
  1939. * Tests the last() method with an empty countable object
  1940. *
  1941. * @return void
  1942. */
  1943. public function testLastWithEmptyCountable()
  1944. {
  1945. $collection = new Collection(new ArrayObject([]));
  1946. $this->assertNull($collection->last());
  1947. }
  1948. /**
  1949. * Tests the last() method with a non-rewindable iterator
  1950. *
  1951. * @return void
  1952. */
  1953. public function testLastWithNonRewindableIterator()
  1954. {
  1955. $iterator = new NoRewindIterator(new ArrayIterator([1, 2, 3]));
  1956. $collection = new Collection($iterator);
  1957. $this->assertEquals(3, $collection->last());
  1958. }
  1959. /**
  1960. * Tests the last() method with a traversable non-iterator
  1961. *
  1962. * @return void
  1963. */
  1964. public function testLastWithTraversableNonIterator()
  1965. {
  1966. $collection = new Collection($this->datePeriod('2017-01-01', '2017-01-07'));
  1967. $date = $collection->last();
  1968. $this->assertInstanceOf('DateTime', $date);
  1969. $this->assertEquals('2017-01-06', $date->format('Y-m-d'));
  1970. }
  1971. /**
  1972. * Tests the lastN() method
  1973. *
  1974. * @dataProvider simpleProvider
  1975. * @return void
  1976. */
  1977. public function testLastN($data)
  1978. {
  1979. $collection = new Collection($data);
  1980. $result = $collection->lastN(3)->toArray();
  1981. $expected = ['b' => 2, 'c' => 3, 'd' => 4];
  1982. $this->assertEquals($expected, $result);
  1983. }
  1984. /**
  1985. * Tests the lastN() method with overflow
  1986. *
  1987. * @dataProvider simpleProvider
  1988. * @return void
  1989. */
  1990. public function testLasNtWithOverflow($data)
  1991. {
  1992. $collection = new Collection($data);
  1993. $result = $collection->lastN(10)->toArray();
  1994. $expected = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4];
  1995. $this->assertEquals($expected, $result);
  1996. }
  1997. /**
  1998. * Tests the lastN() with and odd numbers collection
  1999. *
  2000. * @dataProvider simpleProvider
  2001. * @return void
  2002. */
  2003. public function testLasNtWithOddData($data)
  2004. {
  2005. $collection = new Collection($data);
  2006. $result = $collection->take(3)->lastN(2)->toArray();
  2007. $expected = ['b' => 2, 'c' => 3];
  2008. $this->assertEquals($expected, $result);
  2009. }
  2010. /**
  2011. * Tests the lastN() with countable collection
  2012. *
  2013. * @return void
  2014. */
  2015. public function testLasNtWithCountable()
  2016. {
  2017. $collection = new Collection(new ArrayObject([1, 2, 3, 4, 5]));
  2018. $result = $collection->lastN(2)->toArray();
  2019. $this->assertEquals([4, 5], $result);
  2020. $result = $collection->lastN(1)->toArray();
  2021. $this->assertEquals([5], $result);
  2022. }
  2023. /**
  2024. * Tests the lastN() with countable collection
  2025. *
  2026. * @dataProvider simpleProvider
  2027. * @return void
  2028. */
  2029. public function testLasNtWithNegative($data)
  2030. {
  2031. $collection = new Collection($data);
  2032. $this->expectException(\InvalidArgumentException::class);
  2033. $result = $collection->lastN(-1)->toArray();
  2034. }
  2035. /**
  2036. * Tests sumOf with no parameters
  2037. *
  2038. * @return void
  2039. */
  2040. public function testSumOfWithIdentity()
  2041. {
  2042. $collection = new Collection([1, 2, 3]);
  2043. $this->assertEquals(6, $collection->sumOf());
  2044. $collection = new Collection(['a' => 1, 'b' => 4, 'c' => 6]);
  2045. $this->assertEquals(11, $collection->sumOf());
  2046. }
  2047. /**
  2048. * Tests using extract with the {*} notation
  2049. *
  2050. * @return void
  2051. */
  2052. public function testUnfoldedExtract()
  2053. {
  2054. $items = [
  2055. ['comments' => [['id' => 1], ['id' => 2]]],
  2056. ['comments' => [['id' => 3], ['id' => 4]]],
  2057. ['comments' => [['id' => 7], ['nope' => 8]]],
  2058. ];
  2059. $extracted = (new Collection($items))->extract('comments.{*}.id');
  2060. $this->assertEquals([1, 2, 3, 4, 7, null], $extracted->toArray());
  2061. $items = [
  2062. [
  2063. 'comments' => [
  2064. [
  2065. 'voters' => [['id' => 1], ['id' => 2]]
  2066. ]
  2067. ]
  2068. ],
  2069. [
  2070. 'comments' => [
  2071. [
  2072. 'voters' => [['id' => 3], ['id' => 4]]
  2073. ]
  2074. ]
  2075. ],
  2076. [
  2077. 'comments' => [
  2078. [
  2079. 'voters' => [['id' => 5], ['nope' => 'fail'], ['id' => 6]]
  2080. ]
  2081. ]
  2082. ],
  2083. [
  2084. 'comments' => [
  2085. [
  2086. 'not_voters' => [['id' => 5]]
  2087. ]
  2088. ]
  2089. ],
  2090. ['not_comments' => []]
  2091. ];
  2092. $extracted = (new Collection($items))->extract('comments.{*}.voters.{*}.id');
  2093. $expected = [1, 2, 3, 4, 5, null, 6];
  2094. $this->assertEquals($expected, $extracted->toArray());
  2095. $this->assertEquals($expected, $extracted->toList());
  2096. }
  2097. /**
  2098. * Tests serializing a simple collection
  2099. *
  2100. * @return void
  2101. */
  2102. public function testSerializeSimpleCollection()
  2103. {
  2104. $collection = new Collection([1, 2, 3]);
  2105. $serialized = serialize($collection);
  2106. $unserialized = unserialize($serialized);
  2107. $this->assertEquals($collection->toList(), $unserialized->toList());
  2108. $this->assertEquals($collection->toArray(), $unserialized->toArray());
  2109. }
  2110. /**
  2111. * Tests serialization when using append
  2112. *
  2113. * @return void
  2114. */
  2115. public function testSerializeWithAppendIterators()
  2116. {
  2117. $collection = new Collection([1, 2, 3]);
  2118. $collection = $collection->append(['a' => 4, 'b' => 5, 'c' => 6]);
  2119. $serialized = serialize($collection);
  2120. $unserialized = unserialize($serialized);
  2121. $this->assertEquals($collection->toList(), $unserialized->toList());
  2122. $this->assertEquals($collection->toArray(), $unserialized->toArray());
  2123. }
  2124. /**
  2125. * Tests serialization when using nested iterators
  2126. *
  2127. * @return void
  2128. */
  2129. public function testSerializeWithNestedIterators()
  2130. {
  2131. $collection = new Collection([1, 2, 3]);
  2132. $collection = $collection->map(function ($e) {
  2133. return $e * 3;
  2134. });
  2135. $collection = $collection->groupBy(function ($e) {
  2136. return $e % 2;
  2137. });
  2138. $serialized = serialize($collection);
  2139. $unserialized = unserialize($serialized);
  2140. $this->assertEquals($collection->toList(), $unserialized->toList());
  2141. $this->assertEquals($collection->toArray(), $unserialized->toArray());
  2142. }
  2143. /**
  2144. * Tests serializing a zip() call
  2145. *
  2146. * @return void
  2147. */
  2148. public function testSerializeWithZipIterator()
  2149. {
  2150. $collection = new Collection([4, 5]);
  2151. $collection = $collection->zip([1, 2]);
  2152. $serialized = serialize($collection);
  2153. $unserialized = unserialize($serialized);
  2154. $this->assertEquals($collection->toList(), $unserialized->toList());
  2155. }
  2156. /**
  2157. * Provider for some chunk tests
  2158. *
  2159. * @return array
  2160. */
  2161. public function chunkProvider()
  2162. {
  2163. $items = range(1, 10);
  2164. return [
  2165. 'array' => [$items],
  2166. 'iterator' => [$this->yieldItems($items)]
  2167. ];
  2168. }
  2169. /**
  2170. * Tests the chunk method with exact chunks
  2171. *
  2172. * @dataProvider chunkProvider
  2173. * @return void
  2174. */
  2175. public function testChunk($items)
  2176. {
  2177. $collection = new Collection($items);
  2178. $chunked = $collection->chunk(2)->toList();
  2179. $expected = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]];
  2180. $this->assertEquals($expected, $chunked);
  2181. }
  2182. /**
  2183. * Tests the chunk method with overflowing chunk size
  2184. *
  2185. * @return void
  2186. */
  2187. public function testChunkOverflow()
  2188. {
  2189. $collection = new Collection(range(1, 11));
  2190. $chunked = $collection->chunk(2)->toList();
  2191. $expected = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11]];
  2192. $this->assertEquals($expected, $chunked);
  2193. }
  2194. /**
  2195. * Tests the chunk method with non-scalar items
  2196. *
  2197. * @return void
  2198. */
  2199. public function testChunkNested()
  2200. {
  2201. $collection = new Collection([1, 2, 3, [4, 5], 6, [7, [8, 9], 10], 11]);
  2202. $chunked = $collection->chunk(2)->toList();
  2203. $expected = [[1, 2], [3, [4, 5]], [6, [7, [8, 9], 10]], [11]];
  2204. $this->assertEquals($expected, $chunked);
  2205. }
  2206. /**
  2207. * Tests the chunkWithKeys method with exact chunks
  2208. *
  2209. * @return void
  2210. */
  2211. public function testChunkWithKeys()
  2212. {
  2213. $collection = new Collection(['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6]);
  2214. $chunked = $collection->chunkWithKeys(2)->toList();
  2215. $expected = [['a' => 1, 'b' => 2], ['c' => 3, 'd' => 4], ['e' => 5, 'f' => 6]];
  2216. $this->assertEquals($expected, $chunked);
  2217. }
  2218. /**
  2219. * Tests the chunkWithKeys method with overflowing chunk size
  2220. *
  2221. * @return void
  2222. */
  2223. public function testChunkWithKeysOverflow()
  2224. {
  2225. $collection = new Collection(['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6, 'g' => 7]);
  2226. $chunked = $collection->chunkWithKeys(2)->toList();
  2227. $expected = [['a' => 1, 'b' => 2], ['c' => 3, 'd' => 4], ['e' => 5, 'f' => 6], ['g' => 7]];
  2228. $this->assertEquals($expected, $chunked);
  2229. }
  2230. /**
  2231. * Tests the chunkWithKeys method with non-scalar items
  2232. *
  2233. * @return void
  2234. */
  2235. public function testChunkWithKeysNested()
  2236. {
  2237. $collection = new Collection(['a' => 1, 'b' => 2, 'c' => 3, 'd' => [4, 5], 'e' => 6, 'f' => [7, [8, 9], 10], 'g' => 11]);
  2238. $chunked = $collection->chunkWithKeys(2)->toList();
  2239. $expected = [['a' => 1, 'b' => 2], ['c' => 3, 'd' => [4, 5]], ['e' => 6, 'f' => [7, [8, 9], 10]], ['g' => 11]];
  2240. $this->assertEquals($expected, $chunked);
  2241. }
  2242. /**
  2243. * Tests the chunkWithKeys method without preserving keys
  2244. *
  2245. * @return void
  2246. */
  2247. public function testChunkWithKeysNoPreserveKeys()
  2248. {
  2249. $collection = new Collection(['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6, 'g' => 7]);
  2250. $chunked = $collection->chunkWithKeys(2, false)->toList();
  2251. $expected = [[0 => 1, 1 => 2], [0 => 3, 1 => 4], [0 => 5, 1 => 6], [0 => 7]];
  2252. $this->assertEquals($expected, $chunked);
  2253. }
  2254. /**
  2255. * Tests cartesianProduct
  2256. *
  2257. * @return void
  2258. */
  2259. public function testCartesianProduct()
  2260. {
  2261. $collection = new Collection([]);
  2262. $result = $collection->cartesianProduct();
  2263. $expected = [];
  2264. $this->assertEquals($expected, $result->toList());
  2265. $collection = new Collection([['A', 'B', 'C'], [1, 2, 3]]);
  2266. $result = $collection->cartesianProduct();
  2267. $expected = [
  2268. ['A', 1],
  2269. ['A', 2],
  2270. ['A', 3],
  2271. ['B', 1],
  2272. ['B', 2],
  2273. ['B', 3],
  2274. ['C', 1],
  2275. ['C', 2],
  2276. ['C', 3],
  2277. ];
  2278. $this->assertEquals($expected, $result->toList());
  2279. $collection = new Collection([[1, 2, 3], ['A', 'B', 'C'], ['a', 'b', 'c']]);
  2280. $result = $collection->cartesianProduct(function ($value) {
  2281. return [strval($value[0]) . $value[1] . $value[2]];
  2282. }, function ($value) {
  2283. return $value[0] >= 2;
  2284. });
  2285. $expected = [
  2286. ['2Aa'],
  2287. ['2Ab'],
  2288. ['2Ac'],
  2289. ['2Ba'],
  2290. ['2Bb'],
  2291. ['2Bc'],
  2292. ['2Ca'],
  2293. ['2Cb'],
  2294. ['2Cc'],
  2295. ['3Aa'],
  2296. ['3Ab'],
  2297. ['3Ac'],
  2298. ['3Ba'],
  2299. ['3Bb'],
  2300. ['3Bc'],
  2301. ['3Ca'],
  2302. ['3Cb'],
  2303. ['3Cc'],
  2304. ];
  2305. $this->assertEquals($expected, $result->toList());
  2306. $collection = new Collection([['1', '2', '3', '4'], ['A', 'B', 'C'], ['name', 'surname', 'telephone']]);
  2307. $result = $collection->cartesianProduct(function ($value) {
  2308. return [$value[0] => [$value[1] => $value[2]]];
  2309. }, function ($value) {
  2310. return $value[2] !== 'surname';
  2311. });
  2312. $expected = [
  2313. [1 => ['A' => 'name']],
  2314. [1 => ['A' => 'telephone']],
  2315. [1 => ['B' => 'name']],
  2316. [1 => ['B' => 'telephone']],
  2317. [1 => ['C' => 'name']],
  2318. [1 => ['C' => 'telephone']],
  2319. [2 => ['A' => 'name']],
  2320. [2 => ['A' => 'telephone']],
  2321. [2 => ['B' => 'name']],
  2322. [2 => ['B' => 'telephone']],
  2323. [2 => ['C' => 'name']],
  2324. [2 => ['C' => 'telephone']],
  2325. [3 => ['A' => 'name']],
  2326. [3 => ['A' => 'telephone']],
  2327. [3 => ['B' => 'name']],
  2328. [3 => ['B' => 'telephone']],
  2329. [3 => ['C' => 'name']],
  2330. [3 => ['C' => 'telephone']],
  2331. [4 => ['A' => 'name']],
  2332. [4 => ['A' => 'telephone']],
  2333. [4 => ['B' => 'name']],
  2334. [4 => ['B' => 'telephone']],
  2335. [4 => ['C' => 'name']],
  2336. [4 => ['C' => 'telephone']],
  2337. ];
  2338. $this->assertEquals($expected, $result->toList());
  2339. $collection = new Collection([
  2340. [
  2341. 'name1' => 'alex',
  2342. 'name2' => 'kostas',
  2343. 0 => 'leon',
  2344. ],
  2345. [
  2346. 'val1' => 'alex@example.com',
  2347. 24 => 'kostas@example.com',
  2348. 'val2' => 'leon@example.com',
  2349. ],
  2350. ]);
  2351. $result = $collection->cartesianProduct();
  2352. $expected = [
  2353. ['alex', 'alex@example.com'],
  2354. ['alex', 'kostas@example.com'],
  2355. ['alex', 'leon@example.com'],
  2356. ['kostas', 'alex@example.com'],
  2357. ['kostas', 'kostas@example.com'],
  2358. ['kostas', 'leon@example.com'],
  2359. ['leon', 'alex@example.com'],
  2360. ['leon', 'kostas@example.com'],
  2361. ['leon', 'leon@example.com'],
  2362. ];
  2363. $this->assertEquals($expected, $result->toList());
  2364. }
  2365. /**
  2366. * Tests that an exception is thrown if the cartesian product is called with multidimensional arrays
  2367. *
  2368. * @return void
  2369. */
  2370. public function testCartesianProductMultidimensionalArray()
  2371. {
  2372. $this->expectException(\LogicException::class);
  2373. $collection = new Collection([
  2374. [
  2375. 'names' => [
  2376. 'alex', 'kostas', 'leon'
  2377. ]
  2378. ],
  2379. [
  2380. 'locations' => [
  2381. 'crete', 'london', 'paris'
  2382. ]
  2383. ],
  2384. ]);
  2385. $result = $collection->cartesianProduct();
  2386. }
  2387. public function testTranspose()
  2388. {
  2389. $collection = new Collection([
  2390. ['Products', '2012', '2013', '2014'],
  2391. ['Product A', '200', '100', '50'],
  2392. ['Product B', '300', '200', '100'],
  2393. ['Product C', '400', '300', '200'],
  2394. ['Product D', '500', '400', '300'],
  2395. ]);
  2396. $transposed = $collection->transpose();
  2397. $expected = [
  2398. ['Products', 'Product A', 'Product B', 'Product C', 'Product D'],
  2399. ['2012', '200', '300', '400', '500'],
  2400. ['2013', '100', '200', '300', '400'],
  2401. ['2014', '50', '100', '200', '300'],
  2402. ];
  2403. $this->assertEquals($expected, $transposed->toList());
  2404. }
  2405. /**
  2406. * Tests that provided arrays do not have even length
  2407. *
  2408. * @return void
  2409. */
  2410. public function testTransposeUnEvenLengthShouldThrowException()
  2411. {
  2412. $this->expectException(\LogicException::class);
  2413. $collection = new Collection([
  2414. ['Products', '2012', '2013', '2014'],
  2415. ['Product A', '200', '100', '50'],
  2416. ['Product B', '300'],
  2417. ['Product C', '400', '300'],
  2418. ]);
  2419. $collection->transpose();
  2420. }
  2421. /**
  2422. * Yields all the elements as passed
  2423. *
  2424. * @param array $itmes the elements to be yielded
  2425. * @return void
  2426. */
  2427. protected function yieldItems(array $items)
  2428. {
  2429. foreach ($items as $k => $v) {
  2430. yield $k => $v;
  2431. }
  2432. }
  2433. /**
  2434. * Create a DatePeriod object.
  2435. *
  2436. * @param string $start Start date
  2437. * @param string $end End date
  2438. * @return \DatePeriod
  2439. */
  2440. protected function datePeriod($start, $end)
  2441. {
  2442. return new \DatePeriod(new \DateTime($start), new \DateInterval('P1D'), new \DateTime($end));
  2443. }
  2444. /**
  2445. * Tests to ensure that collection classes extending ArrayIterator work as expected.
  2446. *
  2447. * @return void
  2448. */
  2449. public function testArrayIteratorExtend()
  2450. {
  2451. $iterator = new TestIterator(range(0, 10));
  2452. $this->assertTrue(method_exists($iterator, 'checkValues'));
  2453. $this->assertTrue($iterator->checkValues());
  2454. //We need to perform at least two collection operation to trigger the issue.
  2455. $newIterator = $iterator
  2456. ->filter(function ($item) {
  2457. return $item < 5;
  2458. })
  2459. ->reject(function ($item) {
  2460. return $item > 2;
  2461. });
  2462. $this->assertTrue(method_exists($newIterator, 'checkValues'), 'Our method has gone missing!');
  2463. $this->assertTrue($newIterator->checkValues());
  2464. $this->assertCount(3, $newIterator->toArray());
  2465. }
  2466. }