CollectionTest.php 79 KB

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