CollectionTest.php 69 KB

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