CollectionTest.php 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605
  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. }