CollectionTest.php 78 KB

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