CollectionTest.php 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://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. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since 3.0.0
  13. * @license http://www.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. */
  42. class CollectionTest extends TestCase
  43. {
  44. /**
  45. * Tests that it is possible to convert an array into a collection
  46. *
  47. * @return void
  48. */
  49. public function testArrayIsWrapped()
  50. {
  51. $items = [1, 2, 3];
  52. $collection = new Collection($items);
  53. $this->assertEquals($items, iterator_to_array($collection));
  54. }
  55. /**
  56. * Tests that it is possible to convert an iterator into a collection
  57. *
  58. * @return void
  59. */
  60. public function testIteratorIsWrapped()
  61. {
  62. $items = new \ArrayObject([1, 2, 3]);
  63. $collection = new Collection($items);
  64. $this->assertEquals(iterator_to_array($items), iterator_to_array($collection));
  65. }
  66. /**
  67. * Test running a method over all elements in the collection
  68. *
  69. * @return void
  70. */
  71. public function testEeach()
  72. {
  73. $items = ['a' => 1, 'b' => 2, 'c' => 3];
  74. $collection = new Collection($items);
  75. $callable = $this->getMockBuilder(\StdClass::class)
  76. ->setMethods(['__invoke'])
  77. ->getMock();
  78. $callable->expects($this->at(0))
  79. ->method('__invoke')
  80. ->with(1, 'a');
  81. $callable->expects($this->at(1))
  82. ->method('__invoke')
  83. ->with(2, 'b');
  84. $callable->expects($this->at(2))
  85. ->method('__invoke')
  86. ->with(3, 'c');
  87. $collection->each($callable);
  88. }
  89. /**
  90. * Test filter() with no callback.
  91. *
  92. * @return void
  93. */
  94. public function testFilterNoCallback()
  95. {
  96. $items = [1, 2, 0, 3, false, 4, null, 5, ''];
  97. $collection = new Collection($items);
  98. $result = $collection->filter()->toArray();
  99. $expected = [1, 2, 3, 4, 5];
  100. $this->assertEquals($expected, array_values($result));
  101. }
  102. /**
  103. * Tests that it is possible to chain filter() as it returns a collection object
  104. *
  105. * @return void
  106. */
  107. public function testFilterChaining()
  108. {
  109. $items = ['a' => 1, 'b' => 2, 'c' => 3];
  110. $collection = new Collection($items);
  111. $callable = $this->getMockBuilder(\StdClass::class)
  112. ->setMethods(['__invoke'])
  113. ->getMock();
  114. $callable->expects($this->once())
  115. ->method('__invoke')
  116. ->with(3, 'c');
  117. $filtered = $collection->filter(function ($value, $key, $iterator) {
  118. return $value > 2;
  119. });
  120. $this->assertInstanceOf('Cake\Collection\Collection', $filtered);
  121. $filtered->each($callable);
  122. }
  123. /**
  124. * Tests reject
  125. *
  126. * @return void
  127. */
  128. public function testReject()
  129. {
  130. $items = ['a' => 1, 'b' => 2, 'c' => 3];
  131. $collection = new Collection($items);
  132. $result = $collection->reject(function ($v, $k, $items) use ($collection) {
  133. $this->assertSame($collection->getInnerIterator(), $items);
  134. return $v > 2;
  135. });
  136. $this->assertEquals(['a' => 1, 'b' => 2], iterator_to_array($result));
  137. $this->assertInstanceOf('Cake\Collection\Collection', $result);
  138. }
  139. /**
  140. * Tests every when the callback returns true for all elements
  141. *
  142. * @return void
  143. */
  144. public function testEveryReturnTrue()
  145. {
  146. $items = ['a' => 1, 'b' => 2, 'c' => 3];
  147. $collection = new Collection($items);
  148. $callable = $this->getMockBuilder(\StdClass::class)
  149. ->setMethods(['__invoke'])
  150. ->getMock();
  151. $callable->expects($this->at(0))
  152. ->method('__invoke')
  153. ->with(1, 'a')
  154. ->will($this->returnValue(true));
  155. $callable->expects($this->at(1))
  156. ->method('__invoke')
  157. ->with(2, 'b')
  158. ->will($this->returnValue(true));
  159. $callable->expects($this->at(2))
  160. ->method('__invoke')
  161. ->with(3, 'c')
  162. ->will($this->returnValue(true));
  163. $this->assertTrue($collection->every($callable));
  164. }
  165. /**
  166. * Tests every when the callback returns false for one of the elements
  167. *
  168. * @return void
  169. */
  170. public function testEveryReturnFalse()
  171. {
  172. $items = ['a' => 1, 'b' => 2, 'c' => 3];
  173. $collection = new Collection($items);
  174. $callable = $this->getMockBuilder(\StdClass::class)
  175. ->setMethods(['__invoke'])
  176. ->getMock();
  177. $callable->expects($this->at(0))
  178. ->method('__invoke')
  179. ->with(1, 'a')
  180. ->will($this->returnValue(true));
  181. $callable->expects($this->at(1))
  182. ->method('__invoke')
  183. ->with(2, 'b')
  184. ->will($this->returnValue(false));
  185. $callable->expects($this->exactly(2))->method('__invoke');
  186. $this->assertFalse($collection->every($callable));
  187. $items = [];
  188. $collection = new Collection($items);
  189. $callable = $this->getMockBuilder(\StdClass::class)
  190. ->setMethods(['__invoke'])
  191. ->getMock();
  192. $callable->expects($this->never())
  193. ->method('__invoke');
  194. $this->assertFalse($collection->every($callable));
  195. }
  196. /**
  197. * Tests some() when one of the calls return true
  198. *
  199. * @return void
  200. */
  201. public function testSomeReturnTrue()
  202. {
  203. $items = ['a' => 1, 'b' => 2, 'c' => 3];
  204. $collection = new Collection($items);
  205. $callable = $this->getMockBuilder(\StdClass::class)
  206. ->setMethods(['__invoke'])
  207. ->getMock();
  208. $callable->expects($this->at(0))
  209. ->method('__invoke')
  210. ->with(1, 'a')
  211. ->will($this->returnValue(false));
  212. $callable->expects($this->at(1))
  213. ->method('__invoke')
  214. ->with(2, 'b')
  215. ->will($this->returnValue(true));
  216. $callable->expects($this->exactly(2))->method('__invoke');
  217. $this->assertTrue($collection->some($callable));
  218. }
  219. /**
  220. * Tests some() when none of the calls return true
  221. *
  222. * @return void
  223. */
  224. public function testSomeReturnFalse()
  225. {
  226. $items = ['a' => 1, 'b' => 2, 'c' => 3];
  227. $collection = new Collection($items);
  228. $callable = $this->getMockBuilder(\StdClass::class)
  229. ->setMethods(['__invoke'])
  230. ->getMock();
  231. $callable->expects($this->at(0))
  232. ->method('__invoke')
  233. ->with(1, 'a')
  234. ->will($this->returnValue(false));
  235. $callable->expects($this->at(1))
  236. ->method('__invoke')
  237. ->with(2, 'b')
  238. ->will($this->returnValue(false));
  239. $callable->expects($this->at(2))
  240. ->method('__invoke')
  241. ->with(3, 'c')
  242. ->will($this->returnValue(false));
  243. $this->assertFalse($collection->some($callable));
  244. }
  245. /**
  246. * Tests contains
  247. *
  248. * @return void
  249. */
  250. public function testContains()
  251. {
  252. $items = ['a' => 1, 'b' => 2, 'c' => 3];
  253. $collection = new Collection($items);
  254. $this->assertTrue($collection->contains(2));
  255. $this->assertTrue($collection->contains(1));
  256. $this->assertFalse($collection->contains(10));
  257. $this->assertFalse($collection->contains('2'));
  258. }
  259. /**
  260. * Tests map
  261. *
  262. * @return void
  263. */
  264. public function testMap()
  265. {
  266. $items = ['a' => 1, 'b' => 2, 'c' => 3];
  267. $collection = new Collection($items);
  268. $map = $collection->map(function ($v, $k, $it) use ($collection) {
  269. $this->assertSame($collection->getInnerIterator(), $it);
  270. return $v * $v;
  271. });
  272. $this->assertInstanceOf('Cake\Collection\Iterator\ReplaceIterator', $map);
  273. $this->assertEquals(['a' => 1, 'b' => 4, 'c' => 9], iterator_to_array($map));
  274. }
  275. /**
  276. * Tests reduce with initial value
  277. *
  278. * @return void
  279. */
  280. public function testReduceWithInitialValue()
  281. {
  282. $items = ['a' => 1, 'b' => 2, 'c' => 3];
  283. $collection = new Collection($items);
  284. $callable = $this->getMockBuilder(\StdClass::class)
  285. ->setMethods(['__invoke'])
  286. ->getMock();
  287. $callable->expects($this->at(0))
  288. ->method('__invoke')
  289. ->with(10, 1, 'a')
  290. ->will($this->returnValue(11));
  291. $callable->expects($this->at(1))
  292. ->method('__invoke')
  293. ->with(11, 2, 'b')
  294. ->will($this->returnValue(13));
  295. $callable->expects($this->at(2))
  296. ->method('__invoke')
  297. ->with(13, 3, 'c')
  298. ->will($this->returnValue(16));
  299. $this->assertEquals(16, $collection->reduce($callable, 10));
  300. }
  301. /**
  302. * Tests reduce without initial value
  303. *
  304. * @return void
  305. */
  306. public function testReduceWithoutInitialValue()
  307. {
  308. $items = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4];
  309. $collection = new Collection($items);
  310. $callable = $this->getMockBuilder(\StdClass::class)
  311. ->setMethods(['__invoke'])
  312. ->getMock();
  313. $callable->expects($this->at(0))
  314. ->method('__invoke')
  315. ->with(1, 2, 'b')
  316. ->will($this->returnValue(3));
  317. $callable->expects($this->at(1))
  318. ->method('__invoke')
  319. ->with(3, 3, 'c')
  320. ->will($this->returnValue(6));
  321. $callable->expects($this->at(2))
  322. ->method('__invoke')
  323. ->with(6, 4, 'd')
  324. ->will($this->returnValue(10));
  325. $this->assertEquals(10, $collection->reduce($callable));
  326. }
  327. /**
  328. * Tests extract
  329. *
  330. * @return void
  331. */
  332. public function testExtract()
  333. {
  334. $items = [['a' => ['b' => ['c' => 1]]], 2];
  335. $collection = new Collection($items);
  336. $map = $collection->extract('a.b.c');
  337. $this->assertInstanceOf('Cake\Collection\Iterator\ExtractIterator', $map);
  338. $this->assertEquals([1, null], iterator_to_array($map));
  339. }
  340. /**
  341. * Tests sort
  342. *
  343. * @return void
  344. */
  345. public function testSortString()
  346. {
  347. $items = [
  348. ['a' => ['b' => ['c' => 4]]],
  349. ['a' => ['b' => ['c' => 10]]],
  350. ['a' => ['b' => ['c' => 6]]]
  351. ];
  352. $collection = new Collection($items);
  353. $map = $collection->sortBy('a.b.c');
  354. $this->assertInstanceOf('Cake\Collection\Collection', $map);
  355. $expected = [
  356. ['a' => ['b' => ['c' => 10]]],
  357. ['a' => ['b' => ['c' => 6]]],
  358. ['a' => ['b' => ['c' => 4]]],
  359. ];
  360. $this->assertEquals($expected, $map->toList());
  361. }
  362. /**
  363. * Tests max
  364. *
  365. * @return void
  366. */
  367. public function testMax()
  368. {
  369. $items = [
  370. ['a' => ['b' => ['c' => 4]]],
  371. ['a' => ['b' => ['c' => 10]]],
  372. ['a' => ['b' => ['c' => 6]]]
  373. ];
  374. $collection = new Collection($items);
  375. $this->assertEquals(['a' => ['b' => ['c' => 10]]], $collection->max('a.b.c'));
  376. $callback = function ($e) {
  377. return $e['a']['b']['c'] * - 1;
  378. };
  379. $this->assertEquals(['a' => ['b' => ['c' => 4]]], $collection->max($callback));
  380. }
  381. /**
  382. * Tests min
  383. *
  384. * @return void
  385. */
  386. public function testMin()
  387. {
  388. $items = [
  389. ['a' => ['b' => ['c' => 4]]],
  390. ['a' => ['b' => ['c' => 10]]],
  391. ['a' => ['b' => ['c' => 6]]]
  392. ];
  393. $collection = new Collection($items);
  394. $this->assertEquals(['a' => ['b' => ['c' => 4]]], $collection->min('a.b.c'));
  395. }
  396. /**
  397. * Tests groupBy
  398. *
  399. * @return void
  400. */
  401. public function testGroupBy()
  402. {
  403. $items = [
  404. ['id' => 1, 'name' => 'foo', 'parent_id' => 10],
  405. ['id' => 2, 'name' => 'bar', 'parent_id' => 11],
  406. ['id' => 3, 'name' => 'baz', 'parent_id' => 10],
  407. ];
  408. $collection = new Collection($items);
  409. $grouped = $collection->groupBy('parent_id');
  410. $expected = [
  411. 10 => [
  412. ['id' => 1, 'name' => 'foo', 'parent_id' => 10],
  413. ['id' => 3, 'name' => 'baz', 'parent_id' => 10],
  414. ],
  415. 11 => [
  416. ['id' => 2, 'name' => 'bar', 'parent_id' => 11],
  417. ]
  418. ];
  419. $this->assertEquals($expected, iterator_to_array($grouped));
  420. $this->assertInstanceOf('Cake\Collection\Collection', $grouped);
  421. $grouped = $collection->groupBy(function ($element) {
  422. return $element['parent_id'];
  423. });
  424. $this->assertEquals($expected, iterator_to_array($grouped));
  425. }
  426. /**
  427. * Tests grouping by a deep key
  428. *
  429. * @return void
  430. */
  431. public function testGroupByDeepKey()
  432. {
  433. $items = [
  434. ['id' => 1, 'name' => 'foo', 'thing' => ['parent_id' => 10]],
  435. ['id' => 2, 'name' => 'bar', 'thing' => ['parent_id' => 11]],
  436. ['id' => 3, 'name' => 'baz', 'thing' => ['parent_id' => 10]],
  437. ];
  438. $collection = new Collection($items);
  439. $grouped = $collection->groupBy('thing.parent_id');
  440. $expected = [
  441. 10 => [
  442. ['id' => 1, 'name' => 'foo', 'thing' => ['parent_id' => 10]],
  443. ['id' => 3, 'name' => 'baz', 'thing' => ['parent_id' => 10]],
  444. ],
  445. 11 => [
  446. ['id' => 2, 'name' => 'bar', 'thing' => ['parent_id' => 11]],
  447. ]
  448. ];
  449. $this->assertEquals($expected, iterator_to_array($grouped));
  450. }
  451. /**
  452. * Tests indexBy
  453. *
  454. * @return void
  455. */
  456. public function testIndexBy()
  457. {
  458. $items = [
  459. ['id' => 1, 'name' => 'foo', 'parent_id' => 10],
  460. ['id' => 2, 'name' => 'bar', 'parent_id' => 11],
  461. ['id' => 3, 'name' => 'baz', 'parent_id' => 10],
  462. ];
  463. $collection = new Collection($items);
  464. $grouped = $collection->indexBy('id');
  465. $expected = [
  466. 1 => ['id' => 1, 'name' => 'foo', 'parent_id' => 10],
  467. 3 => ['id' => 3, 'name' => 'baz', 'parent_id' => 10],
  468. 2 => ['id' => 2, 'name' => 'bar', 'parent_id' => 11],
  469. ];
  470. $this->assertEquals($expected, iterator_to_array($grouped));
  471. $this->assertInstanceOf('Cake\Collection\Collection', $grouped);
  472. $grouped = $collection->indexBy(function ($element) {
  473. return $element['id'];
  474. });
  475. $this->assertEquals($expected, iterator_to_array($grouped));
  476. }
  477. /**
  478. * Tests indexBy with a deep property
  479. *
  480. * @return void
  481. */
  482. public function testIndexByDeep()
  483. {
  484. $items = [
  485. ['id' => 1, 'name' => 'foo', 'thing' => ['parent_id' => 10]],
  486. ['id' => 2, 'name' => 'bar', 'thing' => ['parent_id' => 11]],
  487. ['id' => 3, 'name' => 'baz', 'thing' => ['parent_id' => 10]],
  488. ];
  489. $collection = new Collection($items);
  490. $grouped = $collection->indexBy('thing.parent_id');
  491. $expected = [
  492. 10 => ['id' => 3, 'name' => 'baz', 'thing' => ['parent_id' => 10]],
  493. 11 => ['id' => 2, 'name' => 'bar', 'thing' => ['parent_id' => 11]],
  494. ];
  495. $this->assertEquals($expected, iterator_to_array($grouped));
  496. }
  497. /**
  498. * Tests countBy
  499. *
  500. * @return void
  501. */
  502. public function testCountBy()
  503. {
  504. $items = [
  505. ['id' => 1, 'name' => 'foo', 'parent_id' => 10],
  506. ['id' => 2, 'name' => 'bar', 'parent_id' => 11],
  507. ['id' => 3, 'name' => 'baz', 'parent_id' => 10],
  508. ];
  509. $collection = new Collection($items);
  510. $grouped = $collection->countBy('parent_id');
  511. $expected = [
  512. 10 => 2,
  513. 11 => 1
  514. ];
  515. $this->assertEquals($expected, iterator_to_array($grouped));
  516. $this->assertInstanceOf('Cake\Collection\Collection', $grouped);
  517. $grouped = $collection->countBy(function ($element) {
  518. return $element['parent_id'];
  519. });
  520. $this->assertEquals($expected, iterator_to_array($grouped));
  521. }
  522. /**
  523. * Tests shuffle
  524. *
  525. * @return void
  526. */
  527. public function testShuffle()
  528. {
  529. $data = [1, 2, 3, 4];
  530. $collection = (new Collection($data))->shuffle();
  531. $this->assertEquals(count($data), count(iterator_to_array($collection)));
  532. foreach ($collection as $value) {
  533. $this->assertContains($value, $data);
  534. }
  535. }
  536. /**
  537. * Tests sample
  538. *
  539. * @return void
  540. */
  541. public function testSample()
  542. {
  543. $data = [1, 2, 3, 4];
  544. $collection = (new Collection($data))->sample(2);
  545. $this->assertEquals(2, count(iterator_to_array($collection)));
  546. foreach ($collection as $value) {
  547. $this->assertContains($value, $data);
  548. }
  549. }
  550. /**
  551. * Test toArray method
  552. *
  553. * @return void
  554. */
  555. public function testToArray()
  556. {
  557. $data = [1, 2, 3, 4];
  558. $collection = new Collection($data);
  559. $this->assertEquals($data, $collection->toArray());
  560. }
  561. /**
  562. * Test toList method
  563. *
  564. * @return void
  565. */
  566. public function testToList()
  567. {
  568. $data = [100 => 1, 300 => 2, 500 => 3, 1 => 4];
  569. $collection = new Collection($data);
  570. $this->assertEquals(array_values($data), $collection->toList());
  571. }
  572. /**
  573. * Test json encoding
  574. *
  575. * @return void
  576. */
  577. public function testToJson()
  578. {
  579. $data = [1, 2, 3, 4];
  580. $collection = new Collection($data);
  581. $this->assertEquals(json_encode($data), json_encode($collection));
  582. }
  583. /**
  584. * Tests that only arrays and Traversables are allowed in the constructor
  585. *
  586. * @expectedException \InvalidArgumentException
  587. * @expectedExceptionMessage Only an array or \Traversable is allowed for Collection
  588. * @return void
  589. */
  590. public function testInvalidConstructorArgument()
  591. {
  592. new Collection('Derp');
  593. }
  594. /**
  595. * Tests that issuing a count will throw an exception
  596. *
  597. * @expectedException \LogicException
  598. * @return void
  599. */
  600. public function testCollectionCount()
  601. {
  602. $data = [1, 2, 3, 4];
  603. $collection = new Collection($data);
  604. $collection->count();
  605. }
  606. /**
  607. * Tests take method
  608. *
  609. * @return void
  610. */
  611. public function testTake()
  612. {
  613. $data = [1, 2, 3, 4];
  614. $collection = new Collection($data);
  615. $taken = $collection->take(2);
  616. $this->assertEquals([1, 2], $taken->toArray());
  617. $taken = $collection->take(3);
  618. $this->assertEquals([1, 2, 3], $taken->toArray());
  619. $taken = $collection->take(500);
  620. $this->assertEquals([1, 2, 3, 4], $taken->toArray());
  621. $taken = $collection->take(1);
  622. $this->assertEquals([1], $taken->toArray());
  623. $taken = $collection->take();
  624. $this->assertEquals([1], $taken->toArray());
  625. $taken = $collection->take(2, 2);
  626. $this->assertEquals([2 => 3, 3 => 4], $taken->toArray());
  627. }
  628. /**
  629. * Tests match
  630. *
  631. * @return void
  632. */
  633. public function testMatch()
  634. {
  635. $items = [
  636. ['id' => 1, 'name' => 'foo', 'thing' => ['parent_id' => 10]],
  637. ['id' => 2, 'name' => 'bar', 'thing' => ['parent_id' => 11]],
  638. ['id' => 3, 'name' => 'baz', 'thing' => ['parent_id' => 10]],
  639. ];
  640. $collection = new Collection($items);
  641. $matched = $collection->match(['thing.parent_id' => 10, 'name' => 'baz']);
  642. $this->assertEquals([2 => $items[2]], $matched->toArray());
  643. $matched = $collection->match(['thing.parent_id' => 10]);
  644. $this->assertEquals(
  645. [0 => $items[0], 2 => $items[2]],
  646. $matched->toArray()
  647. );
  648. $matched = $collection->match(['thing.parent_id' => 500]);
  649. $this->assertEquals([], $matched->toArray());
  650. $matched = $collection->match(['parent_id' => 10, 'name' => 'baz']);
  651. $this->assertEquals([], $matched->toArray());
  652. }
  653. /**
  654. * Tests firstMatch
  655. *
  656. * @return void
  657. */
  658. public function testFirstMatch()
  659. {
  660. $items = [
  661. ['id' => 1, 'name' => 'foo', 'thing' => ['parent_id' => 10]],
  662. ['id' => 2, 'name' => 'bar', 'thing' => ['parent_id' => 11]],
  663. ['id' => 3, 'name' => 'baz', 'thing' => ['parent_id' => 10]],
  664. ];
  665. $collection = new Collection($items);
  666. $matched = $collection->firstMatch(['thing.parent_id' => 10]);
  667. $this->assertEquals(
  668. ['id' => 1, 'name' => 'foo', 'thing' => ['parent_id' => 10]],
  669. $matched
  670. );
  671. $matched = $collection->firstMatch(['thing.parent_id' => 10, 'name' => 'baz']);
  672. $this->assertEquals(
  673. ['id' => 3, 'name' => 'baz', 'thing' => ['parent_id' => 10]],
  674. $matched
  675. );
  676. }
  677. /**
  678. * Tests the append method
  679. *
  680. * @return void
  681. */
  682. public function testAppend()
  683. {
  684. $collection = new Collection([1, 2, 3]);
  685. $combined = $collection->append([4, 5, 6]);
  686. $this->assertEquals([1, 2, 3, 4, 5, 6], $combined->toArray(false));
  687. $collection = new Collection(['a' => 1, 'b' => 2]);
  688. $combined = $collection->append(['c' => 3, 'a' => 4]);
  689. $this->assertEquals(['a' => 4, 'b' => 2, 'c' => 3], $combined->toArray());
  690. }
  691. /**
  692. * Tests the append method with iterator
  693. */
  694. public function testAppendIterator()
  695. {
  696. $collection = new Collection([1, 2, 3]);
  697. $iterator = new ArrayIterator([4, 5, 6]);
  698. $combined = $collection->append($iterator);
  699. $this->assertEquals([1, 2, 3, 4, 5, 6], $combined->toList());
  700. }
  701. public function testAppendNotCollectionInstance()
  702. {
  703. $collection = new TestCollection([1, 2, 3]);
  704. $combined = $collection->append([4, 5, 6]);
  705. $this->assertEquals([1, 2, 3, 4, 5, 6], $combined->toList());
  706. }
  707. /**
  708. * Tests that by calling compile internal iteration operations are not done
  709. * more than once
  710. *
  711. * @return void
  712. */
  713. public function testCompile()
  714. {
  715. $items = ['a' => 1, 'b' => 2, 'c' => 3];
  716. $collection = new Collection($items);
  717. $callable = $this->getMockBuilder(\StdClass::class)
  718. ->setMethods(['__invoke'])
  719. ->getMock();
  720. $callable->expects($this->at(0))
  721. ->method('__invoke')
  722. ->with(1, 'a')
  723. ->will($this->returnValue(4));
  724. $callable->expects($this->at(1))
  725. ->method('__invoke')
  726. ->with(2, 'b')
  727. ->will($this->returnValue(5));
  728. $callable->expects($this->at(2))
  729. ->method('__invoke')
  730. ->with(3, 'c')
  731. ->will($this->returnValue(6));
  732. $compiled = $collection->map($callable)->compile();
  733. $this->assertEquals(['a' => 4, 'b' => 5, 'c' => 6], $compiled->toArray());
  734. $this->assertEquals(['a' => 4, 'b' => 5, 'c' => 6], $compiled->toArray());
  735. }
  736. /**
  737. * Tests converting a non rewindable iterator into a rewindable one using
  738. * the buffered method.
  739. *
  740. * @return void
  741. */
  742. public function testBuffered()
  743. {
  744. $items = new NoRewindIterator(new ArrayIterator(['a' => 4, 'b' => 5, 'c' => 6]));
  745. $buffered = (new Collection($items))->buffered();
  746. $this->assertEquals(['a' => 4, 'b' => 5, 'c' => 6], $buffered->toArray());
  747. $this->assertEquals(['a' => 4, 'b' => 5, 'c' => 6], $buffered->toArray());
  748. }
  749. /**
  750. * Tests the combine method
  751. *
  752. * @return void
  753. */
  754. public function testCombine()
  755. {
  756. $items = [
  757. ['id' => 1, 'name' => 'foo', 'parent' => 'a'],
  758. ['id' => 2, 'name' => 'bar', 'parent' => 'b'],
  759. ['id' => 3, 'name' => 'baz', 'parent' => 'a']
  760. ];
  761. $collection = (new Collection($items))->combine('id', 'name');
  762. $expected = [1 => 'foo', 2 => 'bar', 3 => 'baz'];
  763. $this->assertEquals($expected, $collection->toArray());
  764. $expected = ['foo' => 1, 'bar' => 2, 'baz' => 3];
  765. $collection = (new Collection($items))->combine('name', 'id');
  766. $this->assertEquals($expected, $collection->toArray());
  767. $collection = (new Collection($items))->combine('id', 'name', 'parent');
  768. $expected = ['a' => [1 => 'foo', 3 => 'baz'], 'b' => [2 => 'bar']];
  769. $this->assertEquals($expected, $collection->toArray());
  770. $expected = [
  771. '0-1' => ['foo-0-1' => '0-1-foo'],
  772. '1-2' => ['bar-1-2' => '1-2-bar'],
  773. '2-3' => ['baz-2-3' => '2-3-baz']
  774. ];
  775. $collection = (new Collection($items))->combine(
  776. function ($value, $key) {
  777. return $value['name'] . '-' . $key;
  778. },
  779. function ($value, $key) {
  780. return $key . '-' . $value['name'];
  781. },
  782. function ($value, $key) {
  783. return $key . '-' . $value['id'];
  784. }
  785. );
  786. $this->assertEquals($expected, $collection->toArray());
  787. $collection = (new Collection($items))->combine('id', 'crazy');
  788. $this->assertEquals([1 => null, 2 => null, 3 => null], $collection->toArray());
  789. }
  790. /**
  791. * Tests the nest method with only one level
  792. *
  793. * @return void
  794. */
  795. public function testNest()
  796. {
  797. $items = [
  798. ['id' => 1, 'parent_id' => null],
  799. ['id' => 2, 'parent_id' => 1],
  800. ['id' => 3, 'parent_id' => 1],
  801. ['id' => 4, 'parent_id' => 1],
  802. ['id' => 5, 'parent_id' => 6],
  803. ['id' => 6, 'parent_id' => null],
  804. ['id' => 7, 'parent_id' => 1],
  805. ['id' => 8, 'parent_id' => 6],
  806. ['id' => 9, 'parent_id' => 6],
  807. ['id' => 10, 'parent_id' => 6]
  808. ];
  809. $collection = (new Collection($items))->nest('id', 'parent_id');
  810. $expected = [
  811. [
  812. 'id' => 1,
  813. 'parent_id' => null,
  814. 'children' => [
  815. ['id' => 2, 'parent_id' => 1, 'children' => []],
  816. ['id' => 3, 'parent_id' => 1, 'children' => []],
  817. ['id' => 4, 'parent_id' => 1, 'children' => []],
  818. ['id' => 7, 'parent_id' => 1, 'children' => []]
  819. ]
  820. ],
  821. [
  822. 'id' => 6,
  823. 'parent_id' => null,
  824. 'children' => [
  825. ['id' => 5, 'parent_id' => 6, 'children' => []],
  826. ['id' => 8, 'parent_id' => 6, 'children' => []],
  827. ['id' => 9, 'parent_id' => 6, 'children' => []],
  828. ['id' => 10, 'parent_id' => 6, 'children' => []]
  829. ]
  830. ]
  831. ];
  832. $this->assertEquals($expected, $collection->toArray());
  833. }
  834. /**
  835. * Tests the nest method with more than one level
  836. *
  837. * @return void
  838. */
  839. public function testNestMultiLevel()
  840. {
  841. $items = [
  842. ['id' => 1, 'parent_id' => null],
  843. ['id' => 2, 'parent_id' => 1],
  844. ['id' => 3, 'parent_id' => 2],
  845. ['id' => 4, 'parent_id' => 2],
  846. ['id' => 5, 'parent_id' => 3],
  847. ['id' => 6, 'parent_id' => null],
  848. ['id' => 7, 'parent_id' => 3],
  849. ['id' => 8, 'parent_id' => 4],
  850. ['id' => 9, 'parent_id' => 6],
  851. ['id' => 10, 'parent_id' => 6]
  852. ];
  853. $collection = (new Collection($items))->nest('id', 'parent_id');
  854. $expected = [
  855. [
  856. 'id' => 1,
  857. 'parent_id' => null,
  858. 'children' => [
  859. [
  860. 'id' => 2,
  861. 'parent_id' => 1,
  862. 'children' => [
  863. [
  864. 'id' => 3,
  865. 'parent_id' => 2,
  866. 'children' => [
  867. ['id' => 5, 'parent_id' => 3, 'children' => []],
  868. ['id' => 7, 'parent_id' => 3, 'children' => []]
  869. ]
  870. ],
  871. [
  872. 'id' => 4,
  873. 'parent_id' => 2,
  874. 'children' => [
  875. ['id' => 8, 'parent_id' => 4, 'children' => []]
  876. ]
  877. ]
  878. ]
  879. ]
  880. ]
  881. ],
  882. [
  883. 'id' => 6,
  884. 'parent_id' => null,
  885. 'children' => [
  886. ['id' => 9, 'parent_id' => 6, 'children' => []],
  887. ['id' => 10, 'parent_id' => 6, 'children' => []]
  888. ]
  889. ]
  890. ];
  891. $this->assertEquals($expected, $collection->toArray());
  892. }
  893. /**
  894. * Tests the nest method with more than one level
  895. *
  896. * @return void
  897. */
  898. public function testNestObjects()
  899. {
  900. $items = [
  901. new ArrayObject(['id' => 1, 'parent_id' => null]),
  902. new ArrayObject(['id' => 2, 'parent_id' => 1]),
  903. new ArrayObject(['id' => 3, 'parent_id' => 2]),
  904. new ArrayObject(['id' => 4, 'parent_id' => 2]),
  905. new ArrayObject(['id' => 5, 'parent_id' => 3]),
  906. new ArrayObject(['id' => 6, 'parent_id' => null]),
  907. new ArrayObject(['id' => 7, 'parent_id' => 3]),
  908. new ArrayObject(['id' => 8, 'parent_id' => 4]),
  909. new ArrayObject(['id' => 9, 'parent_id' => 6]),
  910. new ArrayObject(['id' => 10, 'parent_id' => 6])
  911. ];
  912. $collection = (new Collection($items))->nest('id', 'parent_id');
  913. $expected = [
  914. new ArrayObject([
  915. 'id' => 1,
  916. 'parent_id' => null,
  917. 'children' => [
  918. new ArrayObject([
  919. 'id' => 2,
  920. 'parent_id' => 1,
  921. 'children' => [
  922. new ArrayObject([
  923. 'id' => 3,
  924. 'parent_id' => 2,
  925. 'children' => [
  926. new ArrayObject(['id' => 5, 'parent_id' => 3, 'children' => []]),
  927. new ArrayObject(['id' => 7, 'parent_id' => 3, 'children' => []])
  928. ]
  929. ]),
  930. new ArrayObject([
  931. 'id' => 4,
  932. 'parent_id' => 2,
  933. 'children' => [
  934. new ArrayObject(['id' => 8, 'parent_id' => 4, 'children' => []])
  935. ]
  936. ])
  937. ]
  938. ])
  939. ]
  940. ]),
  941. new ArrayObject([
  942. 'id' => 6,
  943. 'parent_id' => null,
  944. 'children' => [
  945. new ArrayObject(['id' => 9, 'parent_id' => 6, 'children' => []]),
  946. new ArrayObject(['id' => 10, 'parent_id' => 6, 'children' => []])
  947. ]
  948. ])
  949. ];
  950. $this->assertEquals($expected, $collection->toArray());
  951. }
  952. /**
  953. * Tests insert
  954. *
  955. * @return void
  956. */
  957. public function testInsert()
  958. {
  959. $items = [['a' => 1], ['b' => 2]];
  960. $collection = new Collection($items);
  961. $iterator = $collection->insert('c', [3, 4]);
  962. $this->assertInstanceOf('Cake\Collection\Iterator\InsertIterator', $iterator);
  963. $this->assertEquals(
  964. [['a' => 1, 'c' => 3], ['b' => 2, 'c' => 4]],
  965. iterator_to_array($iterator)
  966. );
  967. }
  968. /**
  969. * Provider for testing each of the directions for listNested
  970. *
  971. * @return void
  972. */
  973. public function nestedListProvider()
  974. {
  975. return [
  976. ['desc', [1, 2, 3, 5, 7, 4, 8, 6, 9, 10]],
  977. ['asc', [5, 7, 3, 8, 4, 2, 1, 9, 10, 6]],
  978. ['leaves', [5, 7, 8, 9, 10]]
  979. ];
  980. }
  981. /**
  982. * Tests the listNested method with the default 'children' nesting key
  983. *
  984. * @dataProvider nestedListProvider
  985. * @return void
  986. */
  987. public function testListNested($dir, $expected)
  988. {
  989. $items = [
  990. ['id' => 1, 'parent_id' => null],
  991. ['id' => 2, 'parent_id' => 1],
  992. ['id' => 3, 'parent_id' => 2],
  993. ['id' => 4, 'parent_id' => 2],
  994. ['id' => 5, 'parent_id' => 3],
  995. ['id' => 6, 'parent_id' => null],
  996. ['id' => 7, 'parent_id' => 3],
  997. ['id' => 8, 'parent_id' => 4],
  998. ['id' => 9, 'parent_id' => 6],
  999. ['id' => 10, 'parent_id' => 6]
  1000. ];
  1001. $collection = (new Collection($items))->nest('id', 'parent_id')->listNested($dir);
  1002. $this->assertEquals($expected, $collection->extract('id')->toArray(false));
  1003. }
  1004. /**
  1005. * Tests using listNested with a different nesting key
  1006. *
  1007. * @return void
  1008. */
  1009. public function testListNestedCustomKey()
  1010. {
  1011. $items = [
  1012. ['id' => 1, 'stuff' => [['id' => 2, 'stuff' => [['id' => 3]]]]],
  1013. ['id' => 4, 'stuff' => [['id' => 5]]]
  1014. ];
  1015. $collection = (new Collection($items))->listNested('desc', 'stuff');
  1016. $this->assertEquals(range(1, 5), $collection->extract('id')->toArray(false));
  1017. }
  1018. /**
  1019. * Tests flattening the collection using a custom callable function
  1020. *
  1021. * @return void
  1022. */
  1023. public function testListNestedWithCallable()
  1024. {
  1025. $items = [
  1026. ['id' => 1, 'stuff' => [['id' => 2, 'stuff' => [['id' => 3]]]]],
  1027. ['id' => 4, 'stuff' => [['id' => 5]]]
  1028. ];
  1029. $collection = (new Collection($items))->listNested('desc', function ($item) {
  1030. return isset($item['stuff']) ? $item['stuff'] : [];
  1031. });
  1032. $this->assertEquals(range(1, 5), $collection->extract('id')->toArray(false));
  1033. }
  1034. /**
  1035. * Tests the sumOf method
  1036. *
  1037. * @return void
  1038. */
  1039. public function testSumOf()
  1040. {
  1041. $items = [
  1042. ['invoice' => ['total' => 100]],
  1043. ['invoice' => ['total' => 200]]
  1044. ];
  1045. $this->assertEquals(300, (new Collection($items))->sumOf('invoice.total'));
  1046. $sum = (new Collection($items))->sumOf(function ($v) {
  1047. return $v['invoice']['total'] * 2;
  1048. });
  1049. $this->assertEquals(600, $sum);
  1050. }
  1051. /**
  1052. * Tests the stopWhen method with a callable
  1053. *
  1054. * @return void
  1055. */
  1056. public function testStopWhenCallable()
  1057. {
  1058. $items = [10, 20, 40, 10, 5];
  1059. $collection = (new Collection($items))->stopWhen(function ($v) {
  1060. return $v > 20;
  1061. });
  1062. $this->assertEquals([10, 20], $collection->toArray());
  1063. }
  1064. /**
  1065. * Tests the stopWhen method with a matching array
  1066. *
  1067. * @return void
  1068. */
  1069. public function testStopWhenWithArray()
  1070. {
  1071. $items = [
  1072. ['foo' => 'bar'],
  1073. ['foo' => 'baz'],
  1074. ['foo' => 'foo']
  1075. ];
  1076. $collection = (new Collection($items))->stopWhen(['foo' => 'baz']);
  1077. $this->assertEquals([['foo' => 'bar']], $collection->toArray());
  1078. }
  1079. /**
  1080. * Tests the unfold method
  1081. *
  1082. * @return void
  1083. */
  1084. public function testUnfold()
  1085. {
  1086. $items = [
  1087. [1, 2, 3, 4],
  1088. [5, 6],
  1089. [7, 8]
  1090. ];
  1091. $collection = (new Collection($items))->unfold();
  1092. $this->assertEquals(range(1, 8), $collection->toArray(false));
  1093. $items = [
  1094. [1, 2],
  1095. new Collection([3, 4])
  1096. ];
  1097. $collection = (new Collection($items))->unfold();
  1098. $this->assertEquals(range(1, 4), $collection->toArray(false));
  1099. }
  1100. /**
  1101. * Tests the unfold method with empty levels
  1102. *
  1103. * @return void
  1104. */
  1105. public function testUnfoldEmptyLevels()
  1106. {
  1107. $items = [[], [1, 2], []];
  1108. $collection = (new Collection($items))->unfold();
  1109. $this->assertEquals(range(1, 2), $collection->toArray(false));
  1110. $items = [];
  1111. $collection = (new Collection($items))->unfold();
  1112. $this->assertEmpty($collection->toArray(false));
  1113. }
  1114. /**
  1115. * Tests the unfold when passing a callable
  1116. *
  1117. * @return void
  1118. */
  1119. public function testUnfoldWithCallable()
  1120. {
  1121. $items = [1, 2, 3];
  1122. $collection = (new Collection($items))->unfold(function ($item) {
  1123. return range($item, $item * 2);
  1124. });
  1125. $expected = [1, 2, 2, 3, 4, 3, 4, 5, 6];
  1126. $this->assertEquals($expected, $collection->toArray(false));
  1127. }
  1128. /**
  1129. * Tests the through() method
  1130. *
  1131. * @return void
  1132. */
  1133. public function testThrough()
  1134. {
  1135. $items = [1, 2, 3];
  1136. $collection = (new Collection($items))->through(function ($collection) {
  1137. return $collection->append($collection->toList());
  1138. });
  1139. $this->assertEquals([1, 2, 3, 1, 2, 3], $collection->toList());
  1140. }
  1141. /**
  1142. * Tests the through method when it returns an array
  1143. *
  1144. * @return void
  1145. */
  1146. public function testThroughReturnArray()
  1147. {
  1148. $items = [1, 2, 3];
  1149. $collection = (new Collection($items))->through(function ($collection) {
  1150. $list = $collection->toList();
  1151. return array_merge($list, $list);
  1152. });
  1153. $this->assertEquals([1, 2, 3, 1, 2, 3], $collection->toList());
  1154. }
  1155. /**
  1156. * Tests that the sortBy method does not die when something that is not a
  1157. * collection is passed
  1158. *
  1159. * @return void
  1160. */
  1161. public function testComplexSortBy()
  1162. {
  1163. $results = collection([3, 7])
  1164. ->unfold(function ($value) {
  1165. return [
  1166. ['sorting' => $value * 2],
  1167. ['sorting' => $value * 2]
  1168. ];
  1169. })
  1170. ->sortBy('sorting')
  1171. ->extract('sorting')
  1172. ->toList();
  1173. $this->assertEquals([14, 14, 6, 6], $results);
  1174. }
  1175. /**
  1176. * Tests __debugInfo() or debug() usage
  1177. *
  1178. * @return void
  1179. */
  1180. public function testDebug()
  1181. {
  1182. $items = [1, 2, 3];
  1183. $collection = new Collection($items);
  1184. $result = $collection->__debugInfo();
  1185. $expected = [
  1186. 'count' => 3,
  1187. ];
  1188. $this->assertSame($expected, $result);
  1189. // Calling it again will rewind
  1190. $result = $collection->__debugInfo();
  1191. $expected = [
  1192. 'count' => 3,
  1193. ];
  1194. $this->assertSame($expected, $result);
  1195. // Make sure it also works with non rewindable iterators
  1196. $iterator = new NoRewindIterator(new ArrayIterator($items));
  1197. $collection = new Collection($iterator);
  1198. $result = $collection->__debugInfo();
  1199. $expected = [
  1200. 'count' => 3,
  1201. ];
  1202. $this->assertSame($expected, $result);
  1203. // Calling it again will in this case not rewind
  1204. $result = $collection->__debugInfo();
  1205. $expected = [
  1206. 'count' => 0,
  1207. ];
  1208. $this->assertSame($expected, $result);
  1209. }
  1210. /**
  1211. * Tests the isEmpty() method
  1212. *
  1213. * @return void
  1214. */
  1215. public function testIsEmpty()
  1216. {
  1217. $collection = new Collection([1, 2, 3]);
  1218. $this->assertFalse($collection->isEmpty());
  1219. $collection = $collection->map(function () {
  1220. return null;
  1221. });
  1222. $this->assertFalse($collection->isEmpty());
  1223. $collection = $collection->filter();
  1224. $this->assertTrue($collection->isEmpty());
  1225. }
  1226. /**
  1227. * Tests the isEmpty() method does not consume data
  1228. * from buffered iterators.
  1229. *
  1230. * @return void
  1231. */
  1232. public function testIsEmptyDoesNotConsume()
  1233. {
  1234. $array = new \ArrayIterator([1, 2, 3]);
  1235. $inner = new \Cake\Collection\Iterator\BufferedIterator($array);
  1236. $collection = new Collection($inner);
  1237. $this->assertFalse($collection->isEmpty());
  1238. $this->assertCount(3, $collection->toArray());
  1239. }
  1240. /**
  1241. * Tests the zip() method
  1242. *
  1243. * @return void
  1244. */
  1245. public function testZip()
  1246. {
  1247. $collection = new Collection([1, 2]);
  1248. $zipped = $collection->zip([3, 4]);
  1249. $this->assertEquals([[1, 3], [2, 4]], $zipped->toList());
  1250. $collection = new Collection([1, 2]);
  1251. $zipped = $collection->zip([3]);
  1252. $this->assertEquals([[1, 3]], $zipped->toList());
  1253. $collection = new Collection([1, 2]);
  1254. $zipped = $collection->zip([3, 4], [5, 6], [7, 8], [9, 10, 11]);
  1255. $this->assertEquals([
  1256. [1, 3, 5, 7, 9],
  1257. [2, 4, 6, 8, 10]
  1258. ], $zipped->toList());
  1259. }
  1260. /**
  1261. * Tests the zipWith() method
  1262. *
  1263. * @return void
  1264. */
  1265. public function testZipWith()
  1266. {
  1267. $collection = new Collection([1, 2]);
  1268. $zipped = $collection->zipWith([3, 4], function ($a, $b) {
  1269. return $a * $b;
  1270. });
  1271. $this->assertEquals([3, 8], $zipped->toList());
  1272. $zipped = $collection->zipWith([3, 4], [5, 6, 7], function () {
  1273. return array_sum(func_get_args());
  1274. });
  1275. $this->assertEquals([9, 12], $zipped->toList());
  1276. }
  1277. /**
  1278. * Tests the skip() method
  1279. *
  1280. * @return void
  1281. */
  1282. public function testSkip()
  1283. {
  1284. $collection = new Collection([1, 2, 3, 4, 5]);
  1285. $this->assertEquals([3, 4, 5], $collection->skip(2)->toList());
  1286. $this->assertEquals([5], $collection->skip(4)->toList());
  1287. }
  1288. /**
  1289. * Tests the last() method
  1290. *
  1291. * @return void
  1292. */
  1293. public function testLast()
  1294. {
  1295. $collection = new Collection([1, 2, 3]);
  1296. $this->assertEquals(3, $collection->last());
  1297. $collection = $collection->map(function ($e) {
  1298. return $e * 2;
  1299. });
  1300. $this->assertEquals(6, $collection->last());
  1301. }
  1302. /**
  1303. * Tests the last() method when on an empty collection
  1304. *
  1305. * @return void
  1306. */
  1307. public function testLAstWithEmptyCollection()
  1308. {
  1309. $collection = new Collection([]);
  1310. $this->assertNull($collection->last());
  1311. }
  1312. /**
  1313. * Tests sumOf with no parameters
  1314. *
  1315. * @return void
  1316. */
  1317. public function testSumOfWithIdentity()
  1318. {
  1319. $collection = new Collection([1, 2, 3]);
  1320. $this->assertEquals(6, $collection->sumOf());
  1321. $collection = new Collection(['a' => 1, 'b' => 4, 'c' => 6]);
  1322. $this->assertEquals(11, $collection->sumOf());
  1323. }
  1324. /**
  1325. * Tests using extract with the {*} notation
  1326. *
  1327. * @return void
  1328. */
  1329. public function testUnfoldedExtract()
  1330. {
  1331. $items = [
  1332. ['comments' => [['id' => 1], ['id' => 2]]],
  1333. ['comments' => [['id' => 3], ['id' => 4]]],
  1334. ['comments' => [['id' => 7], ['nope' => 8]]],
  1335. ];
  1336. $extracted = (new Collection($items))->extract('comments.{*}.id');
  1337. $this->assertEquals([1, 2, 3, 4, 7, null], $extracted->toArray());
  1338. $items = [
  1339. [
  1340. 'comments' => [
  1341. [
  1342. 'voters' => [['id' => 1], ['id' => 2]]
  1343. ]
  1344. ]
  1345. ],
  1346. [
  1347. 'comments' => [
  1348. [
  1349. 'voters' => [['id' => 3], ['id' => 4]]
  1350. ]
  1351. ]
  1352. ],
  1353. [
  1354. 'comments' => [
  1355. [
  1356. 'voters' => [['id' => 5], ['nope' => 'fail'], ['id' => 6]]
  1357. ]
  1358. ]
  1359. ],
  1360. [
  1361. 'comments' => [
  1362. [
  1363. 'not_voters' => [['id' => 5]]
  1364. ]
  1365. ]
  1366. ],
  1367. ['not_comments' => []]
  1368. ];
  1369. $extracted = (new Collection($items))->extract('comments.{*}.voters.{*}.id');
  1370. $expected = [1, 2, 3, 4, 5, null, 6];
  1371. $this->assertEquals($expected, $extracted->toArray());
  1372. $this->assertEquals($expected, $extracted->toList());
  1373. }
  1374. /**
  1375. * Tests serializing a simple collection
  1376. *
  1377. * @return void
  1378. */
  1379. public function testSerializeSimpleCollection()
  1380. {
  1381. $collection = new Collection([1, 2, 3]);
  1382. $selialized = serialize($collection);
  1383. $unserialized = unserialize($selialized);
  1384. $this->assertEquals($collection->toList(), $unserialized->toList());
  1385. $this->assertEquals($collection->toArray(), $unserialized->toArray());
  1386. }
  1387. /**
  1388. * Tests serialization when using append
  1389. *
  1390. * @return void
  1391. */
  1392. public function testSerializeWithAppendIterators()
  1393. {
  1394. $collection = new Collection([1, 2, 3]);
  1395. $collection = $collection->append(['a' => 4, 'b' => 5, 'c' => 6]);
  1396. $selialized = serialize($collection);
  1397. $unserialized = unserialize($selialized);
  1398. $this->assertEquals($collection->toList(), $unserialized->toList());
  1399. $this->assertEquals($collection->toArray(), $unserialized->toArray());
  1400. }
  1401. /**
  1402. * Tests serialization when using nested iterators
  1403. *
  1404. * @return void
  1405. */
  1406. public function testSerializeWithNestedIterators()
  1407. {
  1408. $collection = new Collection([1, 2, 3]);
  1409. $collection = $collection->map(function ($e) {
  1410. return $e * 3;
  1411. });
  1412. $collection = $collection->groupBy(function ($e) {
  1413. return $e % 2;
  1414. });
  1415. $selialized = serialize($collection);
  1416. $unserialized = unserialize($selialized);
  1417. $this->assertEquals($collection->toList(), $unserialized->toList());
  1418. $this->assertEquals($collection->toArray(), $unserialized->toArray());
  1419. }
  1420. /**
  1421. * Tests serializing a zip() call
  1422. *
  1423. * @return void
  1424. */
  1425. public function testSerializeWithZipIterator()
  1426. {
  1427. $collection = new Collection([4, 5]);
  1428. $collection = $collection->zip([1, 2]);
  1429. $selialized = serialize($collection);
  1430. $unserialized = unserialize($selialized);
  1431. $this->assertEquals($collection->toList(), $unserialized->toList());
  1432. }
  1433. /**
  1434. * Tests the chunk method with exact chunks
  1435. *
  1436. * @return void
  1437. */
  1438. public function testChunk()
  1439. {
  1440. $collection = new Collection(range(1, 10));
  1441. $chunked = $collection->chunk(2)->toList();
  1442. $expected = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]];
  1443. $this->assertEquals($expected, $chunked);
  1444. }
  1445. /**
  1446. * Tests the chunk method with overflowing chunk size
  1447. *
  1448. * @return void
  1449. */
  1450. public function testChunkOverflow()
  1451. {
  1452. $collection = new Collection(range(1, 11));
  1453. $chunked = $collection->chunk(2)->toList();
  1454. $expected = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11]];
  1455. $this->assertEquals($expected, $chunked);
  1456. }
  1457. /**
  1458. * Tests the chunk method with non-scalar items
  1459. *
  1460. * @return void
  1461. */
  1462. public function testChunkNested()
  1463. {
  1464. $collection = new Collection([1, 2, 3, [4, 5], 6, [7, [8, 9], 10], 11]);
  1465. $chunked = $collection->chunk(2)->toList();
  1466. $expected = [[1, 2], [3, [4, 5]], [6, [7, [8, 9], 10]], [11]];
  1467. $this->assertEquals($expected, $chunked);
  1468. }
  1469. public function testTranspose()
  1470. {
  1471. $collection = new Collection([
  1472. ['Products', '2012', '2013', '2014'],
  1473. ['Product A', '200', '100', '50'],
  1474. ['Product B', '300', '200', '100'],
  1475. ['Product C', '400', '300', '200'],
  1476. ]);
  1477. $transposed = $collection->transpose();
  1478. $expected = [
  1479. ['Products', 'Product A', 'Product B', 'Product C'],
  1480. ['2012', '200', '300', '400'],
  1481. ['2013', '100', '200', '300'],
  1482. ['2014', '50', '100', '200'],
  1483. ];
  1484. $this->assertEquals($expected, $transposed->toList());
  1485. }
  1486. /**
  1487. * Tests that provided arrays do not have even length
  1488. *
  1489. * @expectedException \LogicException
  1490. * @return void
  1491. */
  1492. public function testTransposeUnEvenLengthShouldThrowException()
  1493. {
  1494. $collection = new Collection([
  1495. ['Products', '2012', '2013', '2014'],
  1496. ['Product A', '200', '100', '50'],
  1497. ['Product B', '300'],
  1498. ['Product C', '400', '300'],
  1499. ]);
  1500. $collection->transpose();
  1501. }
  1502. }