CollectionTest.php 81 KB

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