CollectionTest.php 82 KB

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