CollectionTest.php 47 KB

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