CollectionTest.php 73 KB

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