CollectionTest.php 81 KB

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