CollectionTest.php 74 KB

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