CollectionTest.php 80 KB

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