CollectionTest.php 78 KB

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