CollectionTest.php 80 KB

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