CollectionTest.php 81 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787
  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 group by path that does not exist or contains a 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 index by path that does not exist or contains a null value');
  749. $collection->indexBy('missing');
  750. }
  751. /**
  752. * Tests passing an invalid path to indexBy.
  753. *
  754. * @return void
  755. */
  756. public function testIndexByInvalidPathCallback()
  757. {
  758. $items = [
  759. ['id' => 1, 'name' => 'foo'],
  760. ['id' => 2, 'name' => 'bar'],
  761. ['id' => 3, 'name' => 'baz'],
  762. ];
  763. $collection = new Collection($items);
  764. $this->expectException(InvalidArgumentException::class);
  765. $this->expectExceptionMessage('Cannot index by path that does not exist or contains a null value');
  766. $collection->indexBy(function ($e) {
  767. return null;
  768. });
  769. }
  770. /**
  771. * Tests countBy
  772. *
  773. * @dataProvider groupByProvider
  774. * @return void
  775. */
  776. public function testCountBy($items)
  777. {
  778. $collection = new Collection($items);
  779. $grouped = $collection->countBy('parent_id');
  780. $expected = [
  781. 10 => 2,
  782. 11 => 1,
  783. ];
  784. $result = iterator_to_array($grouped);
  785. $this->assertInstanceOf('Cake\Collection\Collection', $grouped);
  786. $this->assertEquals($expected, $result);
  787. }
  788. /**
  789. * Tests countBy
  790. *
  791. * @dataProvider groupByProvider
  792. * @return void
  793. */
  794. public function testCountByCallback($items)
  795. {
  796. $expected = [
  797. 10 => 2,
  798. 11 => 1,
  799. ];
  800. $collection = new Collection($items);
  801. $grouped = $collection->countBy(function ($element) {
  802. return $element['parent_id'];
  803. });
  804. $this->assertEquals($expected, iterator_to_array($grouped));
  805. }
  806. /**
  807. * Tests shuffle
  808. *
  809. * @dataProvider simpleProvider
  810. * @return void
  811. */
  812. public function testShuffle($data)
  813. {
  814. $collection = (new Collection($data))->shuffle();
  815. $result = $collection->toArray();
  816. $this->assertCount(4, $result);
  817. $this->assertContains(1, $result);
  818. $this->assertContains(2, $result);
  819. $this->assertContains(3, $result);
  820. $this->assertContains(4, $result);
  821. }
  822. /**
  823. * Tests shuffle with duplicate keys.
  824. *
  825. * @return void
  826. */
  827. public function testShuffleDuplicateKeys()
  828. {
  829. $collection = (new Collection(['a' => 1]))->append(['a' => 2])->shuffle();
  830. $result = $collection->toArray();
  831. $this->assertCount(2, $result);
  832. $this->assertEquals([0, 1], array_keys($result));
  833. $this->assertContainsEquals(1, $result);
  834. $this->assertContainsEquals(2, $result);
  835. }
  836. /**
  837. * Tests sample
  838. *
  839. * @dataProvider simpleProvider
  840. * @return void
  841. */
  842. public function testSample($data)
  843. {
  844. $result = (new Collection($data))->sample(2)->toArray();
  845. $this->assertCount(2, $result);
  846. foreach ($result as $number) {
  847. $this->assertContains($number, [1, 2, 3, 4]);
  848. }
  849. }
  850. /**
  851. * Tests the sample() method with a traversable non-iterator
  852. *
  853. * @return void
  854. */
  855. public function testSampleWithTraversableNonIterator()
  856. {
  857. $collection = new Collection($this->datePeriod('2017-01-01', '2017-01-07'));
  858. $result = $collection->sample(3)->toList();
  859. $list = [
  860. '2017-01-01',
  861. '2017-01-02',
  862. '2017-01-03',
  863. '2017-01-04',
  864. '2017-01-05',
  865. '2017-01-06',
  866. ];
  867. $this->assertCount(3, $result);
  868. foreach ($result as $date) {
  869. $this->assertContains($date->format('Y-m-d'), $list);
  870. }
  871. }
  872. /**
  873. * Test toArray method
  874. *
  875. * @return void
  876. */
  877. public function testToArray()
  878. {
  879. $data = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4];
  880. $collection = new Collection($data);
  881. $this->assertEquals($data, $collection->toArray());
  882. }
  883. /**
  884. * Test toList method
  885. *
  886. * @dataProvider simpleProvider
  887. * @return void
  888. */
  889. public function testToList($data)
  890. {
  891. $collection = new Collection($data);
  892. $this->assertEquals([1, 2, 3, 4], $collection->toList());
  893. }
  894. /**
  895. * Test JSON encoding
  896. *
  897. * @return void
  898. */
  899. public function testToJson()
  900. {
  901. $data = [1, 2, 3, 4];
  902. $collection = new Collection($data);
  903. $this->assertEquals(json_encode($data), json_encode($collection));
  904. }
  905. /**
  906. * Tests that Count returns the number of elements
  907. *
  908. * @dataProvider simpleProvider
  909. * @return void
  910. */
  911. public function testCollectionCount($list)
  912. {
  913. $list = (new Collection($list))->buffered();
  914. $collection = new Collection($list);
  915. $this->assertSame(8, $collection->append($list)->count());
  916. }
  917. /**
  918. * Tests that countKeys returns the number of unique keys
  919. *
  920. * @dataProvider simpleProvider
  921. * @return void
  922. */
  923. public function testCollectionCountKeys($list)
  924. {
  925. $list = (new Collection($list))->buffered();
  926. $collection = new Collection($list);
  927. $this->assertSame(4, $collection->append($list)->countKeys());
  928. }
  929. /**
  930. * Tests take method
  931. *
  932. * @return void
  933. */
  934. public function testTake()
  935. {
  936. $data = [1, 2, 3, 4];
  937. $collection = new Collection($data);
  938. $taken = $collection->take(2);
  939. $this->assertEquals([1, 2], $taken->toArray());
  940. $taken = $collection->take(3);
  941. $this->assertEquals([1, 2, 3], $taken->toArray());
  942. $taken = $collection->take(500);
  943. $this->assertEquals([1, 2, 3, 4], $taken->toArray());
  944. $taken = $collection->take(1);
  945. $this->assertEquals([1], $taken->toArray());
  946. $taken = $collection->take();
  947. $this->assertEquals([1], $taken->toArray());
  948. $taken = $collection->take(2, 2);
  949. $this->assertEquals([2 => 3, 3 => 4], $taken->toArray());
  950. }
  951. /**
  952. * Tests the take() method with a traversable non-iterator
  953. *
  954. * @return void
  955. */
  956. public function testTakeWithTraversableNonIterator()
  957. {
  958. $collection = new Collection($this->datePeriod('2017-01-01', '2017-01-07'));
  959. $result = $collection->take(3, 1)->toList();
  960. $expected = [
  961. new \DateTime('2017-01-02'),
  962. new \DateTime('2017-01-03'),
  963. new \DateTime('2017-01-04'),
  964. ];
  965. $this->assertEquals($expected, $result);
  966. }
  967. /**
  968. * Tests match
  969. *
  970. * @return void
  971. */
  972. public function testMatch()
  973. {
  974. $items = [
  975. ['id' => 1, 'name' => 'foo', 'thing' => ['parent_id' => 10]],
  976. ['id' => 2, 'name' => 'bar', 'thing' => ['parent_id' => 11]],
  977. ['id' => 3, 'name' => 'baz', 'thing' => ['parent_id' => 10]],
  978. ];
  979. $collection = new Collection($items);
  980. $matched = $collection->match(['thing.parent_id' => 10, 'name' => 'baz']);
  981. $this->assertEquals([2 => $items[2]], $matched->toArray());
  982. $matched = $collection->match(['thing.parent_id' => 10]);
  983. $this->assertEquals(
  984. [0 => $items[0], 2 => $items[2]],
  985. $matched->toArray()
  986. );
  987. $matched = $collection->match(['thing.parent_id' => 500]);
  988. $this->assertEquals([], $matched->toArray());
  989. $matched = $collection->match(['parent_id' => 10, 'name' => 'baz']);
  990. $this->assertEquals([], $matched->toArray());
  991. }
  992. /**
  993. * Tests firstMatch
  994. *
  995. * @return void
  996. */
  997. public function testFirstMatch()
  998. {
  999. $items = [
  1000. ['id' => 1, 'name' => 'foo', 'thing' => ['parent_id' => 10]],
  1001. ['id' => 2, 'name' => 'bar', 'thing' => ['parent_id' => 11]],
  1002. ['id' => 3, 'name' => 'baz', 'thing' => ['parent_id' => 10]],
  1003. ];
  1004. $collection = new Collection($items);
  1005. $matched = $collection->firstMatch(['thing.parent_id' => 10]);
  1006. $this->assertEquals(
  1007. ['id' => 1, 'name' => 'foo', 'thing' => ['parent_id' => 10]],
  1008. $matched
  1009. );
  1010. $matched = $collection->firstMatch(['thing.parent_id' => 10, 'name' => 'baz']);
  1011. $this->assertEquals(
  1012. ['id' => 3, 'name' => 'baz', 'thing' => ['parent_id' => 10]],
  1013. $matched
  1014. );
  1015. }
  1016. /**
  1017. * Tests the append method
  1018. *
  1019. * @return void
  1020. */
  1021. public function testAppend()
  1022. {
  1023. $collection = new Collection([1, 2, 3]);
  1024. $combined = $collection->append([4, 5, 6]);
  1025. $this->assertEquals([1, 2, 3, 4, 5, 6], $combined->toArray(false));
  1026. $collection = new Collection(['a' => 1, 'b' => 2]);
  1027. $combined = $collection->append(['c' => 3, 'a' => 4]);
  1028. $this->assertEquals(['a' => 4, 'b' => 2, 'c' => 3], $combined->toArray());
  1029. }
  1030. /**
  1031. * Tests the appendItem method
  1032. */
  1033. public function testAppendItem()
  1034. {
  1035. $collection = new Collection([1, 2, 3]);
  1036. $combined = $collection->appendItem(4);
  1037. $this->assertEquals([1, 2, 3, 4], $combined->toArray(false));
  1038. $collection = new Collection(['a' => 1, 'b' => 2]);
  1039. $combined = $collection->appendItem(3, 'c');
  1040. $combined = $combined->appendItem(4, 'a');
  1041. $this->assertEquals(['a' => 4, 'b' => 2, 'c' => 3], $combined->toArray());
  1042. }
  1043. /**
  1044. * Tests the prepend method
  1045. */
  1046. public function testPrepend()
  1047. {
  1048. $collection = new Collection([1, 2, 3]);
  1049. $combined = $collection->prepend(['a']);
  1050. $this->assertEquals(['a', 1, 2, 3], $combined->toList());
  1051. $collection = new Collection(['c' => 3, 'd' => 4]);
  1052. $combined = $collection->prepend(['a' => 1, 'b' => 2]);
  1053. $this->assertEquals(['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4], $combined->toArray());
  1054. }
  1055. /**
  1056. * Tests prependItem method
  1057. */
  1058. public function testPrependItem()
  1059. {
  1060. $collection = new Collection([1, 2, 3]);
  1061. $combined = $collection->prependItem('a');
  1062. $this->assertEquals(['a', 1, 2, 3], $combined->toList());
  1063. $collection = new Collection(['c' => 3, 'd' => 4]);
  1064. $combined = $collection->prependItem(2, 'b');
  1065. $combined = $combined->prependItem(1, 'a');
  1066. $this->assertEquals(['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4], $combined->toArray());
  1067. }
  1068. /**
  1069. * Tests prependItem method
  1070. */
  1071. public function testPrependItemPreserveKeys()
  1072. {
  1073. $collection = new Collection([1, 2, 3]);
  1074. $combined = $collection->prependItem('a');
  1075. $this->assertEquals(['a', 1, 2, 3], $combined->toList());
  1076. $collection = new Collection(['c' => 3, 'd' => 4]);
  1077. $combined = $collection->prependItem(2, 'b');
  1078. $combined = $combined->prependItem(1, 'a');
  1079. $this->assertEquals(['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4], $combined->toArray());
  1080. }
  1081. /**
  1082. * Tests the append method with iterator
  1083. */
  1084. public function testAppendIterator()
  1085. {
  1086. $collection = new Collection([1, 2, 3]);
  1087. $iterator = new ArrayIterator([4, 5, 6]);
  1088. $combined = $collection->append($iterator);
  1089. $this->assertEquals([1, 2, 3, 4, 5, 6], $combined->toList());
  1090. }
  1091. public function testAppendNotCollectionInstance()
  1092. {
  1093. $collection = new TestCollection([1, 2, 3]);
  1094. $combined = $collection->append([4, 5, 6]);
  1095. $this->assertEquals([1, 2, 3, 4, 5, 6], $combined->toList());
  1096. }
  1097. /**
  1098. * Tests that by calling compile internal iteration operations are not done
  1099. * more than once
  1100. *
  1101. * @return void
  1102. */
  1103. public function testCompile()
  1104. {
  1105. $items = ['a' => 1, 'b' => 2, 'c' => 3];
  1106. $collection = new Collection($items);
  1107. $results = [];
  1108. $compiled = $collection
  1109. ->map(function ($value, $key) use (&$results) {
  1110. $results[] = [$key => $value];
  1111. return $value + 3;
  1112. })
  1113. ->compile();
  1114. $this->assertSame(['a' => 4, 'b' => 5, 'c' => 6], $compiled->toArray());
  1115. $this->assertSame(['a' => 4, 'b' => 5, 'c' => 6], $compiled->toArray());
  1116. $this->assertSame([['a' => 1], ['b' => 2], ['c' => 3]], $results);
  1117. }
  1118. /**
  1119. * Tests converting a non rewindable iterator into a rewindable one using
  1120. * the buffered method.
  1121. *
  1122. * @return void
  1123. */
  1124. public function testBuffered()
  1125. {
  1126. $items = new NoRewindIterator(new ArrayIterator(['a' => 4, 'b' => 5, 'c' => 6]));
  1127. $buffered = (new Collection($items))->buffered();
  1128. $this->assertEquals(['a' => 4, 'b' => 5, 'c' => 6], $buffered->toArray());
  1129. $this->assertEquals(['a' => 4, 'b' => 5, 'c' => 6], $buffered->toArray());
  1130. }
  1131. public function testBufferedIterator()
  1132. {
  1133. $data = [
  1134. ['myField' => '1'],
  1135. ['myField' => '2'],
  1136. ['myField' => '3'],
  1137. ];
  1138. $buffered = (new \Cake\Collection\Collection($data))->buffered();
  1139. // Check going forwards
  1140. $this->assertNotEmpty($buffered->firstMatch(['myField' => '1']));
  1141. $this->assertNotEmpty($buffered->firstMatch(['myField' => '2']));
  1142. $this->assertNotEmpty($buffered->firstMatch(['myField' => '3']));
  1143. // And backwards.
  1144. $this->assertNotEmpty($buffered->firstMatch(['myField' => '3']));
  1145. $this->assertNotEmpty($buffered->firstMatch(['myField' => '2']));
  1146. $this->assertNotEmpty($buffered->firstMatch(['myField' => '1']));
  1147. }
  1148. /**
  1149. * Tests the combine method
  1150. *
  1151. * @return void
  1152. */
  1153. public function testCombine()
  1154. {
  1155. $items = [
  1156. ['id' => 1, 'name' => 'foo', 'parent' => 'a'],
  1157. ['id' => 2, 'name' => 'bar', 'parent' => 'b'],
  1158. ['id' => 3, 'name' => 'baz', 'parent' => 'a'],
  1159. ];
  1160. $collection = (new Collection($items))->combine('id', 'name');
  1161. $expected = [1 => 'foo', 2 => 'bar', 3 => 'baz'];
  1162. $this->assertEquals($expected, $collection->toArray());
  1163. $expected = ['foo' => 1, 'bar' => 2, 'baz' => 3];
  1164. $collection = (new Collection($items))->combine('name', 'id');
  1165. $this->assertEquals($expected, $collection->toArray());
  1166. $collection = (new Collection($items))->combine('id', 'name', 'parent');
  1167. $expected = ['a' => [1 => 'foo', 3 => 'baz'], 'b' => [2 => 'bar']];
  1168. $this->assertEquals($expected, $collection->toArray());
  1169. $expected = [
  1170. '0-1' => ['foo-0-1' => '0-1-foo'],
  1171. '1-2' => ['bar-1-2' => '1-2-bar'],
  1172. '2-3' => ['baz-2-3' => '2-3-baz'],
  1173. ];
  1174. $collection = (new Collection($items))->combine(
  1175. function ($value, $key) {
  1176. return $value['name'] . '-' . $key;
  1177. },
  1178. function ($value, $key) {
  1179. return $key . '-' . $value['name'];
  1180. },
  1181. function ($value, $key) {
  1182. return $key . '-' . $value['id'];
  1183. }
  1184. );
  1185. $this->assertEquals($expected, $collection->toArray());
  1186. $collection = (new Collection($items))->combine('id', 'crazy');
  1187. $this->assertEquals([1 => null, 2 => null, 3 => null], $collection->toArray());
  1188. }
  1189. /**
  1190. * Tests the nest method with only one level
  1191. *
  1192. * @return void
  1193. */
  1194. public function testNest()
  1195. {
  1196. $items = [
  1197. ['id' => 1, 'parent_id' => null],
  1198. ['id' => 2, 'parent_id' => 1],
  1199. ['id' => 3, 'parent_id' => 1],
  1200. ['id' => 4, 'parent_id' => 1],
  1201. ['id' => 5, 'parent_id' => 6],
  1202. ['id' => 6, 'parent_id' => null],
  1203. ['id' => 7, 'parent_id' => 1],
  1204. ['id' => 8, 'parent_id' => 6],
  1205. ['id' => 9, 'parent_id' => 6],
  1206. ['id' => 10, 'parent_id' => 6],
  1207. ];
  1208. $collection = (new Collection($items))->nest('id', 'parent_id');
  1209. $expected = [
  1210. [
  1211. 'id' => 1,
  1212. 'parent_id' => null,
  1213. 'children' => [
  1214. ['id' => 2, 'parent_id' => 1, 'children' => []],
  1215. ['id' => 3, 'parent_id' => 1, 'children' => []],
  1216. ['id' => 4, 'parent_id' => 1, 'children' => []],
  1217. ['id' => 7, 'parent_id' => 1, 'children' => []],
  1218. ],
  1219. ],
  1220. [
  1221. 'id' => 6,
  1222. 'parent_id' => null,
  1223. 'children' => [
  1224. ['id' => 5, 'parent_id' => 6, 'children' => []],
  1225. ['id' => 8, 'parent_id' => 6, 'children' => []],
  1226. ['id' => 9, 'parent_id' => 6, 'children' => []],
  1227. ['id' => 10, 'parent_id' => 6, 'children' => []],
  1228. ],
  1229. ],
  1230. ];
  1231. $this->assertEquals($expected, $collection->toArray());
  1232. }
  1233. /**
  1234. * Tests the nest method with alternate nesting key
  1235. *
  1236. * @return void
  1237. */
  1238. public function testNestAlternateNestingKey()
  1239. {
  1240. $items = [
  1241. ['id' => 1, 'parent_id' => null],
  1242. ['id' => 2, 'parent_id' => 1],
  1243. ['id' => 3, 'parent_id' => 1],
  1244. ['id' => 4, 'parent_id' => 1],
  1245. ['id' => 5, 'parent_id' => 6],
  1246. ['id' => 6, 'parent_id' => null],
  1247. ['id' => 7, 'parent_id' => 1],
  1248. ['id' => 8, 'parent_id' => 6],
  1249. ['id' => 9, 'parent_id' => 6],
  1250. ['id' => 10, 'parent_id' => 6],
  1251. ];
  1252. $collection = (new Collection($items))->nest('id', 'parent_id', 'nodes');
  1253. $expected = [
  1254. [
  1255. 'id' => 1,
  1256. 'parent_id' => null,
  1257. 'nodes' => [
  1258. ['id' => 2, 'parent_id' => 1, 'nodes' => []],
  1259. ['id' => 3, 'parent_id' => 1, 'nodes' => []],
  1260. ['id' => 4, 'parent_id' => 1, 'nodes' => []],
  1261. ['id' => 7, 'parent_id' => 1, 'nodes' => []],
  1262. ],
  1263. ],
  1264. [
  1265. 'id' => 6,
  1266. 'parent_id' => null,
  1267. 'nodes' => [
  1268. ['id' => 5, 'parent_id' => 6, 'nodes' => []],
  1269. ['id' => 8, 'parent_id' => 6, 'nodes' => []],
  1270. ['id' => 9, 'parent_id' => 6, 'nodes' => []],
  1271. ['id' => 10, 'parent_id' => 6, 'nodes' => []],
  1272. ],
  1273. ],
  1274. ];
  1275. $this->assertEquals($expected, $collection->toArray());
  1276. }
  1277. /**
  1278. * Tests the nest method with more than one level
  1279. *
  1280. * @return void
  1281. */
  1282. public function testNestMultiLevel()
  1283. {
  1284. $items = [
  1285. ['id' => 1, 'parent_id' => null],
  1286. ['id' => 2, 'parent_id' => 1],
  1287. ['id' => 3, 'parent_id' => 2],
  1288. ['id' => 4, 'parent_id' => 2],
  1289. ['id' => 5, 'parent_id' => 3],
  1290. ['id' => 6, 'parent_id' => null],
  1291. ['id' => 7, 'parent_id' => 3],
  1292. ['id' => 8, 'parent_id' => 4],
  1293. ['id' => 9, 'parent_id' => 6],
  1294. ['id' => 10, 'parent_id' => 6],
  1295. ];
  1296. $collection = (new Collection($items))->nest('id', 'parent_id', 'nodes');
  1297. $expected = [
  1298. [
  1299. 'id' => 1,
  1300. 'parent_id' => null,
  1301. 'nodes' => [
  1302. [
  1303. 'id' => 2,
  1304. 'parent_id' => 1,
  1305. 'nodes' => [
  1306. [
  1307. 'id' => 3,
  1308. 'parent_id' => 2,
  1309. 'nodes' => [
  1310. ['id' => 5, 'parent_id' => 3, 'nodes' => []],
  1311. ['id' => 7, 'parent_id' => 3, 'nodes' => []],
  1312. ],
  1313. ],
  1314. [
  1315. 'id' => 4,
  1316. 'parent_id' => 2,
  1317. 'nodes' => [
  1318. ['id' => 8, 'parent_id' => 4, 'nodes' => []],
  1319. ],
  1320. ],
  1321. ],
  1322. ],
  1323. ],
  1324. ],
  1325. [
  1326. 'id' => 6,
  1327. 'parent_id' => null,
  1328. 'nodes' => [
  1329. ['id' => 9, 'parent_id' => 6, 'nodes' => []],
  1330. ['id' => 10, 'parent_id' => 6, 'nodes' => []],
  1331. ],
  1332. ],
  1333. ];
  1334. $this->assertEquals($expected, $collection->toArray());
  1335. }
  1336. /**
  1337. * Tests the nest method with more than one level
  1338. *
  1339. * @return void
  1340. */
  1341. public function testNestMultiLevelAlternateNestingKey()
  1342. {
  1343. $items = [
  1344. ['id' => 1, 'parent_id' => null],
  1345. ['id' => 2, 'parent_id' => 1],
  1346. ['id' => 3, 'parent_id' => 2],
  1347. ['id' => 4, 'parent_id' => 2],
  1348. ['id' => 5, 'parent_id' => 3],
  1349. ['id' => 6, 'parent_id' => null],
  1350. ['id' => 7, 'parent_id' => 3],
  1351. ['id' => 8, 'parent_id' => 4],
  1352. ['id' => 9, 'parent_id' => 6],
  1353. ['id' => 10, 'parent_id' => 6],
  1354. ];
  1355. $collection = (new Collection($items))->nest('id', 'parent_id');
  1356. $expected = [
  1357. [
  1358. 'id' => 1,
  1359. 'parent_id' => null,
  1360. 'children' => [
  1361. [
  1362. 'id' => 2,
  1363. 'parent_id' => 1,
  1364. 'children' => [
  1365. [
  1366. 'id' => 3,
  1367. 'parent_id' => 2,
  1368. 'children' => [
  1369. ['id' => 5, 'parent_id' => 3, 'children' => []],
  1370. ['id' => 7, 'parent_id' => 3, 'children' => []],
  1371. ],
  1372. ],
  1373. [
  1374. 'id' => 4,
  1375. 'parent_id' => 2,
  1376. 'children' => [
  1377. ['id' => 8, 'parent_id' => 4, 'children' => []],
  1378. ],
  1379. ],
  1380. ],
  1381. ],
  1382. ],
  1383. ],
  1384. [
  1385. 'id' => 6,
  1386. 'parent_id' => null,
  1387. 'children' => [
  1388. ['id' => 9, 'parent_id' => 6, 'children' => []],
  1389. ['id' => 10, 'parent_id' => 6, 'children' => []],
  1390. ],
  1391. ],
  1392. ];
  1393. $this->assertEquals($expected, $collection->toArray());
  1394. }
  1395. /**
  1396. * Tests the nest method with more than one level
  1397. *
  1398. * @return void
  1399. */
  1400. public function testNestObjects()
  1401. {
  1402. $items = [
  1403. new ArrayObject(['id' => 1, 'parent_id' => null]),
  1404. new ArrayObject(['id' => 2, 'parent_id' => 1]),
  1405. new ArrayObject(['id' => 3, 'parent_id' => 2]),
  1406. new ArrayObject(['id' => 4, 'parent_id' => 2]),
  1407. new ArrayObject(['id' => 5, 'parent_id' => 3]),
  1408. new ArrayObject(['id' => 6, 'parent_id' => null]),
  1409. new ArrayObject(['id' => 7, 'parent_id' => 3]),
  1410. new ArrayObject(['id' => 8, 'parent_id' => 4]),
  1411. new ArrayObject(['id' => 9, 'parent_id' => 6]),
  1412. new ArrayObject(['id' => 10, 'parent_id' => 6]),
  1413. ];
  1414. $collection = (new Collection($items))->nest('id', 'parent_id');
  1415. $expected = [
  1416. new ArrayObject([
  1417. 'id' => 1,
  1418. 'parent_id' => null,
  1419. 'children' => [
  1420. new ArrayObject([
  1421. 'id' => 2,
  1422. 'parent_id' => 1,
  1423. 'children' => [
  1424. new ArrayObject([
  1425. 'id' => 3,
  1426. 'parent_id' => 2,
  1427. 'children' => [
  1428. new ArrayObject(['id' => 5, 'parent_id' => 3, 'children' => []]),
  1429. new ArrayObject(['id' => 7, 'parent_id' => 3, 'children' => []]),
  1430. ],
  1431. ]),
  1432. new ArrayObject([
  1433. 'id' => 4,
  1434. 'parent_id' => 2,
  1435. 'children' => [
  1436. new ArrayObject(['id' => 8, 'parent_id' => 4, 'children' => []]),
  1437. ],
  1438. ]),
  1439. ],
  1440. ]),
  1441. ],
  1442. ]),
  1443. new ArrayObject([
  1444. 'id' => 6,
  1445. 'parent_id' => null,
  1446. 'children' => [
  1447. new ArrayObject(['id' => 9, 'parent_id' => 6, 'children' => []]),
  1448. new ArrayObject(['id' => 10, 'parent_id' => 6, 'children' => []]),
  1449. ],
  1450. ]),
  1451. ];
  1452. $this->assertEquals($expected, $collection->toArray());
  1453. }
  1454. /**
  1455. * Tests the nest method with more than one level
  1456. *
  1457. * @return void
  1458. */
  1459. public function testNestObjectsAlternateNestingKey()
  1460. {
  1461. $items = [
  1462. new ArrayObject(['id' => 1, 'parent_id' => null]),
  1463. new ArrayObject(['id' => 2, 'parent_id' => 1]),
  1464. new ArrayObject(['id' => 3, 'parent_id' => 2]),
  1465. new ArrayObject(['id' => 4, 'parent_id' => 2]),
  1466. new ArrayObject(['id' => 5, 'parent_id' => 3]),
  1467. new ArrayObject(['id' => 6, 'parent_id' => null]),
  1468. new ArrayObject(['id' => 7, 'parent_id' => 3]),
  1469. new ArrayObject(['id' => 8, 'parent_id' => 4]),
  1470. new ArrayObject(['id' => 9, 'parent_id' => 6]),
  1471. new ArrayObject(['id' => 10, 'parent_id' => 6]),
  1472. ];
  1473. $collection = (new Collection($items))->nest('id', 'parent_id', 'nodes');
  1474. $expected = [
  1475. new ArrayObject([
  1476. 'id' => 1,
  1477. 'parent_id' => null,
  1478. 'nodes' => [
  1479. new ArrayObject([
  1480. 'id' => 2,
  1481. 'parent_id' => 1,
  1482. 'nodes' => [
  1483. new ArrayObject([
  1484. 'id' => 3,
  1485. 'parent_id' => 2,
  1486. 'nodes' => [
  1487. new ArrayObject(['id' => 5, 'parent_id' => 3, 'nodes' => []]),
  1488. new ArrayObject(['id' => 7, 'parent_id' => 3, 'nodes' => []]),
  1489. ],
  1490. ]),
  1491. new ArrayObject([
  1492. 'id' => 4,
  1493. 'parent_id' => 2,
  1494. 'nodes' => [
  1495. new ArrayObject(['id' => 8, 'parent_id' => 4, 'nodes' => []]),
  1496. ],
  1497. ]),
  1498. ],
  1499. ]),
  1500. ],
  1501. ]),
  1502. new ArrayObject([
  1503. 'id' => 6,
  1504. 'parent_id' => null,
  1505. 'nodes' => [
  1506. new ArrayObject(['id' => 9, 'parent_id' => 6, 'nodes' => []]),
  1507. new ArrayObject(['id' => 10, 'parent_id' => 6, 'nodes' => []]),
  1508. ],
  1509. ]),
  1510. ];
  1511. $this->assertEquals($expected, $collection->toArray());
  1512. }
  1513. /**
  1514. * Tests insert
  1515. *
  1516. * @return void
  1517. */
  1518. public function testInsert()
  1519. {
  1520. $items = [['a' => 1], ['b' => 2]];
  1521. $collection = new Collection($items);
  1522. $iterator = $collection->insert('c', [3, 4]);
  1523. $this->assertInstanceOf('Cake\Collection\Iterator\InsertIterator', $iterator);
  1524. $this->assertEquals(
  1525. [['a' => 1, 'c' => 3], ['b' => 2, 'c' => 4]],
  1526. iterator_to_array($iterator)
  1527. );
  1528. }
  1529. /**
  1530. * Provider for testing each of the directions for listNested
  1531. *
  1532. * @return array
  1533. */
  1534. public function nestedListProvider()
  1535. {
  1536. return [
  1537. ['desc', [1, 2, 3, 5, 7, 4, 8, 6, 9, 10]],
  1538. ['asc', [5, 7, 3, 8, 4, 2, 1, 9, 10, 6]],
  1539. ['leaves', [5, 7, 8, 9, 10]],
  1540. ];
  1541. }
  1542. /**
  1543. * Tests the listNested method with the default 'children' nesting key
  1544. *
  1545. * @dataProvider nestedListProvider
  1546. * @return void
  1547. */
  1548. public function testListNested($dir, $expected)
  1549. {
  1550. $items = [
  1551. ['id' => 1, 'parent_id' => null],
  1552. ['id' => 2, 'parent_id' => 1],
  1553. ['id' => 3, 'parent_id' => 2],
  1554. ['id' => 4, 'parent_id' => 2],
  1555. ['id' => 5, 'parent_id' => 3],
  1556. ['id' => 6, 'parent_id' => null],
  1557. ['id' => 7, 'parent_id' => 3],
  1558. ['id' => 8, 'parent_id' => 4],
  1559. ['id' => 9, 'parent_id' => 6],
  1560. ['id' => 10, 'parent_id' => 6],
  1561. ];
  1562. $collection = (new Collection($items))->nest('id', 'parent_id')->listNested($dir);
  1563. $this->assertEquals($expected, $collection->extract('id')->toArray(false));
  1564. }
  1565. /**
  1566. * Tests the listNested spacer output.
  1567. *
  1568. * @return void
  1569. */
  1570. public function testListNestedSpacer()
  1571. {
  1572. $items = [
  1573. ['id' => 1, 'parent_id' => null, 'name' => 'Birds'],
  1574. ['id' => 2, 'parent_id' => 1, 'name' => 'Land Birds'],
  1575. ['id' => 3, 'parent_id' => 1, 'name' => 'Eagle'],
  1576. ['id' => 4, 'parent_id' => 1, 'name' => 'Seagull'],
  1577. ['id' => 5, 'parent_id' => 6, 'name' => 'Clown Fish'],
  1578. ['id' => 6, 'parent_id' => null, 'name' => 'Fish'],
  1579. ];
  1580. $collection = (new Collection($items))->nest('id', 'parent_id')->listNested();
  1581. $expected = [
  1582. 'Birds',
  1583. '---Land Birds',
  1584. '---Eagle',
  1585. '---Seagull',
  1586. 'Fish',
  1587. '---Clown Fish',
  1588. ];
  1589. $this->assertSame($expected, $collection->printer('name', 'id', '---')->toList());
  1590. }
  1591. /**
  1592. * Tests using listNested with a different nesting key
  1593. *
  1594. * @return void
  1595. */
  1596. public function testListNestedCustomKey()
  1597. {
  1598. $items = [
  1599. ['id' => 1, 'stuff' => [['id' => 2, 'stuff' => [['id' => 3]]]]],
  1600. ['id' => 4, 'stuff' => [['id' => 5]]],
  1601. ];
  1602. $collection = (new Collection($items))->listNested('desc', 'stuff');
  1603. $this->assertEquals(range(1, 5), $collection->extract('id')->toArray(false));
  1604. }
  1605. /**
  1606. * Tests flattening the collection using a custom callable function
  1607. *
  1608. * @return void
  1609. */
  1610. public function testListNestedWithCallable()
  1611. {
  1612. $items = [
  1613. ['id' => 1, 'stuff' => [['id' => 2, 'stuff' => [['id' => 3]]]]],
  1614. ['id' => 4, 'stuff' => [['id' => 5]]],
  1615. ];
  1616. $collection = (new Collection($items))->listNested('desc', function ($item) {
  1617. return $item['stuff'] ?? [];
  1618. });
  1619. $this->assertEquals(range(1, 5), $collection->extract('id')->toArray(false));
  1620. }
  1621. /**
  1622. * Provider for sumOf tests
  1623. *
  1624. * @return array
  1625. */
  1626. public function sumOfProvider()
  1627. {
  1628. $items = [
  1629. ['invoice' => ['total' => 100]],
  1630. ['invoice' => ['total' => 200]],
  1631. ];
  1632. $floatItems = [
  1633. ['invoice' => ['total' => 100.0]],
  1634. ['invoice' => ['total' => 200.0]],
  1635. ];
  1636. return [
  1637. 'array' => [$items, 300],
  1638. 'iterator' => [$this->yieldItems($items), 300],
  1639. 'floatArray' => [$floatItems, 300.0],
  1640. 'floatIterator' => [$this->yieldItems($floatItems), 300.0],
  1641. ];
  1642. }
  1643. /**
  1644. * Tests the sumOf method
  1645. *
  1646. * @dataProvider sumOfProvider
  1647. * @return void
  1648. */
  1649. public function testSumOf($items, $expected)
  1650. {
  1651. $this->assertEquals($expected, (new Collection($items))->sumOf('invoice.total'));
  1652. }
  1653. /**
  1654. * Tests the sumOf method
  1655. *
  1656. * @dataProvider sumOfProvider
  1657. * @return void
  1658. */
  1659. public function testSumOfCallable($items, $expected)
  1660. {
  1661. $sum = (new Collection($items))->sumOf(function ($v) {
  1662. return $v['invoice']['total'];
  1663. });
  1664. $this->assertEquals($expected, $sum);
  1665. }
  1666. /**
  1667. * Tests the stopWhen method with a callable
  1668. *
  1669. * @dataProvider simpleProvider
  1670. * @return void
  1671. */
  1672. public function testStopWhenCallable($items)
  1673. {
  1674. $collection = (new Collection($items))->stopWhen(function ($v) {
  1675. return $v > 3;
  1676. });
  1677. $this->assertEquals(['a' => 1, 'b' => 2, 'c' => 3], $collection->toArray());
  1678. }
  1679. /**
  1680. * Tests the stopWhen method with a matching array
  1681. *
  1682. * @return void
  1683. */
  1684. public function testStopWhenWithArray()
  1685. {
  1686. $items = [
  1687. ['foo' => 'bar'],
  1688. ['foo' => 'baz'],
  1689. ['foo' => 'foo'],
  1690. ];
  1691. $collection = (new Collection($items))->stopWhen(['foo' => 'baz']);
  1692. $this->assertEquals([['foo' => 'bar']], $collection->toArray());
  1693. }
  1694. /**
  1695. * Tests the unfold method
  1696. *
  1697. * @return void
  1698. */
  1699. public function testUnfold()
  1700. {
  1701. $items = [
  1702. [1, 2, 3, 4],
  1703. [5, 6],
  1704. [7, 8],
  1705. ];
  1706. $collection = (new Collection($items))->unfold();
  1707. $this->assertEquals(range(1, 8), $collection->toArray(false));
  1708. $items = [
  1709. [1, 2],
  1710. new Collection([3, 4]),
  1711. ];
  1712. $collection = (new Collection($items))->unfold();
  1713. $this->assertEquals(range(1, 4), $collection->toArray(false));
  1714. }
  1715. /**
  1716. * Tests the unfold method with empty levels
  1717. *
  1718. * @return void
  1719. */
  1720. public function testUnfoldEmptyLevels()
  1721. {
  1722. $items = [[], [1, 2], []];
  1723. $collection = (new Collection($items))->unfold();
  1724. $this->assertEquals(range(1, 2), $collection->toArray(false));
  1725. $items = [];
  1726. $collection = (new Collection($items))->unfold();
  1727. $this->assertEmpty($collection->toArray(false));
  1728. }
  1729. /**
  1730. * Tests the unfold when passing a callable
  1731. *
  1732. * @return void
  1733. */
  1734. public function testUnfoldWithCallable()
  1735. {
  1736. $items = [1, 2, 3];
  1737. $collection = (new Collection($items))->unfold(function ($item) {
  1738. return range($item, $item * 2);
  1739. });
  1740. $expected = [1, 2, 2, 3, 4, 3, 4, 5, 6];
  1741. $this->assertEquals($expected, $collection->toArray(false));
  1742. }
  1743. /**
  1744. * Tests the through() method
  1745. *
  1746. * @return void
  1747. */
  1748. public function testThrough()
  1749. {
  1750. $items = [1, 2, 3];
  1751. $collection = (new Collection($items))->through(function ($collection) {
  1752. return $collection->append($collection->toList());
  1753. });
  1754. $this->assertEquals([1, 2, 3, 1, 2, 3], $collection->toList());
  1755. }
  1756. /**
  1757. * Tests the through method when it returns an array
  1758. *
  1759. * @return void
  1760. */
  1761. public function testThroughReturnArray()
  1762. {
  1763. $items = [1, 2, 3];
  1764. $collection = (new Collection($items))->through(function ($collection) {
  1765. $list = $collection->toList();
  1766. return array_merge($list, $list);
  1767. });
  1768. $this->assertEquals([1, 2, 3, 1, 2, 3], $collection->toList());
  1769. }
  1770. /**
  1771. * Tests that the sortBy method does not die when something that is not a
  1772. * collection is passed
  1773. *
  1774. * @return void
  1775. */
  1776. public function testComplexSortBy()
  1777. {
  1778. $results = collection([3, 7])
  1779. ->unfold(function ($value) {
  1780. return [
  1781. ['sorting' => $value * 2],
  1782. ['sorting' => $value * 2],
  1783. ];
  1784. })
  1785. ->sortBy('sorting')
  1786. ->extract('sorting')
  1787. ->toList();
  1788. $this->assertEquals([14, 14, 6, 6], $results);
  1789. }
  1790. /**
  1791. * Tests __debugInfo() or debug() usage
  1792. *
  1793. * @return void
  1794. */
  1795. public function testDebug()
  1796. {
  1797. $items = [1, 2, 3];
  1798. $collection = new Collection($items);
  1799. $result = $collection->__debugInfo();
  1800. $expected = [
  1801. 'count' => 3,
  1802. ];
  1803. $this->assertSame($expected, $result);
  1804. // Calling it again will rewind
  1805. $result = $collection->__debugInfo();
  1806. $expected = [
  1807. 'count' => 3,
  1808. ];
  1809. $this->assertSame($expected, $result);
  1810. // Make sure it also works with non rewindable iterators
  1811. $iterator = new NoRewindIterator(new ArrayIterator($items));
  1812. $collection = new Collection($iterator);
  1813. $result = $collection->__debugInfo();
  1814. $expected = [
  1815. 'count' => 3,
  1816. ];
  1817. $this->assertSame($expected, $result);
  1818. // Calling it again will in this case not rewind
  1819. $result = $collection->__debugInfo();
  1820. $expected = [
  1821. 'count' => 0,
  1822. ];
  1823. $this->assertSame($expected, $result);
  1824. }
  1825. /**
  1826. * Tests the isEmpty() method
  1827. *
  1828. * @return void
  1829. */
  1830. public function testIsEmpty()
  1831. {
  1832. $collection = new Collection([1, 2, 3]);
  1833. $this->assertFalse($collection->isEmpty());
  1834. $collection = $collection->map(function () {
  1835. return null;
  1836. });
  1837. $this->assertFalse($collection->isEmpty());
  1838. $collection = $collection->filter();
  1839. $this->assertTrue($collection->isEmpty());
  1840. }
  1841. /**
  1842. * Tests the isEmpty() method does not consume data
  1843. * from buffered iterators.
  1844. *
  1845. * @return void
  1846. */
  1847. public function testIsEmptyDoesNotConsume()
  1848. {
  1849. $array = new \ArrayIterator([1, 2, 3]);
  1850. $inner = new \Cake\Collection\Iterator\BufferedIterator($array);
  1851. $collection = new Collection($inner);
  1852. $this->assertFalse($collection->isEmpty());
  1853. $this->assertCount(3, $collection->toArray());
  1854. }
  1855. /**
  1856. * Tests the zip() method
  1857. *
  1858. * @return void
  1859. */
  1860. public function testZip()
  1861. {
  1862. $collection = new Collection([1, 2]);
  1863. $zipped = $collection->zip([3, 4]);
  1864. $this->assertEquals([[1, 3], [2, 4]], $zipped->toList());
  1865. $collection = new Collection([1, 2]);
  1866. $zipped = $collection->zip([3]);
  1867. $this->assertEquals([[1, 3]], $zipped->toList());
  1868. $collection = new Collection([1, 2]);
  1869. $zipped = $collection->zip([3, 4], [5, 6], [7, 8], [9, 10, 11]);
  1870. $this->assertEquals([
  1871. [1, 3, 5, 7, 9],
  1872. [2, 4, 6, 8, 10],
  1873. ], $zipped->toList());
  1874. }
  1875. /**
  1876. * Tests the zipWith() method
  1877. *
  1878. * @return void
  1879. */
  1880. public function testZipWith()
  1881. {
  1882. $collection = new Collection([1, 2]);
  1883. $zipped = $collection->zipWith([3, 4], function ($a, $b) {
  1884. return $a * $b;
  1885. });
  1886. $this->assertEquals([3, 8], $zipped->toList());
  1887. $zipped = $collection->zipWith([3, 4], [5, 6, 7], function (...$args) {
  1888. return array_sum($args);
  1889. });
  1890. $this->assertEquals([9, 12], $zipped->toList());
  1891. }
  1892. /**
  1893. * Tests the skip() method
  1894. *
  1895. * @return void
  1896. */
  1897. public function testSkip()
  1898. {
  1899. $collection = new Collection([1, 2, 3, 4, 5]);
  1900. $this->assertEquals([3, 4, 5], $collection->skip(2)->toList());
  1901. $this->assertEquals([1, 2, 3, 4, 5], $collection->skip(0)->toList());
  1902. $this->assertEquals([4, 5], $collection->skip(3)->toList());
  1903. $this->assertEquals([5], $collection->skip(4)->toList());
  1904. }
  1905. /**
  1906. * Test skip() with an overflow
  1907. *
  1908. * @return void
  1909. */
  1910. public function testSkipOverflow()
  1911. {
  1912. $collection = new Collection([1, 2, 3]);
  1913. $this->assertEquals([], $collection->skip(3)->toArray());
  1914. $this->assertEquals([], $collection->skip(4)->toArray());
  1915. }
  1916. /**
  1917. * Tests the skip() method with a traversable non-iterator
  1918. *
  1919. * @return void
  1920. */
  1921. public function testSkipWithTraversableNonIterator()
  1922. {
  1923. $collection = new Collection($this->datePeriod('2017-01-01', '2017-01-07'));
  1924. $result = $collection->skip(3)->toList();
  1925. $expected = [
  1926. new \DateTime('2017-01-04'),
  1927. new \DateTime('2017-01-05'),
  1928. new \DateTime('2017-01-06'),
  1929. ];
  1930. $this->assertEquals($expected, $result);
  1931. }
  1932. /**
  1933. * Tests the first() method with a traversable non-iterator
  1934. *
  1935. * @return void
  1936. */
  1937. public function testFirstWithTraversableNonIterator()
  1938. {
  1939. $collection = new Collection($this->datePeriod('2017-01-01', '2017-01-07'));
  1940. $date = $collection->first();
  1941. $this->assertInstanceOf('DateTime', $date);
  1942. $this->assertSame('2017-01-01', $date->format('Y-m-d'));
  1943. }
  1944. /**
  1945. * Tests the last() method
  1946. *
  1947. * @return void
  1948. */
  1949. public function testLast()
  1950. {
  1951. $collection = new Collection([1, 2, 3]);
  1952. $this->assertSame(3, $collection->last());
  1953. $collection = $collection->map(function ($e) {
  1954. return $e * 2;
  1955. });
  1956. $this->assertSame(6, $collection->last());
  1957. }
  1958. /**
  1959. * Tests the last() method when on an empty collection
  1960. *
  1961. * @return void
  1962. */
  1963. public function testLastWithEmptyCollection()
  1964. {
  1965. $collection = new Collection([]);
  1966. $this->assertNull($collection->last());
  1967. }
  1968. /**
  1969. * Tests the last() method with a countable object
  1970. *
  1971. * @return void
  1972. */
  1973. public function testLastWithCountable()
  1974. {
  1975. $collection = new Collection(new ArrayObject([1, 2, 3]));
  1976. $this->assertSame(3, $collection->last());
  1977. }
  1978. /**
  1979. * Tests the last() method with an empty countable object
  1980. *
  1981. * @return void
  1982. */
  1983. public function testLastWithEmptyCountable()
  1984. {
  1985. $collection = new Collection(new ArrayObject([]));
  1986. $this->assertNull($collection->last());
  1987. }
  1988. /**
  1989. * Tests the last() method with a non-rewindable iterator
  1990. *
  1991. * @return void
  1992. */
  1993. public function testLastWithNonRewindableIterator()
  1994. {
  1995. $iterator = new NoRewindIterator(new ArrayIterator([1, 2, 3]));
  1996. $collection = new Collection($iterator);
  1997. $this->assertSame(3, $collection->last());
  1998. }
  1999. /**
  2000. * Tests the last() method with a traversable non-iterator
  2001. *
  2002. * @return void
  2003. */
  2004. public function testLastWithTraversableNonIterator()
  2005. {
  2006. $collection = new Collection($this->datePeriod('2017-01-01', '2017-01-07'));
  2007. $date = $collection->last();
  2008. $this->assertInstanceOf('DateTime', $date);
  2009. $this->assertSame('2017-01-06', $date->format('Y-m-d'));
  2010. }
  2011. /**
  2012. * Tests the takeLast() method
  2013. *
  2014. * @dataProvider simpleProvider
  2015. * @param array $data The data to test with.
  2016. * @return void
  2017. * @covers ::takeLast
  2018. */
  2019. public function testLastN($data)
  2020. {
  2021. $collection = new Collection($data);
  2022. $result = $collection->takeLast(3)->toArray();
  2023. $expected = ['b' => 2, 'c' => 3, 'd' => 4];
  2024. $this->assertEquals($expected, $result);
  2025. }
  2026. /**
  2027. * Tests the takeLast() method with overflow
  2028. *
  2029. * @dataProvider simpleProvider
  2030. * @param array $data The data to test with.
  2031. * @return void
  2032. * @covers ::takeLast
  2033. */
  2034. public function testLastNtWithOverflow($data)
  2035. {
  2036. $collection = new Collection($data);
  2037. $result = $collection->takeLast(10)->toArray();
  2038. $expected = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4];
  2039. $this->assertEquals($expected, $result);
  2040. }
  2041. /**
  2042. * Tests the takeLast() with an odd numbers collection
  2043. *
  2044. * @dataProvider simpleProvider
  2045. * @param array $data The data to test with.
  2046. * @return void
  2047. * @covers ::takeLast
  2048. */
  2049. public function testLastNtWithOddData($data)
  2050. {
  2051. $collection = new Collection($data);
  2052. $result = $collection->take(3)->takeLast(2)->toArray();
  2053. $expected = ['b' => 2, 'c' => 3];
  2054. $this->assertEquals($expected, $result);
  2055. }
  2056. /**
  2057. * Tests the takeLast() with countable collection
  2058. *
  2059. * @return void
  2060. * @covers ::takeLast
  2061. */
  2062. public function testLastNtWithCountable()
  2063. {
  2064. $rangeZeroToFive = range(0, 5);
  2065. $collection = new Collection(new CountableIterator($rangeZeroToFive));
  2066. $result = $collection->takeLast(2)->toList();
  2067. $this->assertEquals([4, 5], $result);
  2068. $collection = new Collection(new CountableIterator($rangeZeroToFive));
  2069. $result = $collection->takeLast(1)->toList();
  2070. $this->assertEquals([5], $result);
  2071. }
  2072. /**
  2073. * Tests the takeLast() with countable collection
  2074. *
  2075. * @dataProvider simpleProvider
  2076. * @param array $data The data to test with.
  2077. * @return void
  2078. * @covers ::takeLast
  2079. */
  2080. public function testLastNtWithNegative($data)
  2081. {
  2082. $collection = new Collection($data);
  2083. $this->expectException(\InvalidArgumentException::class);
  2084. $this->expectExceptionMessage('The takeLast method requires a number greater than 0.');
  2085. $collection->takeLast(-1)->toArray();
  2086. }
  2087. /**
  2088. * Tests sumOf with no parameters
  2089. *
  2090. * @return void
  2091. */
  2092. public function testSumOfWithIdentity()
  2093. {
  2094. $collection = new Collection([1, 2, 3]);
  2095. $this->assertSame(6, $collection->sumOf());
  2096. $collection = new Collection(['a' => 1, 'b' => 4, 'c' => 6]);
  2097. $this->assertSame(11, $collection->sumOf());
  2098. }
  2099. /**
  2100. * Tests using extract with the {*} notation
  2101. *
  2102. * @return void
  2103. */
  2104. public function testUnfoldedExtract()
  2105. {
  2106. $items = [
  2107. ['comments' => [['id' => 1], ['id' => 2]]],
  2108. ['comments' => [['id' => 3], ['id' => 4]]],
  2109. ['comments' => [['id' => 7], ['nope' => 8]]],
  2110. ];
  2111. $extracted = (new Collection($items))->extract('comments.{*}.id');
  2112. $this->assertEquals([1, 2, 3, 4, 7, null], $extracted->toArray());
  2113. $items = [
  2114. [
  2115. 'comments' => [
  2116. [
  2117. 'voters' => [['id' => 1], ['id' => 2]],
  2118. ],
  2119. ],
  2120. ],
  2121. [
  2122. 'comments' => [
  2123. [
  2124. 'voters' => [['id' => 3], ['id' => 4]],
  2125. ],
  2126. ],
  2127. ],
  2128. [
  2129. 'comments' => [
  2130. [
  2131. 'voters' => [['id' => 5], ['nope' => 'fail'], ['id' => 6]],
  2132. ],
  2133. ],
  2134. ],
  2135. [
  2136. 'comments' => [
  2137. [
  2138. 'not_voters' => [['id' => 5]],
  2139. ],
  2140. ],
  2141. ],
  2142. ['not_comments' => []],
  2143. ];
  2144. $extracted = (new Collection($items))->extract('comments.{*}.voters.{*}.id');
  2145. $expected = [1, 2, 3, 4, 5, null, 6];
  2146. $this->assertEquals($expected, $extracted->toArray());
  2147. $this->assertEquals($expected, $extracted->toList());
  2148. }
  2149. /**
  2150. * Tests serializing a simple collection
  2151. *
  2152. * @return void
  2153. */
  2154. public function testSerializeSimpleCollection()
  2155. {
  2156. $collection = new Collection([1, 2, 3]);
  2157. $serialized = serialize($collection);
  2158. $unserialized = unserialize($serialized);
  2159. $this->assertEquals($collection->toList(), $unserialized->toList());
  2160. $this->assertEquals($collection->toArray(), $unserialized->toArray());
  2161. }
  2162. /**
  2163. * Tests serialization when using append
  2164. *
  2165. * @return void
  2166. */
  2167. public function testSerializeWithAppendIterators()
  2168. {
  2169. $collection = new Collection([1, 2, 3]);
  2170. $collection = $collection->append(['a' => 4, 'b' => 5, 'c' => 6]);
  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 serialization when using nested iterators
  2178. *
  2179. * @return void
  2180. */
  2181. public function testSerializeWithNestedIterators()
  2182. {
  2183. $collection = new Collection([1, 2, 3]);
  2184. $collection = $collection->map(function ($e) {
  2185. return $e * 3;
  2186. });
  2187. $collection = $collection->groupBy(function ($e) {
  2188. return $e % 2;
  2189. });
  2190. $serialized = serialize($collection);
  2191. $unserialized = unserialize($serialized);
  2192. $this->assertEquals($collection->toList(), $unserialized->toList());
  2193. $this->assertEquals($collection->toArray(), $unserialized->toArray());
  2194. }
  2195. /**
  2196. * Tests serializing a zip() call
  2197. *
  2198. * @return void
  2199. */
  2200. public function testSerializeWithZipIterator()
  2201. {
  2202. $collection = new Collection([4, 5]);
  2203. $collection = $collection->zip([1, 2]);
  2204. $serialized = serialize($collection);
  2205. $unserialized = unserialize($serialized);
  2206. $this->assertEquals($collection->toList(), $unserialized->toList());
  2207. }
  2208. /**
  2209. * Provider for some chunk tests
  2210. *
  2211. * @return array
  2212. */
  2213. public function chunkProvider()
  2214. {
  2215. $items = range(1, 10);
  2216. return [
  2217. 'array' => [$items],
  2218. 'iterator' => [$this->yieldItems($items)],
  2219. ];
  2220. }
  2221. /**
  2222. * Tests the chunk method with exact chunks
  2223. *
  2224. * @dataProvider chunkProvider
  2225. * @return void
  2226. */
  2227. public function testChunk($items)
  2228. {
  2229. $collection = new Collection($items);
  2230. $chunked = $collection->chunk(2)->toList();
  2231. $expected = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]];
  2232. $this->assertEquals($expected, $chunked);
  2233. }
  2234. /**
  2235. * Tests the chunk method with overflowing chunk size
  2236. *
  2237. * @return void
  2238. */
  2239. public function testChunkOverflow()
  2240. {
  2241. $collection = new Collection(range(1, 11));
  2242. $chunked = $collection->chunk(2)->toList();
  2243. $expected = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11]];
  2244. $this->assertEquals($expected, $chunked);
  2245. }
  2246. /**
  2247. * Tests the chunk method with non-scalar items
  2248. *
  2249. * @return void
  2250. */
  2251. public function testChunkNested()
  2252. {
  2253. $collection = new Collection([1, 2, 3, [4, 5], 6, [7, [8, 9], 10], 11]);
  2254. $chunked = $collection->chunk(2)->toList();
  2255. $expected = [[1, 2], [3, [4, 5]], [6, [7, [8, 9], 10]], [11]];
  2256. $this->assertEquals($expected, $chunked);
  2257. }
  2258. /**
  2259. * Tests the chunkWithKeys method with exact chunks
  2260. *
  2261. * @return void
  2262. */
  2263. public function testChunkWithKeys()
  2264. {
  2265. $collection = new Collection(['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6]);
  2266. $chunked = $collection->chunkWithKeys(2)->toList();
  2267. $expected = [['a' => 1, 'b' => 2], ['c' => 3, 'd' => 4], ['e' => 5, 'f' => 6]];
  2268. $this->assertEquals($expected, $chunked);
  2269. }
  2270. /**
  2271. * Tests the chunkWithKeys method with overflowing chunk size
  2272. *
  2273. * @return void
  2274. */
  2275. public function testChunkWithKeysOverflow()
  2276. {
  2277. $collection = new Collection(['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6, 'g' => 7]);
  2278. $chunked = $collection->chunkWithKeys(2)->toList();
  2279. $expected = [['a' => 1, 'b' => 2], ['c' => 3, 'd' => 4], ['e' => 5, 'f' => 6], ['g' => 7]];
  2280. $this->assertEquals($expected, $chunked);
  2281. }
  2282. /**
  2283. * Tests the chunkWithKeys method with non-scalar items
  2284. *
  2285. * @return void
  2286. */
  2287. public function testChunkWithKeysNested()
  2288. {
  2289. $collection = new Collection(['a' => 1, 'b' => 2, 'c' => 3, 'd' => [4, 5], 'e' => 6, 'f' => [7, [8, 9], 10], 'g' => 11]);
  2290. $chunked = $collection->chunkWithKeys(2)->toList();
  2291. $expected = [['a' => 1, 'b' => 2], ['c' => 3, 'd' => [4, 5]], ['e' => 6, 'f' => [7, [8, 9], 10]], ['g' => 11]];
  2292. $this->assertEquals($expected, $chunked);
  2293. }
  2294. /**
  2295. * Tests the chunkWithKeys method without preserving keys
  2296. *
  2297. * @return void
  2298. */
  2299. public function testChunkWithKeysNoPreserveKeys()
  2300. {
  2301. $collection = new Collection(['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6, 'g' => 7]);
  2302. $chunked = $collection->chunkWithKeys(2, false)->toList();
  2303. $expected = [[0 => 1, 1 => 2], [0 => 3, 1 => 4], [0 => 5, 1 => 6], [0 => 7]];
  2304. $this->assertEquals($expected, $chunked);
  2305. }
  2306. /**
  2307. * Tests cartesianProduct
  2308. *
  2309. * @return void
  2310. */
  2311. public function testCartesianProduct()
  2312. {
  2313. $collection = new Collection([]);
  2314. $result = $collection->cartesianProduct();
  2315. $expected = [];
  2316. $this->assertEquals($expected, $result->toList());
  2317. $collection = new Collection([['A', 'B', 'C'], [1, 2, 3]]);
  2318. $result = $collection->cartesianProduct();
  2319. $expected = [
  2320. ['A', 1],
  2321. ['A', 2],
  2322. ['A', 3],
  2323. ['B', 1],
  2324. ['B', 2],
  2325. ['B', 3],
  2326. ['C', 1],
  2327. ['C', 2],
  2328. ['C', 3],
  2329. ];
  2330. $this->assertEquals($expected, $result->toList());
  2331. $collection = new Collection([[1, 2, 3], ['A', 'B', 'C'], ['a', 'b', 'c']]);
  2332. $result = $collection->cartesianProduct(function ($value) {
  2333. return [strval($value[0]) . $value[1] . $value[2]];
  2334. }, function ($value) {
  2335. return $value[0] >= 2;
  2336. });
  2337. $expected = [
  2338. ['2Aa'],
  2339. ['2Ab'],
  2340. ['2Ac'],
  2341. ['2Ba'],
  2342. ['2Bb'],
  2343. ['2Bc'],
  2344. ['2Ca'],
  2345. ['2Cb'],
  2346. ['2Cc'],
  2347. ['3Aa'],
  2348. ['3Ab'],
  2349. ['3Ac'],
  2350. ['3Ba'],
  2351. ['3Bb'],
  2352. ['3Bc'],
  2353. ['3Ca'],
  2354. ['3Cb'],
  2355. ['3Cc'],
  2356. ];
  2357. $this->assertEquals($expected, $result->toList());
  2358. $collection = new Collection([['1', '2', '3', '4'], ['A', 'B', 'C'], ['name', 'surname', 'telephone']]);
  2359. $result = $collection->cartesianProduct(function ($value) {
  2360. return [$value[0] => [$value[1] => $value[2]]];
  2361. }, function ($value) {
  2362. return $value[2] !== 'surname';
  2363. });
  2364. $expected = [
  2365. [1 => ['A' => 'name']],
  2366. [1 => ['A' => 'telephone']],
  2367. [1 => ['B' => 'name']],
  2368. [1 => ['B' => 'telephone']],
  2369. [1 => ['C' => 'name']],
  2370. [1 => ['C' => 'telephone']],
  2371. [2 => ['A' => 'name']],
  2372. [2 => ['A' => 'telephone']],
  2373. [2 => ['B' => 'name']],
  2374. [2 => ['B' => 'telephone']],
  2375. [2 => ['C' => 'name']],
  2376. [2 => ['C' => 'telephone']],
  2377. [3 => ['A' => 'name']],
  2378. [3 => ['A' => 'telephone']],
  2379. [3 => ['B' => 'name']],
  2380. [3 => ['B' => 'telephone']],
  2381. [3 => ['C' => 'name']],
  2382. [3 => ['C' => 'telephone']],
  2383. [4 => ['A' => 'name']],
  2384. [4 => ['A' => 'telephone']],
  2385. [4 => ['B' => 'name']],
  2386. [4 => ['B' => 'telephone']],
  2387. [4 => ['C' => 'name']],
  2388. [4 => ['C' => 'telephone']],
  2389. ];
  2390. $this->assertEquals($expected, $result->toList());
  2391. $collection = new Collection([
  2392. [
  2393. 'name1' => 'alex',
  2394. 'name2' => 'kostas',
  2395. 0 => 'leon',
  2396. ],
  2397. [
  2398. 'val1' => 'alex@example.com',
  2399. 24 => 'kostas@example.com',
  2400. 'val2' => 'leon@example.com',
  2401. ],
  2402. ]);
  2403. $result = $collection->cartesianProduct();
  2404. $expected = [
  2405. ['alex', 'alex@example.com'],
  2406. ['alex', 'kostas@example.com'],
  2407. ['alex', 'leon@example.com'],
  2408. ['kostas', 'alex@example.com'],
  2409. ['kostas', 'kostas@example.com'],
  2410. ['kostas', 'leon@example.com'],
  2411. ['leon', 'alex@example.com'],
  2412. ['leon', 'kostas@example.com'],
  2413. ['leon', 'leon@example.com'],
  2414. ];
  2415. $this->assertEquals($expected, $result->toList());
  2416. }
  2417. /**
  2418. * Tests that an exception is thrown if the cartesian product is called with multidimensional arrays
  2419. *
  2420. * @return void
  2421. */
  2422. public function testCartesianProductMultidimensionalArray()
  2423. {
  2424. $this->expectException(\LogicException::class);
  2425. $collection = new Collection([
  2426. [
  2427. 'names' => [
  2428. 'alex', 'kostas', 'leon',
  2429. ],
  2430. ],
  2431. [
  2432. 'locations' => [
  2433. 'crete', 'london', 'paris',
  2434. ],
  2435. ],
  2436. ]);
  2437. $result = $collection->cartesianProduct();
  2438. }
  2439. public function testTranspose()
  2440. {
  2441. $collection = new Collection([
  2442. ['Products', '2012', '2013', '2014'],
  2443. ['Product A', '200', '100', '50'],
  2444. ['Product B', '300', '200', '100'],
  2445. ['Product C', '400', '300', '200'],
  2446. ['Product D', '500', '400', '300'],
  2447. ]);
  2448. $transposed = $collection->transpose();
  2449. $expected = [
  2450. ['Products', 'Product A', 'Product B', 'Product C', 'Product D'],
  2451. ['2012', '200', '300', '400', '500'],
  2452. ['2013', '100', '200', '300', '400'],
  2453. ['2014', '50', '100', '200', '300'],
  2454. ];
  2455. $this->assertEquals($expected, $transposed->toList());
  2456. }
  2457. /**
  2458. * Tests that provided arrays do not have even length
  2459. *
  2460. * @return void
  2461. */
  2462. public function testTransposeUnEvenLengthShouldThrowException()
  2463. {
  2464. $this->expectException(\LogicException::class);
  2465. $collection = new Collection([
  2466. ['Products', '2012', '2013', '2014'],
  2467. ['Product A', '200', '100', '50'],
  2468. ['Product B', '300'],
  2469. ['Product C', '400', '300'],
  2470. ]);
  2471. $collection->transpose();
  2472. }
  2473. /**
  2474. * Yields all the elements as passed
  2475. *
  2476. * @param array $items the elements to be yielded
  2477. * @return \Generator<array>
  2478. */
  2479. protected function yieldItems(array $items)
  2480. {
  2481. foreach ($items as $k => $v) {
  2482. yield $k => $v;
  2483. }
  2484. }
  2485. /**
  2486. * Create a DatePeriod object.
  2487. *
  2488. * @param string $start Start date
  2489. * @param string $end End date
  2490. * @return \DatePeriod
  2491. */
  2492. protected function datePeriod($start, $end)
  2493. {
  2494. return new \DatePeriod(new \DateTime($start), new \DateInterval('P1D'), new \DateTime($end));
  2495. }
  2496. /**
  2497. * Tests to ensure that collection classes extending ArrayIterator work as expected.
  2498. *
  2499. * @return void
  2500. */
  2501. public function testArrayIteratorExtend()
  2502. {
  2503. $iterator = new TestIterator(range(0, 10));
  2504. $this->assertTrue(method_exists($iterator, 'checkValues'));
  2505. $this->assertTrue($iterator->checkValues());
  2506. //We need to perform at least two collection operation to trigger the issue.
  2507. $newIterator = $iterator
  2508. ->filter(function ($item) {
  2509. return $item < 5;
  2510. })
  2511. ->reject(function ($item) {
  2512. return $item > 2;
  2513. });
  2514. $this->assertTrue(method_exists($newIterator, 'checkValues'), 'Our method has gone missing!');
  2515. $this->assertTrue($newIterator->checkValues());
  2516. $this->assertCount(3, $newIterator->toArray());
  2517. }
  2518. /**
  2519. * Tests that elements in a lazy collection are not fetched immediately.
  2520. *
  2521. * @return void
  2522. */
  2523. public function testLazy()
  2524. {
  2525. $items = ['a' => 1, 'b' => 2, 'c' => 3];
  2526. $collection = (new Collection($items))->lazy();
  2527. $callable = $this->getMockBuilder(stdClass::class)
  2528. ->addMethods(['__invoke'])
  2529. ->getMock();
  2530. $callable->expects($this->never())->method('__invoke');
  2531. $collection->filter($callable)->filter($callable);
  2532. }
  2533. }