CollectionTest.php 82 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810
  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 sample
  894. *
  895. * @dataProvider simpleProvider
  896. * @return void
  897. */
  898. public function testSample($data)
  899. {
  900. $result = (new Collection($data))->sample(2)->toArray();
  901. $this->assertCount(2, $result);
  902. foreach ($result as $number) {
  903. $this->assertContains($number, [1, 2, 3, 4]);
  904. }
  905. }
  906. /**
  907. * Tests the sample() method with a traversable non-iterator
  908. *
  909. * @return void
  910. */
  911. public function testSampleWithTraversableNonIterator()
  912. {
  913. $collection = new Collection($this->datePeriod('2017-01-01', '2017-01-07'));
  914. $result = $collection->sample(3)->toList();
  915. $list = [
  916. '2017-01-01',
  917. '2017-01-02',
  918. '2017-01-03',
  919. '2017-01-04',
  920. '2017-01-05',
  921. '2017-01-06',
  922. ];
  923. $this->assertCount(3, $result);
  924. foreach ($result as $date) {
  925. $this->assertContains($date->format('Y-m-d'), $list);
  926. }
  927. }
  928. /**
  929. * Test toArray method
  930. *
  931. * @return void
  932. */
  933. public function testToArray()
  934. {
  935. $data = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4];
  936. $collection = new Collection($data);
  937. $this->assertEquals($data, $collection->toArray());
  938. }
  939. /**
  940. * Test toList method
  941. *
  942. * @dataProvider simpleProvider
  943. * @return void
  944. */
  945. public function testToList($data)
  946. {
  947. $collection = new Collection($data);
  948. $this->assertEquals([1, 2, 3, 4], $collection->toList());
  949. }
  950. /**
  951. * Test json encoding
  952. *
  953. * @return void
  954. */
  955. public function testToJson()
  956. {
  957. $data = [1, 2, 3, 4];
  958. $collection = new Collection($data);
  959. $this->assertEquals(json_encode($data), json_encode($collection));
  960. }
  961. /**
  962. * Tests that only arrays and Traversables are allowed in the constructor
  963. *
  964. * @return void
  965. */
  966. public function testInvalidConstructorArgument()
  967. {
  968. $this->expectException(\InvalidArgumentException::class);
  969. $this->expectExceptionMessage('Only an array or \Traversable is allowed for Collection');
  970. new Collection('Derp');
  971. }
  972. /**
  973. * Tests that Count returns the number of elements
  974. *
  975. * @dataProvider simpleProvider
  976. * @return void
  977. */
  978. public function testCollectionCount($list)
  979. {
  980. $list = (new Collection($list))->buffered();
  981. $collection = new Collection($list);
  982. $this->assertEquals(8, $collection->append($list)->count());
  983. }
  984. /**
  985. * Tests that countKeys returns the number of unique keys
  986. *
  987. * @dataProvider simpleProvider
  988. * @return void
  989. */
  990. public function testCollectionCountKeys($list)
  991. {
  992. $list = (new Collection($list))->buffered();
  993. $collection = new Collection($list);
  994. $this->assertEquals(4, $collection->append($list)->countKeys());
  995. }
  996. /**
  997. * Tests take method
  998. *
  999. * @return void
  1000. */
  1001. public function testTake()
  1002. {
  1003. $data = [1, 2, 3, 4];
  1004. $collection = new Collection($data);
  1005. $taken = $collection->take(2);
  1006. $this->assertEquals([1, 2], $taken->toArray());
  1007. $taken = $collection->take(3);
  1008. $this->assertEquals([1, 2, 3], $taken->toArray());
  1009. $taken = $collection->take(500);
  1010. $this->assertEquals([1, 2, 3, 4], $taken->toArray());
  1011. $taken = $collection->take(1);
  1012. $this->assertEquals([1], $taken->toArray());
  1013. $taken = $collection->take();
  1014. $this->assertEquals([1], $taken->toArray());
  1015. $taken = $collection->take(2, 2);
  1016. $this->assertEquals([2 => 3, 3 => 4], $taken->toArray());
  1017. }
  1018. /**
  1019. * Tests the take() method with a traversable non-iterator
  1020. *
  1021. * @return void
  1022. */
  1023. public function testTakeWithTraversableNonIterator()
  1024. {
  1025. $collection = new Collection($this->datePeriod('2017-01-01', '2017-01-07'));
  1026. $result = $collection->take(3, 1)->toList();
  1027. $expected = [
  1028. new \DateTime('2017-01-02'),
  1029. new \DateTime('2017-01-03'),
  1030. new \DateTime('2017-01-04'),
  1031. ];
  1032. $this->assertEquals($expected, $result);
  1033. }
  1034. /**
  1035. * Tests match
  1036. *
  1037. * @return void
  1038. */
  1039. public function testMatch()
  1040. {
  1041. $items = [
  1042. ['id' => 1, 'name' => 'foo', 'thing' => ['parent_id' => 10]],
  1043. ['id' => 2, 'name' => 'bar', 'thing' => ['parent_id' => 11]],
  1044. ['id' => 3, 'name' => 'baz', 'thing' => ['parent_id' => 10]],
  1045. ];
  1046. $collection = new Collection($items);
  1047. $matched = $collection->match(['thing.parent_id' => 10, 'name' => 'baz']);
  1048. $this->assertEquals([2 => $items[2]], $matched->toArray());
  1049. $matched = $collection->match(['thing.parent_id' => 10]);
  1050. $this->assertEquals(
  1051. [0 => $items[0], 2 => $items[2]],
  1052. $matched->toArray()
  1053. );
  1054. $matched = $collection->match(['thing.parent_id' => 500]);
  1055. $this->assertEquals([], $matched->toArray());
  1056. $matched = $collection->match(['parent_id' => 10, 'name' => 'baz']);
  1057. $this->assertEquals([], $matched->toArray());
  1058. }
  1059. /**
  1060. * Tests firstMatch
  1061. *
  1062. * @return void
  1063. */
  1064. public function testFirstMatch()
  1065. {
  1066. $items = [
  1067. ['id' => 1, 'name' => 'foo', 'thing' => ['parent_id' => 10]],
  1068. ['id' => 2, 'name' => 'bar', 'thing' => ['parent_id' => 11]],
  1069. ['id' => 3, 'name' => 'baz', 'thing' => ['parent_id' => 10]],
  1070. ];
  1071. $collection = new Collection($items);
  1072. $matched = $collection->firstMatch(['thing.parent_id' => 10]);
  1073. $this->assertEquals(
  1074. ['id' => 1, 'name' => 'foo', 'thing' => ['parent_id' => 10]],
  1075. $matched
  1076. );
  1077. $matched = $collection->firstMatch(['thing.parent_id' => 10, 'name' => 'baz']);
  1078. $this->assertEquals(
  1079. ['id' => 3, 'name' => 'baz', 'thing' => ['parent_id' => 10]],
  1080. $matched
  1081. );
  1082. }
  1083. /**
  1084. * Tests the append method
  1085. *
  1086. * @return void
  1087. */
  1088. public function testAppend()
  1089. {
  1090. $collection = new Collection([1, 2, 3]);
  1091. $combined = $collection->append([4, 5, 6]);
  1092. $this->assertEquals([1, 2, 3, 4, 5, 6], $combined->toArray(false));
  1093. $collection = new Collection(['a' => 1, 'b' => 2]);
  1094. $combined = $collection->append(['c' => 3, 'a' => 4]);
  1095. $this->assertEquals(['a' => 4, 'b' => 2, 'c' => 3], $combined->toArray());
  1096. }
  1097. /**
  1098. * Tests the appendItem method
  1099. */
  1100. public function testAppendItem()
  1101. {
  1102. $collection = new Collection([1, 2, 3]);
  1103. $combined = $collection->appendItem(4);
  1104. $this->assertEquals([1, 2, 3, 4], $combined->toArray(false));
  1105. $collection = new Collection(['a' => 1, 'b' => 2]);
  1106. $combined = $collection->appendItem(3, 'c');
  1107. $combined = $combined->appendItem(4, 'a');
  1108. $this->assertEquals(['a' => 4, 'b' => 2, 'c' => 3], $combined->toArray());
  1109. }
  1110. /**
  1111. * Tests the prepend method
  1112. */
  1113. public function testPrepend()
  1114. {
  1115. $collection = new Collection([1, 2, 3]);
  1116. $combined = $collection->prepend(['a']);
  1117. $this->assertEquals(['a', 1, 2, 3], $combined->toList());
  1118. $collection = new Collection(['c' => 3, 'd' => 4]);
  1119. $combined = $collection->prepend(['a' => 1, 'b' => 2]);
  1120. $this->assertEquals(['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4], $combined->toArray());
  1121. }
  1122. /**
  1123. * Tests prependItem method
  1124. */
  1125. public function testPrependItem()
  1126. {
  1127. $collection = new Collection([1, 2, 3]);
  1128. $combined = $collection->prependItem('a');
  1129. $this->assertEquals(['a', 1, 2, 3], $combined->toList());
  1130. $collection = new Collection(['c' => 3, 'd' => 4]);
  1131. $combined = $collection->prependItem(2, 'b');
  1132. $combined = $combined->prependItem(1, 'a');
  1133. $this->assertEquals(['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4], $combined->toArray());
  1134. }
  1135. /**
  1136. * Tests prependItem method
  1137. */
  1138. public function testPrependItemPreserveKeys()
  1139. {
  1140. $collection = new Collection([1, 2, 3]);
  1141. $combined = $collection->prependItem('a');
  1142. $this->assertEquals(['a', 1, 2, 3], $combined->toList());
  1143. $collection = new Collection(['c' => 3, 'd' => 4]);
  1144. $combined = $collection->prependItem(2, 'b');
  1145. $combined = $combined->prependItem(1, 'a');
  1146. $this->assertEquals(['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4], $combined->toArray());
  1147. }
  1148. /**
  1149. * Tests the append method with iterator
  1150. */
  1151. public function testAppendIterator()
  1152. {
  1153. $collection = new Collection([1, 2, 3]);
  1154. $iterator = new ArrayIterator([4, 5, 6]);
  1155. $combined = $collection->append($iterator);
  1156. $this->assertEquals([1, 2, 3, 4, 5, 6], $combined->toList());
  1157. }
  1158. public function testAppendNotCollectionInstance()
  1159. {
  1160. $collection = new TestCollection([1, 2, 3]);
  1161. $combined = $collection->append([4, 5, 6]);
  1162. $this->assertEquals([1, 2, 3, 4, 5, 6], $combined->toList());
  1163. }
  1164. /**
  1165. * Tests that by calling compile internal iteration operations are not done
  1166. * more than once
  1167. *
  1168. * @return void
  1169. */
  1170. public function testCompile()
  1171. {
  1172. $items = ['a' => 1, 'b' => 2, 'c' => 3];
  1173. $collection = new Collection($items);
  1174. $callable = $this->getMockBuilder(\StdClass::class)
  1175. ->setMethods(['__invoke'])
  1176. ->getMock();
  1177. $callable->expects($this->at(0))
  1178. ->method('__invoke')
  1179. ->with(1, 'a')
  1180. ->will($this->returnValue(4));
  1181. $callable->expects($this->at(1))
  1182. ->method('__invoke')
  1183. ->with(2, 'b')
  1184. ->will($this->returnValue(5));
  1185. $callable->expects($this->at(2))
  1186. ->method('__invoke')
  1187. ->with(3, 'c')
  1188. ->will($this->returnValue(6));
  1189. $compiled = $collection->map($callable)->compile();
  1190. $this->assertEquals(['a' => 4, 'b' => 5, 'c' => 6], $compiled->toArray());
  1191. $this->assertEquals(['a' => 4, 'b' => 5, 'c' => 6], $compiled->toArray());
  1192. }
  1193. /**
  1194. * Tests converting a non rewindable iterator into a rewindable one using
  1195. * the buffered method.
  1196. *
  1197. * @return void
  1198. */
  1199. public function testBuffered()
  1200. {
  1201. $items = new NoRewindIterator(new ArrayIterator(['a' => 4, 'b' => 5, 'c' => 6]));
  1202. $buffered = (new Collection($items))->buffered();
  1203. $this->assertEquals(['a' => 4, 'b' => 5, 'c' => 6], $buffered->toArray());
  1204. $this->assertEquals(['a' => 4, 'b' => 5, 'c' => 6], $buffered->toArray());
  1205. }
  1206. /**
  1207. * Tests the combine method
  1208. *
  1209. * @return void
  1210. */
  1211. public function testCombine()
  1212. {
  1213. $items = [
  1214. ['id' => 1, 'name' => 'foo', 'parent' => 'a'],
  1215. ['id' => 2, 'name' => 'bar', 'parent' => 'b'],
  1216. ['id' => 3, 'name' => 'baz', 'parent' => 'a'],
  1217. ];
  1218. $collection = (new Collection($items))->combine('id', 'name');
  1219. $expected = [1 => 'foo', 2 => 'bar', 3 => 'baz'];
  1220. $this->assertEquals($expected, $collection->toArray());
  1221. $expected = ['foo' => 1, 'bar' => 2, 'baz' => 3];
  1222. $collection = (new Collection($items))->combine('name', 'id');
  1223. $this->assertEquals($expected, $collection->toArray());
  1224. $collection = (new Collection($items))->combine('id', 'name', 'parent');
  1225. $expected = ['a' => [1 => 'foo', 3 => 'baz'], 'b' => [2 => 'bar']];
  1226. $this->assertEquals($expected, $collection->toArray());
  1227. $expected = [
  1228. '0-1' => ['foo-0-1' => '0-1-foo'],
  1229. '1-2' => ['bar-1-2' => '1-2-bar'],
  1230. '2-3' => ['baz-2-3' => '2-3-baz'],
  1231. ];
  1232. $collection = (new Collection($items))->combine(
  1233. function ($value, $key) {
  1234. return $value['name'] . '-' . $key;
  1235. },
  1236. function ($value, $key) {
  1237. return $key . '-' . $value['name'];
  1238. },
  1239. function ($value, $key) {
  1240. return $key . '-' . $value['id'];
  1241. }
  1242. );
  1243. $this->assertEquals($expected, $collection->toArray());
  1244. $collection = (new Collection($items))->combine('id', 'crazy');
  1245. $this->assertEquals([1 => null, 2 => null, 3 => null], $collection->toArray());
  1246. }
  1247. /**
  1248. * Tests the nest method with only one level
  1249. *
  1250. * @return void
  1251. */
  1252. public function testNest()
  1253. {
  1254. $items = [
  1255. ['id' => 1, 'parent_id' => null],
  1256. ['id' => 2, 'parent_id' => 1],
  1257. ['id' => 3, 'parent_id' => 1],
  1258. ['id' => 4, 'parent_id' => 1],
  1259. ['id' => 5, 'parent_id' => 6],
  1260. ['id' => 6, 'parent_id' => null],
  1261. ['id' => 7, 'parent_id' => 1],
  1262. ['id' => 8, 'parent_id' => 6],
  1263. ['id' => 9, 'parent_id' => 6],
  1264. ['id' => 10, 'parent_id' => 6],
  1265. ];
  1266. $collection = (new Collection($items))->nest('id', 'parent_id');
  1267. $expected = [
  1268. [
  1269. 'id' => 1,
  1270. 'parent_id' => null,
  1271. 'children' => [
  1272. ['id' => 2, 'parent_id' => 1, 'children' => []],
  1273. ['id' => 3, 'parent_id' => 1, 'children' => []],
  1274. ['id' => 4, 'parent_id' => 1, 'children' => []],
  1275. ['id' => 7, 'parent_id' => 1, 'children' => []],
  1276. ],
  1277. ],
  1278. [
  1279. 'id' => 6,
  1280. 'parent_id' => null,
  1281. 'children' => [
  1282. ['id' => 5, 'parent_id' => 6, 'children' => []],
  1283. ['id' => 8, 'parent_id' => 6, 'children' => []],
  1284. ['id' => 9, 'parent_id' => 6, 'children' => []],
  1285. ['id' => 10, 'parent_id' => 6, 'children' => []],
  1286. ],
  1287. ],
  1288. ];
  1289. $this->assertEquals($expected, $collection->toArray());
  1290. }
  1291. /**
  1292. * Tests the nest method with alternate nesting key
  1293. *
  1294. * @return void
  1295. */
  1296. public function testNestAlternateNestingKey()
  1297. {
  1298. $items = [
  1299. ['id' => 1, 'parent_id' => null],
  1300. ['id' => 2, 'parent_id' => 1],
  1301. ['id' => 3, 'parent_id' => 1],
  1302. ['id' => 4, 'parent_id' => 1],
  1303. ['id' => 5, 'parent_id' => 6],
  1304. ['id' => 6, 'parent_id' => null],
  1305. ['id' => 7, 'parent_id' => 1],
  1306. ['id' => 8, 'parent_id' => 6],
  1307. ['id' => 9, 'parent_id' => 6],
  1308. ['id' => 10, 'parent_id' => 6],
  1309. ];
  1310. $collection = (new Collection($items))->nest('id', 'parent_id', 'nodes');
  1311. $expected = [
  1312. [
  1313. 'id' => 1,
  1314. 'parent_id' => null,
  1315. 'nodes' => [
  1316. ['id' => 2, 'parent_id' => 1, 'nodes' => []],
  1317. ['id' => 3, 'parent_id' => 1, 'nodes' => []],
  1318. ['id' => 4, 'parent_id' => 1, 'nodes' => []],
  1319. ['id' => 7, 'parent_id' => 1, 'nodes' => []],
  1320. ],
  1321. ],
  1322. [
  1323. 'id' => 6,
  1324. 'parent_id' => null,
  1325. 'nodes' => [
  1326. ['id' => 5, 'parent_id' => 6, 'nodes' => []],
  1327. ['id' => 8, 'parent_id' => 6, 'nodes' => []],
  1328. ['id' => 9, 'parent_id' => 6, 'nodes' => []],
  1329. ['id' => 10, 'parent_id' => 6, 'nodes' => []],
  1330. ],
  1331. ],
  1332. ];
  1333. $this->assertEquals($expected, $collection->toArray());
  1334. }
  1335. /**
  1336. * Tests the nest method with more than one level
  1337. *
  1338. * @return void
  1339. */
  1340. public function testNestMultiLevel()
  1341. {
  1342. $items = [
  1343. ['id' => 1, 'parent_id' => null],
  1344. ['id' => 2, 'parent_id' => 1],
  1345. ['id' => 3, 'parent_id' => 2],
  1346. ['id' => 4, 'parent_id' => 2],
  1347. ['id' => 5, 'parent_id' => 3],
  1348. ['id' => 6, 'parent_id' => null],
  1349. ['id' => 7, 'parent_id' => 3],
  1350. ['id' => 8, 'parent_id' => 4],
  1351. ['id' => 9, 'parent_id' => 6],
  1352. ['id' => 10, 'parent_id' => 6],
  1353. ];
  1354. $collection = (new Collection($items))->nest('id', 'parent_id', 'nodes');
  1355. $expected = [
  1356. [
  1357. 'id' => 1,
  1358. 'parent_id' => null,
  1359. 'nodes' => [
  1360. [
  1361. 'id' => 2,
  1362. 'parent_id' => 1,
  1363. 'nodes' => [
  1364. [
  1365. 'id' => 3,
  1366. 'parent_id' => 2,
  1367. 'nodes' => [
  1368. ['id' => 5, 'parent_id' => 3, 'nodes' => []],
  1369. ['id' => 7, 'parent_id' => 3, 'nodes' => []],
  1370. ],
  1371. ],
  1372. [
  1373. 'id' => 4,
  1374. 'parent_id' => 2,
  1375. 'nodes' => [
  1376. ['id' => 8, 'parent_id' => 4, 'nodes' => []],
  1377. ],
  1378. ],
  1379. ],
  1380. ],
  1381. ],
  1382. ],
  1383. [
  1384. 'id' => 6,
  1385. 'parent_id' => null,
  1386. 'nodes' => [
  1387. ['id' => 9, 'parent_id' => 6, 'nodes' => []],
  1388. ['id' => 10, 'parent_id' => 6, 'nodes' => []],
  1389. ],
  1390. ],
  1391. ];
  1392. $this->assertEquals($expected, $collection->toArray());
  1393. }
  1394. /**
  1395. * Tests the nest method with more than one level
  1396. *
  1397. * @return void
  1398. */
  1399. public function testNestMultiLevelAlternateNestingKey()
  1400. {
  1401. $items = [
  1402. ['id' => 1, 'parent_id' => null],
  1403. ['id' => 2, 'parent_id' => 1],
  1404. ['id' => 3, 'parent_id' => 2],
  1405. ['id' => 4, 'parent_id' => 2],
  1406. ['id' => 5, 'parent_id' => 3],
  1407. ['id' => 6, 'parent_id' => null],
  1408. ['id' => 7, 'parent_id' => 3],
  1409. ['id' => 8, 'parent_id' => 4],
  1410. ['id' => 9, 'parent_id' => 6],
  1411. ['id' => 10, 'parent_id' => 6],
  1412. ];
  1413. $collection = (new Collection($items))->nest('id', 'parent_id');
  1414. $expected = [
  1415. [
  1416. 'id' => 1,
  1417. 'parent_id' => null,
  1418. 'children' => [
  1419. [
  1420. 'id' => 2,
  1421. 'parent_id' => 1,
  1422. 'children' => [
  1423. [
  1424. 'id' => 3,
  1425. 'parent_id' => 2,
  1426. 'children' => [
  1427. ['id' => 5, 'parent_id' => 3, 'children' => []],
  1428. ['id' => 7, 'parent_id' => 3, 'children' => []],
  1429. ],
  1430. ],
  1431. [
  1432. 'id' => 4,
  1433. 'parent_id' => 2,
  1434. 'children' => [
  1435. ['id' => 8, 'parent_id' => 4, 'children' => []],
  1436. ],
  1437. ],
  1438. ],
  1439. ],
  1440. ],
  1441. ],
  1442. [
  1443. 'id' => 6,
  1444. 'parent_id' => null,
  1445. 'children' => [
  1446. ['id' => 9, 'parent_id' => 6, 'children' => []],
  1447. ['id' => 10, 'parent_id' => 6, 'children' => []],
  1448. ],
  1449. ],
  1450. ];
  1451. $this->assertEquals($expected, $collection->toArray());
  1452. }
  1453. /**
  1454. * Tests the nest method with more than one level
  1455. *
  1456. * @return void
  1457. */
  1458. public function testNestObjects()
  1459. {
  1460. $items = [
  1461. new ArrayObject(['id' => 1, 'parent_id' => null]),
  1462. new ArrayObject(['id' => 2, 'parent_id' => 1]),
  1463. new ArrayObject(['id' => 3, 'parent_id' => 2]),
  1464. new ArrayObject(['id' => 4, 'parent_id' => 2]),
  1465. new ArrayObject(['id' => 5, 'parent_id' => 3]),
  1466. new ArrayObject(['id' => 6, 'parent_id' => null]),
  1467. new ArrayObject(['id' => 7, 'parent_id' => 3]),
  1468. new ArrayObject(['id' => 8, 'parent_id' => 4]),
  1469. new ArrayObject(['id' => 9, 'parent_id' => 6]),
  1470. new ArrayObject(['id' => 10, 'parent_id' => 6]),
  1471. ];
  1472. $collection = (new Collection($items))->nest('id', 'parent_id');
  1473. $expected = [
  1474. new ArrayObject([
  1475. 'id' => 1,
  1476. 'parent_id' => null,
  1477. 'children' => [
  1478. new ArrayObject([
  1479. 'id' => 2,
  1480. 'parent_id' => 1,
  1481. 'children' => [
  1482. new ArrayObject([
  1483. 'id' => 3,
  1484. 'parent_id' => 2,
  1485. 'children' => [
  1486. new ArrayObject(['id' => 5, 'parent_id' => 3, 'children' => []]),
  1487. new ArrayObject(['id' => 7, 'parent_id' => 3, 'children' => []]),
  1488. ],
  1489. ]),
  1490. new ArrayObject([
  1491. 'id' => 4,
  1492. 'parent_id' => 2,
  1493. 'children' => [
  1494. new ArrayObject(['id' => 8, 'parent_id' => 4, 'children' => []]),
  1495. ],
  1496. ]),
  1497. ],
  1498. ]),
  1499. ],
  1500. ]),
  1501. new ArrayObject([
  1502. 'id' => 6,
  1503. 'parent_id' => null,
  1504. 'children' => [
  1505. new ArrayObject(['id' => 9, 'parent_id' => 6, 'children' => []]),
  1506. new ArrayObject(['id' => 10, 'parent_id' => 6, 'children' => []]),
  1507. ],
  1508. ]),
  1509. ];
  1510. $this->assertEquals($expected, $collection->toArray());
  1511. }
  1512. /**
  1513. * Tests the nest method with more than one level
  1514. *
  1515. * @return void
  1516. */
  1517. public function testNestObjectsAlternateNestingKey()
  1518. {
  1519. $items = [
  1520. new ArrayObject(['id' => 1, 'parent_id' => null]),
  1521. new ArrayObject(['id' => 2, 'parent_id' => 1]),
  1522. new ArrayObject(['id' => 3, 'parent_id' => 2]),
  1523. new ArrayObject(['id' => 4, 'parent_id' => 2]),
  1524. new ArrayObject(['id' => 5, 'parent_id' => 3]),
  1525. new ArrayObject(['id' => 6, 'parent_id' => null]),
  1526. new ArrayObject(['id' => 7, 'parent_id' => 3]),
  1527. new ArrayObject(['id' => 8, 'parent_id' => 4]),
  1528. new ArrayObject(['id' => 9, 'parent_id' => 6]),
  1529. new ArrayObject(['id' => 10, 'parent_id' => 6]),
  1530. ];
  1531. $collection = (new Collection($items))->nest('id', 'parent_id', 'nodes');
  1532. $expected = [
  1533. new ArrayObject([
  1534. 'id' => 1,
  1535. 'parent_id' => null,
  1536. 'nodes' => [
  1537. new ArrayObject([
  1538. 'id' => 2,
  1539. 'parent_id' => 1,
  1540. 'nodes' => [
  1541. new ArrayObject([
  1542. 'id' => 3,
  1543. 'parent_id' => 2,
  1544. 'nodes' => [
  1545. new ArrayObject(['id' => 5, 'parent_id' => 3, 'nodes' => []]),
  1546. new ArrayObject(['id' => 7, 'parent_id' => 3, 'nodes' => []]),
  1547. ],
  1548. ]),
  1549. new ArrayObject([
  1550. 'id' => 4,
  1551. 'parent_id' => 2,
  1552. 'nodes' => [
  1553. new ArrayObject(['id' => 8, 'parent_id' => 4, 'nodes' => []]),
  1554. ],
  1555. ]),
  1556. ],
  1557. ]),
  1558. ],
  1559. ]),
  1560. new ArrayObject([
  1561. 'id' => 6,
  1562. 'parent_id' => null,
  1563. 'nodes' => [
  1564. new ArrayObject(['id' => 9, 'parent_id' => 6, 'nodes' => []]),
  1565. new ArrayObject(['id' => 10, 'parent_id' => 6, 'nodes' => []]),
  1566. ],
  1567. ]),
  1568. ];
  1569. $this->assertEquals($expected, $collection->toArray());
  1570. }
  1571. /**
  1572. * Tests insert
  1573. *
  1574. * @return void
  1575. */
  1576. public function testInsert()
  1577. {
  1578. $items = [['a' => 1], ['b' => 2]];
  1579. $collection = new Collection($items);
  1580. $iterator = $collection->insert('c', [3, 4]);
  1581. $this->assertInstanceOf('Cake\Collection\Iterator\InsertIterator', $iterator);
  1582. $this->assertEquals(
  1583. [['a' => 1, 'c' => 3], ['b' => 2, 'c' => 4]],
  1584. iterator_to_array($iterator)
  1585. );
  1586. }
  1587. /**
  1588. * Provider for testing each of the directions for listNested
  1589. *
  1590. * @return array
  1591. */
  1592. public function nestedListProvider()
  1593. {
  1594. return [
  1595. ['desc', [1, 2, 3, 5, 7, 4, 8, 6, 9, 10]],
  1596. ['asc', [5, 7, 3, 8, 4, 2, 1, 9, 10, 6]],
  1597. ['leaves', [5, 7, 8, 9, 10]],
  1598. ];
  1599. }
  1600. /**
  1601. * Tests the listNested method with the default 'children' nesting key
  1602. *
  1603. * @dataProvider nestedListProvider
  1604. * @return void
  1605. */
  1606. public function testListNested($dir, $expected)
  1607. {
  1608. $items = [
  1609. ['id' => 1, 'parent_id' => null],
  1610. ['id' => 2, 'parent_id' => 1],
  1611. ['id' => 3, 'parent_id' => 2],
  1612. ['id' => 4, 'parent_id' => 2],
  1613. ['id' => 5, 'parent_id' => 3],
  1614. ['id' => 6, 'parent_id' => null],
  1615. ['id' => 7, 'parent_id' => 3],
  1616. ['id' => 8, 'parent_id' => 4],
  1617. ['id' => 9, 'parent_id' => 6],
  1618. ['id' => 10, 'parent_id' => 6],
  1619. ];
  1620. $collection = (new Collection($items))->nest('id', 'parent_id')->listNested($dir);
  1621. $this->assertEquals($expected, $collection->extract('id')->toArray(false));
  1622. }
  1623. /**
  1624. * Tests using listNested with a different nesting key
  1625. *
  1626. * @return void
  1627. */
  1628. public function testListNestedCustomKey()
  1629. {
  1630. $items = [
  1631. ['id' => 1, 'stuff' => [['id' => 2, 'stuff' => [['id' => 3]]]]],
  1632. ['id' => 4, 'stuff' => [['id' => 5]]],
  1633. ];
  1634. $collection = (new Collection($items))->listNested('desc', 'stuff');
  1635. $this->assertEquals(range(1, 5), $collection->extract('id')->toArray(false));
  1636. }
  1637. /**
  1638. * Tests flattening the collection using a custom callable function
  1639. *
  1640. * @return void
  1641. */
  1642. public function testListNestedWithCallable()
  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', function ($item) {
  1649. return isset($item['stuff']) ? $item['stuff'] : [];
  1650. });
  1651. $this->assertEquals(range(1, 5), $collection->extract('id')->toArray(false));
  1652. }
  1653. /**
  1654. * Provider for sumOf tests
  1655. *
  1656. * @return array
  1657. */
  1658. public function sumOfProvider()
  1659. {
  1660. $items = [
  1661. ['invoice' => ['total' => 100]],
  1662. ['invoice' => ['total' => 200]],
  1663. ];
  1664. return [
  1665. 'array' => [$items],
  1666. 'iterator' => [$this->yieldItems($items)],
  1667. ];
  1668. }
  1669. /**
  1670. * Tests the sumOf method
  1671. *
  1672. * @dataProvider sumOfProvider
  1673. * @return void
  1674. */
  1675. public function testSumOf($items)
  1676. {
  1677. $this->assertEquals(300, (new Collection($items))->sumOf('invoice.total'));
  1678. }
  1679. /**
  1680. * Tests the sumOf method
  1681. *
  1682. * @dataProvider sumOfProvider
  1683. * @return void
  1684. */
  1685. public function testSumOfCallable($items)
  1686. {
  1687. $sum = (new Collection($items))->sumOf(function ($v) {
  1688. return $v['invoice']['total'] * 2;
  1689. });
  1690. $this->assertEquals(600, $sum);
  1691. }
  1692. /**
  1693. * Tests the stopWhen method with a callable
  1694. *
  1695. * @dataProvider simpleProvider
  1696. * @return void
  1697. */
  1698. public function testStopWhenCallable($items)
  1699. {
  1700. $collection = (new Collection($items))->stopWhen(function ($v) {
  1701. return $v > 3;
  1702. });
  1703. $this->assertEquals(['a' => 1, 'b' => 2, 'c' => 3], $collection->toArray());
  1704. }
  1705. /**
  1706. * Tests the stopWhen method with a matching array
  1707. *
  1708. * @return void
  1709. */
  1710. public function testStopWhenWithArray()
  1711. {
  1712. $items = [
  1713. ['foo' => 'bar'],
  1714. ['foo' => 'baz'],
  1715. ['foo' => 'foo'],
  1716. ];
  1717. $collection = (new Collection($items))->stopWhen(['foo' => 'baz']);
  1718. $this->assertEquals([['foo' => 'bar']], $collection->toArray());
  1719. }
  1720. /**
  1721. * Tests the unfold method
  1722. *
  1723. * @return void
  1724. */
  1725. public function testUnfold()
  1726. {
  1727. $items = [
  1728. [1, 2, 3, 4],
  1729. [5, 6],
  1730. [7, 8],
  1731. ];
  1732. $collection = (new Collection($items))->unfold();
  1733. $this->assertEquals(range(1, 8), $collection->toArray(false));
  1734. $items = [
  1735. [1, 2],
  1736. new Collection([3, 4]),
  1737. ];
  1738. $collection = (new Collection($items))->unfold();
  1739. $this->assertEquals(range(1, 4), $collection->toArray(false));
  1740. }
  1741. /**
  1742. * Tests the unfold method with empty levels
  1743. *
  1744. * @return void
  1745. */
  1746. public function testUnfoldEmptyLevels()
  1747. {
  1748. $items = [[], [1, 2], []];
  1749. $collection = (new Collection($items))->unfold();
  1750. $this->assertEquals(range(1, 2), $collection->toArray(false));
  1751. $items = [];
  1752. $collection = (new Collection($items))->unfold();
  1753. $this->assertEmpty($collection->toArray(false));
  1754. }
  1755. /**
  1756. * Tests the unfold when passing a callable
  1757. *
  1758. * @return void
  1759. */
  1760. public function testUnfoldWithCallable()
  1761. {
  1762. $items = [1, 2, 3];
  1763. $collection = (new Collection($items))->unfold(function ($item) {
  1764. return range($item, $item * 2);
  1765. });
  1766. $expected = [1, 2, 2, 3, 4, 3, 4, 5, 6];
  1767. $this->assertEquals($expected, $collection->toArray(false));
  1768. }
  1769. /**
  1770. * Tests the through() method
  1771. *
  1772. * @return void
  1773. */
  1774. public function testThrough()
  1775. {
  1776. $items = [1, 2, 3];
  1777. $collection = (new Collection($items))->through(function ($collection) {
  1778. return $collection->append($collection->toList());
  1779. });
  1780. $this->assertEquals([1, 2, 3, 1, 2, 3], $collection->toList());
  1781. }
  1782. /**
  1783. * Tests the through method when it returns an array
  1784. *
  1785. * @return void
  1786. */
  1787. public function testThroughReturnArray()
  1788. {
  1789. $items = [1, 2, 3];
  1790. $collection = (new Collection($items))->through(function ($collection) {
  1791. $list = $collection->toList();
  1792. return array_merge($list, $list);
  1793. });
  1794. $this->assertEquals([1, 2, 3, 1, 2, 3], $collection->toList());
  1795. }
  1796. /**
  1797. * Tests that the sortBy method does not die when something that is not a
  1798. * collection is passed
  1799. *
  1800. * @return void
  1801. */
  1802. public function testComplexSortBy()
  1803. {
  1804. $results = collection([3, 7])
  1805. ->unfold(function ($value) {
  1806. return [
  1807. ['sorting' => $value * 2],
  1808. ['sorting' => $value * 2],
  1809. ];
  1810. })
  1811. ->sortBy('sorting')
  1812. ->extract('sorting')
  1813. ->toList();
  1814. $this->assertEquals([14, 14, 6, 6], $results);
  1815. }
  1816. /**
  1817. * Tests __debugInfo() or debug() usage
  1818. *
  1819. * @return void
  1820. */
  1821. public function testDebug()
  1822. {
  1823. $items = [1, 2, 3];
  1824. $collection = new Collection($items);
  1825. $result = $collection->__debugInfo();
  1826. $expected = [
  1827. 'count' => 3,
  1828. ];
  1829. $this->assertSame($expected, $result);
  1830. // Calling it again will rewind
  1831. $result = $collection->__debugInfo();
  1832. $expected = [
  1833. 'count' => 3,
  1834. ];
  1835. $this->assertSame($expected, $result);
  1836. // Make sure it also works with non rewindable iterators
  1837. $iterator = new NoRewindIterator(new ArrayIterator($items));
  1838. $collection = new Collection($iterator);
  1839. $result = $collection->__debugInfo();
  1840. $expected = [
  1841. 'count' => 3,
  1842. ];
  1843. $this->assertSame($expected, $result);
  1844. // Calling it again will in this case not rewind
  1845. $result = $collection->__debugInfo();
  1846. $expected = [
  1847. 'count' => 0,
  1848. ];
  1849. $this->assertSame($expected, $result);
  1850. }
  1851. /**
  1852. * Tests the isEmpty() method
  1853. *
  1854. * @return void
  1855. */
  1856. public function testIsEmpty()
  1857. {
  1858. $collection = new Collection([1, 2, 3]);
  1859. $this->assertFalse($collection->isEmpty());
  1860. $collection = $collection->map(function () {
  1861. return null;
  1862. });
  1863. $this->assertFalse($collection->isEmpty());
  1864. $collection = $collection->filter();
  1865. $this->assertTrue($collection->isEmpty());
  1866. }
  1867. /**
  1868. * Tests the isEmpty() method does not consume data
  1869. * from buffered iterators.
  1870. *
  1871. * @return void
  1872. */
  1873. public function testIsEmptyDoesNotConsume()
  1874. {
  1875. $array = new \ArrayIterator([1, 2, 3]);
  1876. $inner = new \Cake\Collection\Iterator\BufferedIterator($array);
  1877. $collection = new Collection($inner);
  1878. $this->assertFalse($collection->isEmpty());
  1879. $this->assertCount(3, $collection->toArray());
  1880. }
  1881. /**
  1882. * Tests the zip() method
  1883. *
  1884. * @return void
  1885. */
  1886. public function testZip()
  1887. {
  1888. $collection = new Collection([1, 2]);
  1889. $zipped = $collection->zip([3, 4]);
  1890. $this->assertEquals([[1, 3], [2, 4]], $zipped->toList());
  1891. $collection = new Collection([1, 2]);
  1892. $zipped = $collection->zip([3]);
  1893. $this->assertEquals([[1, 3]], $zipped->toList());
  1894. $collection = new Collection([1, 2]);
  1895. $zipped = $collection->zip([3, 4], [5, 6], [7, 8], [9, 10, 11]);
  1896. $this->assertEquals([
  1897. [1, 3, 5, 7, 9],
  1898. [2, 4, 6, 8, 10],
  1899. ], $zipped->toList());
  1900. }
  1901. /**
  1902. * Tests the zipWith() method
  1903. *
  1904. * @return void
  1905. */
  1906. public function testZipWith()
  1907. {
  1908. $collection = new Collection([1, 2]);
  1909. $zipped = $collection->zipWith([3, 4], function ($a, $b) {
  1910. return $a * $b;
  1911. });
  1912. $this->assertEquals([3, 8], $zipped->toList());
  1913. $zipped = $collection->zipWith([3, 4], [5, 6, 7], function (...$args) {
  1914. return array_sum($args);
  1915. });
  1916. $this->assertEquals([9, 12], $zipped->toList());
  1917. }
  1918. /**
  1919. * Tests the skip() method
  1920. *
  1921. * @return void
  1922. */
  1923. public function testSkip()
  1924. {
  1925. $collection = new Collection([1, 2, 3, 4, 5]);
  1926. $this->assertEquals([3, 4, 5], $collection->skip(2)->toList());
  1927. $this->assertEquals([1, 2, 3, 4, 5], $collection->skip(0)->toList());
  1928. $this->assertEquals([4, 5], $collection->skip(3)->toList());
  1929. $this->assertEquals([5], $collection->skip(4)->toList());
  1930. }
  1931. /**
  1932. * Test skip() with an overflow
  1933. *
  1934. * @return void
  1935. */
  1936. public function testSkipOverflow()
  1937. {
  1938. $collection = new Collection([1, 2, 3]);
  1939. $this->assertEquals([], $collection->skip(3)->toArray());
  1940. $this->assertEquals([], $collection->skip(4)->toArray());
  1941. }
  1942. /**
  1943. * Tests the skip() method with a traversable non-iterator
  1944. *
  1945. * @return void
  1946. */
  1947. public function testSkipWithTraversableNonIterator()
  1948. {
  1949. $collection = new Collection($this->datePeriod('2017-01-01', '2017-01-07'));
  1950. $result = $collection->skip(3)->toList();
  1951. $expected = [
  1952. new \DateTime('2017-01-04'),
  1953. new \DateTime('2017-01-05'),
  1954. new \DateTime('2017-01-06'),
  1955. ];
  1956. $this->assertEquals($expected, $result);
  1957. }
  1958. /**
  1959. * Tests the first() method with a traversable non-iterator
  1960. *
  1961. * @return void
  1962. */
  1963. public function testFirstWithTraversableNonIterator()
  1964. {
  1965. $collection = new Collection($this->datePeriod('2017-01-01', '2017-01-07'));
  1966. $date = $collection->first();
  1967. $this->assertInstanceOf('DateTime', $date);
  1968. $this->assertEquals('2017-01-01', $date->format('Y-m-d'));
  1969. }
  1970. /**
  1971. * Tests the last() method
  1972. *
  1973. * @return void
  1974. */
  1975. public function testLast()
  1976. {
  1977. $collection = new Collection([1, 2, 3]);
  1978. $this->assertEquals(3, $collection->last());
  1979. $collection = $collection->map(function ($e) {
  1980. return $e * 2;
  1981. });
  1982. $this->assertEquals(6, $collection->last());
  1983. }
  1984. /**
  1985. * Tests the last() method when on an empty collection
  1986. *
  1987. * @return void
  1988. */
  1989. public function testLastWithEmptyCollection()
  1990. {
  1991. $collection = new Collection([]);
  1992. $this->assertNull($collection->last());
  1993. }
  1994. /**
  1995. * Tests the last() method with a countable object
  1996. *
  1997. * @return void
  1998. */
  1999. public function testLastWithCountable()
  2000. {
  2001. $collection = new Collection(new ArrayObject([1, 2, 3]));
  2002. $this->assertEquals(3, $collection->last());
  2003. }
  2004. /**
  2005. * Tests the last() method with an empty countable object
  2006. *
  2007. * @return void
  2008. */
  2009. public function testLastWithEmptyCountable()
  2010. {
  2011. $collection = new Collection(new ArrayObject([]));
  2012. $this->assertNull($collection->last());
  2013. }
  2014. /**
  2015. * Tests the last() method with a non-rewindable iterator
  2016. *
  2017. * @return void
  2018. */
  2019. public function testLastWithNonRewindableIterator()
  2020. {
  2021. $iterator = new NoRewindIterator(new ArrayIterator([1, 2, 3]));
  2022. $collection = new Collection($iterator);
  2023. $this->assertEquals(3, $collection->last());
  2024. }
  2025. /**
  2026. * Tests the last() method with a traversable non-iterator
  2027. *
  2028. * @return void
  2029. */
  2030. public function testLastWithTraversableNonIterator()
  2031. {
  2032. $collection = new Collection($this->datePeriod('2017-01-01', '2017-01-07'));
  2033. $date = $collection->last();
  2034. $this->assertInstanceOf('DateTime', $date);
  2035. $this->assertEquals('2017-01-06', $date->format('Y-m-d'));
  2036. }
  2037. /**
  2038. * Tests the takeLast() method
  2039. *
  2040. * @dataProvider simpleProvider
  2041. * @param array $data The data to test with.
  2042. * @return void
  2043. * @covers ::takeLast
  2044. */
  2045. public function testLastN($data)
  2046. {
  2047. $collection = new Collection($data);
  2048. $result = $collection->takeLast(3)->toArray();
  2049. $expected = ['b' => 2, 'c' => 3, 'd' => 4];
  2050. $this->assertEquals($expected, $result);
  2051. }
  2052. /**
  2053. * Tests the takeLast() method with overflow
  2054. *
  2055. * @dataProvider simpleProvider
  2056. * @param array $data The data to test with.
  2057. * @return void
  2058. * @covers ::takeLast
  2059. */
  2060. public function testLastNtWithOverflow($data)
  2061. {
  2062. $collection = new Collection($data);
  2063. $result = $collection->takeLast(10)->toArray();
  2064. $expected = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4];
  2065. $this->assertEquals($expected, $result);
  2066. }
  2067. /**
  2068. * Tests the takeLast() with an odd numbers collection
  2069. *
  2070. * @dataProvider simpleProvider
  2071. * @param array $data The data to test with.
  2072. * @return void
  2073. * @covers ::takeLast
  2074. */
  2075. public function testLastNtWithOddData($data)
  2076. {
  2077. $collection = new Collection($data);
  2078. $result = $collection->take(3)->takeLast(2)->toArray();
  2079. $expected = ['b' => 2, 'c' => 3];
  2080. $this->assertEquals($expected, $result);
  2081. }
  2082. /**
  2083. * Tests the takeLast() with countable collection
  2084. *
  2085. * @return void
  2086. * @covers ::takeLast
  2087. */
  2088. public function testLastNtWithCountable()
  2089. {
  2090. $rangeZeroToFive = range(0, 5);
  2091. $collection = new Collection(new CountableIterator($rangeZeroToFive));
  2092. $result = $collection->takeLast(2)->toList();
  2093. $this->assertEquals([4, 5], $result);
  2094. $collection = new Collection(new CountableIterator($rangeZeroToFive));
  2095. $result = $collection->takeLast(1)->toList();
  2096. $this->assertEquals([5], $result);
  2097. }
  2098. /**
  2099. * Tests the takeLast() with countable collection
  2100. *
  2101. * @dataProvider simpleProvider
  2102. * @param array $data The data to test with.
  2103. * @return void
  2104. * @covers ::takeLast
  2105. */
  2106. public function testLastNtWithNegative($data)
  2107. {
  2108. $collection = new Collection($data);
  2109. $this->expectException(\InvalidArgumentException::class);
  2110. $this->expectExceptionMessage('The takeLast method requires a number greater than 0.');
  2111. $collection->takeLast(-1)->toArray();
  2112. }
  2113. /**
  2114. * Tests sumOf with no parameters
  2115. *
  2116. * @return void
  2117. */
  2118. public function testSumOfWithIdentity()
  2119. {
  2120. $collection = new Collection([1, 2, 3]);
  2121. $this->assertEquals(6, $collection->sumOf());
  2122. $collection = new Collection(['a' => 1, 'b' => 4, 'c' => 6]);
  2123. $this->assertEquals(11, $collection->sumOf());
  2124. }
  2125. /**
  2126. * Tests using extract with the {*} notation
  2127. *
  2128. * @return void
  2129. */
  2130. public function testUnfoldedExtract()
  2131. {
  2132. $items = [
  2133. ['comments' => [['id' => 1], ['id' => 2]]],
  2134. ['comments' => [['id' => 3], ['id' => 4]]],
  2135. ['comments' => [['id' => 7], ['nope' => 8]]],
  2136. ];
  2137. $extracted = (new Collection($items))->extract('comments.{*}.id');
  2138. $this->assertEquals([1, 2, 3, 4, 7, null], $extracted->toArray());
  2139. $items = [
  2140. [
  2141. 'comments' => [
  2142. [
  2143. 'voters' => [['id' => 1], ['id' => 2]],
  2144. ],
  2145. ],
  2146. ],
  2147. [
  2148. 'comments' => [
  2149. [
  2150. 'voters' => [['id' => 3], ['id' => 4]],
  2151. ],
  2152. ],
  2153. ],
  2154. [
  2155. 'comments' => [
  2156. [
  2157. 'voters' => [['id' => 5], ['nope' => 'fail'], ['id' => 6]],
  2158. ],
  2159. ],
  2160. ],
  2161. [
  2162. 'comments' => [
  2163. [
  2164. 'not_voters' => [['id' => 5]],
  2165. ],
  2166. ],
  2167. ],
  2168. ['not_comments' => []],
  2169. ];
  2170. $extracted = (new Collection($items))->extract('comments.{*}.voters.{*}.id');
  2171. $expected = [1, 2, 3, 4, 5, null, 6];
  2172. $this->assertEquals($expected, $extracted->toArray());
  2173. $this->assertEquals($expected, $extracted->toList());
  2174. }
  2175. /**
  2176. * Tests serializing a simple collection
  2177. *
  2178. * @return void
  2179. */
  2180. public function testSerializeSimpleCollection()
  2181. {
  2182. $collection = new Collection([1, 2, 3]);
  2183. $serialized = serialize($collection);
  2184. $unserialized = unserialize($serialized);
  2185. $this->assertEquals($collection->toList(), $unserialized->toList());
  2186. $this->assertEquals($collection->toArray(), $unserialized->toArray());
  2187. }
  2188. /**
  2189. * Tests serialization when using append
  2190. *
  2191. * @return void
  2192. */
  2193. public function testSerializeWithAppendIterators()
  2194. {
  2195. $collection = new Collection([1, 2, 3]);
  2196. $collection = $collection->append(['a' => 4, 'b' => 5, 'c' => 6]);
  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 nested iterators
  2204. *
  2205. * @return void
  2206. */
  2207. public function testSerializeWithNestedIterators()
  2208. {
  2209. $collection = new Collection([1, 2, 3]);
  2210. $collection = $collection->map(function ($e) {
  2211. return $e * 3;
  2212. });
  2213. $collection = $collection->groupBy(function ($e) {
  2214. return $e % 2;
  2215. });
  2216. $serialized = serialize($collection);
  2217. $unserialized = unserialize($serialized);
  2218. $this->assertEquals($collection->toList(), $unserialized->toList());
  2219. $this->assertEquals($collection->toArray(), $unserialized->toArray());
  2220. }
  2221. /**
  2222. * Tests serializing a zip() call
  2223. *
  2224. * @return void
  2225. */
  2226. public function testSerializeWithZipIterator()
  2227. {
  2228. $collection = new Collection([4, 5]);
  2229. $collection = $collection->zip([1, 2]);
  2230. $serialized = serialize($collection);
  2231. $unserialized = unserialize($serialized);
  2232. $this->assertEquals($collection->toList(), $unserialized->toList());
  2233. }
  2234. /**
  2235. * Provider for some chunk tests
  2236. *
  2237. * @return array
  2238. */
  2239. public function chunkProvider()
  2240. {
  2241. $items = range(1, 10);
  2242. return [
  2243. 'array' => [$items],
  2244. 'iterator' => [$this->yieldItems($items)],
  2245. ];
  2246. }
  2247. /**
  2248. * Tests the chunk method with exact chunks
  2249. *
  2250. * @dataProvider chunkProvider
  2251. * @return void
  2252. */
  2253. public function testChunk($items)
  2254. {
  2255. $collection = new Collection($items);
  2256. $chunked = $collection->chunk(2)->toList();
  2257. $expected = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]];
  2258. $this->assertEquals($expected, $chunked);
  2259. }
  2260. /**
  2261. * Tests the chunk method with overflowing chunk size
  2262. *
  2263. * @return void
  2264. */
  2265. public function testChunkOverflow()
  2266. {
  2267. $collection = new Collection(range(1, 11));
  2268. $chunked = $collection->chunk(2)->toList();
  2269. $expected = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11]];
  2270. $this->assertEquals($expected, $chunked);
  2271. }
  2272. /**
  2273. * Tests the chunk method with non-scalar items
  2274. *
  2275. * @return void
  2276. */
  2277. public function testChunkNested()
  2278. {
  2279. $collection = new Collection([1, 2, 3, [4, 5], 6, [7, [8, 9], 10], 11]);
  2280. $chunked = $collection->chunk(2)->toList();
  2281. $expected = [[1, 2], [3, [4, 5]], [6, [7, [8, 9], 10]], [11]];
  2282. $this->assertEquals($expected, $chunked);
  2283. }
  2284. /**
  2285. * Tests the chunkWithKeys method with exact chunks
  2286. *
  2287. * @return void
  2288. */
  2289. public function testChunkWithKeys()
  2290. {
  2291. $collection = new Collection(['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6]);
  2292. $chunked = $collection->chunkWithKeys(2)->toList();
  2293. $expected = [['a' => 1, 'b' => 2], ['c' => 3, 'd' => 4], ['e' => 5, 'f' => 6]];
  2294. $this->assertEquals($expected, $chunked);
  2295. }
  2296. /**
  2297. * Tests the chunkWithKeys method with overflowing chunk size
  2298. *
  2299. * @return void
  2300. */
  2301. public function testChunkWithKeysOverflow()
  2302. {
  2303. $collection = new Collection(['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6, 'g' => 7]);
  2304. $chunked = $collection->chunkWithKeys(2)->toList();
  2305. $expected = [['a' => 1, 'b' => 2], ['c' => 3, 'd' => 4], ['e' => 5, 'f' => 6], ['g' => 7]];
  2306. $this->assertEquals($expected, $chunked);
  2307. }
  2308. /**
  2309. * Tests the chunkWithKeys method with non-scalar items
  2310. *
  2311. * @return void
  2312. */
  2313. public function testChunkWithKeysNested()
  2314. {
  2315. $collection = new Collection(['a' => 1, 'b' => 2, 'c' => 3, 'd' => [4, 5], 'e' => 6, 'f' => [7, [8, 9], 10], 'g' => 11]);
  2316. $chunked = $collection->chunkWithKeys(2)->toList();
  2317. $expected = [['a' => 1, 'b' => 2], ['c' => 3, 'd' => [4, 5]], ['e' => 6, 'f' => [7, [8, 9], 10]], ['g' => 11]];
  2318. $this->assertEquals($expected, $chunked);
  2319. }
  2320. /**
  2321. * Tests the chunkWithKeys method without preserving keys
  2322. *
  2323. * @return void
  2324. */
  2325. public function testChunkWithKeysNoPreserveKeys()
  2326. {
  2327. $collection = new Collection(['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6, 'g' => 7]);
  2328. $chunked = $collection->chunkWithKeys(2, false)->toList();
  2329. $expected = [[0 => 1, 1 => 2], [0 => 3, 1 => 4], [0 => 5, 1 => 6], [0 => 7]];
  2330. $this->assertEquals($expected, $chunked);
  2331. }
  2332. /**
  2333. * Tests cartesianProduct
  2334. *
  2335. * @return void
  2336. */
  2337. public function testCartesianProduct()
  2338. {
  2339. $collection = new Collection([]);
  2340. $result = $collection->cartesianProduct();
  2341. $expected = [];
  2342. $this->assertEquals($expected, $result->toList());
  2343. $collection = new Collection([['A', 'B', 'C'], [1, 2, 3]]);
  2344. $result = $collection->cartesianProduct();
  2345. $expected = [
  2346. ['A', 1],
  2347. ['A', 2],
  2348. ['A', 3],
  2349. ['B', 1],
  2350. ['B', 2],
  2351. ['B', 3],
  2352. ['C', 1],
  2353. ['C', 2],
  2354. ['C', 3],
  2355. ];
  2356. $this->assertEquals($expected, $result->toList());
  2357. $collection = new Collection([[1, 2, 3], ['A', 'B', 'C'], ['a', 'b', 'c']]);
  2358. $result = $collection->cartesianProduct(function ($value) {
  2359. return [strval($value[0]) . $value[1] . $value[2]];
  2360. }, function ($value) {
  2361. return $value[0] >= 2;
  2362. });
  2363. $expected = [
  2364. ['2Aa'],
  2365. ['2Ab'],
  2366. ['2Ac'],
  2367. ['2Ba'],
  2368. ['2Bb'],
  2369. ['2Bc'],
  2370. ['2Ca'],
  2371. ['2Cb'],
  2372. ['2Cc'],
  2373. ['3Aa'],
  2374. ['3Ab'],
  2375. ['3Ac'],
  2376. ['3Ba'],
  2377. ['3Bb'],
  2378. ['3Bc'],
  2379. ['3Ca'],
  2380. ['3Cb'],
  2381. ['3Cc'],
  2382. ];
  2383. $this->assertEquals($expected, $result->toList());
  2384. $collection = new Collection([['1', '2', '3', '4'], ['A', 'B', 'C'], ['name', 'surname', 'telephone']]);
  2385. $result = $collection->cartesianProduct(function ($value) {
  2386. return [$value[0] => [$value[1] => $value[2]]];
  2387. }, function ($value) {
  2388. return $value[2] !== 'surname';
  2389. });
  2390. $expected = [
  2391. [1 => ['A' => 'name']],
  2392. [1 => ['A' => 'telephone']],
  2393. [1 => ['B' => 'name']],
  2394. [1 => ['B' => 'telephone']],
  2395. [1 => ['C' => 'name']],
  2396. [1 => ['C' => 'telephone']],
  2397. [2 => ['A' => 'name']],
  2398. [2 => ['A' => 'telephone']],
  2399. [2 => ['B' => 'name']],
  2400. [2 => ['B' => 'telephone']],
  2401. [2 => ['C' => 'name']],
  2402. [2 => ['C' => 'telephone']],
  2403. [3 => ['A' => 'name']],
  2404. [3 => ['A' => 'telephone']],
  2405. [3 => ['B' => 'name']],
  2406. [3 => ['B' => 'telephone']],
  2407. [3 => ['C' => 'name']],
  2408. [3 => ['C' => 'telephone']],
  2409. [4 => ['A' => 'name']],
  2410. [4 => ['A' => 'telephone']],
  2411. [4 => ['B' => 'name']],
  2412. [4 => ['B' => 'telephone']],
  2413. [4 => ['C' => 'name']],
  2414. [4 => ['C' => 'telephone']],
  2415. ];
  2416. $this->assertEquals($expected, $result->toList());
  2417. $collection = new Collection([
  2418. [
  2419. 'name1' => 'alex',
  2420. 'name2' => 'kostas',
  2421. 0 => 'leon',
  2422. ],
  2423. [
  2424. 'val1' => 'alex@example.com',
  2425. 24 => 'kostas@example.com',
  2426. 'val2' => 'leon@example.com',
  2427. ],
  2428. ]);
  2429. $result = $collection->cartesianProduct();
  2430. $expected = [
  2431. ['alex', 'alex@example.com'],
  2432. ['alex', 'kostas@example.com'],
  2433. ['alex', 'leon@example.com'],
  2434. ['kostas', 'alex@example.com'],
  2435. ['kostas', 'kostas@example.com'],
  2436. ['kostas', 'leon@example.com'],
  2437. ['leon', 'alex@example.com'],
  2438. ['leon', 'kostas@example.com'],
  2439. ['leon', 'leon@example.com'],
  2440. ];
  2441. $this->assertEquals($expected, $result->toList());
  2442. }
  2443. /**
  2444. * Tests that an exception is thrown if the cartesian product is called with multidimensional arrays
  2445. *
  2446. * @return void
  2447. */
  2448. public function testCartesianProductMultidimensionalArray()
  2449. {
  2450. $this->expectException(\LogicException::class);
  2451. $collection = new Collection([
  2452. [
  2453. 'names' => [
  2454. 'alex', 'kostas', 'leon',
  2455. ],
  2456. ],
  2457. [
  2458. 'locations' => [
  2459. 'crete', 'london', 'paris',
  2460. ],
  2461. ],
  2462. ]);
  2463. $result = $collection->cartesianProduct();
  2464. }
  2465. public function testTranspose()
  2466. {
  2467. $collection = new Collection([
  2468. ['Products', '2012', '2013', '2014'],
  2469. ['Product A', '200', '100', '50'],
  2470. ['Product B', '300', '200', '100'],
  2471. ['Product C', '400', '300', '200'],
  2472. ['Product D', '500', '400', '300'],
  2473. ]);
  2474. $transposed = $collection->transpose();
  2475. $expected = [
  2476. ['Products', 'Product A', 'Product B', 'Product C', 'Product D'],
  2477. ['2012', '200', '300', '400', '500'],
  2478. ['2013', '100', '200', '300', '400'],
  2479. ['2014', '50', '100', '200', '300'],
  2480. ];
  2481. $this->assertEquals($expected, $transposed->toList());
  2482. }
  2483. /**
  2484. * Tests that provided arrays do not have even length
  2485. *
  2486. * @return void
  2487. */
  2488. public function testTransposeUnEvenLengthShouldThrowException()
  2489. {
  2490. $this->expectException(\LogicException::class);
  2491. $collection = new Collection([
  2492. ['Products', '2012', '2013', '2014'],
  2493. ['Product A', '200', '100', '50'],
  2494. ['Product B', '300'],
  2495. ['Product C', '400', '300'],
  2496. ]);
  2497. $collection->transpose();
  2498. }
  2499. /**
  2500. * Yields all the elements as passed
  2501. *
  2502. * @param array $itmes the elements to be yielded
  2503. * @return void
  2504. */
  2505. protected function yieldItems(array $items)
  2506. {
  2507. foreach ($items as $k => $v) {
  2508. yield $k => $v;
  2509. }
  2510. }
  2511. /**
  2512. * Create a DatePeriod object.
  2513. *
  2514. * @param string $start Start date
  2515. * @param string $end End date
  2516. * @return \DatePeriod
  2517. */
  2518. protected function datePeriod($start, $end)
  2519. {
  2520. return new \DatePeriod(new \DateTime($start), new \DateInterval('P1D'), new \DateTime($end));
  2521. }
  2522. /**
  2523. * Tests to ensure that collection classes extending ArrayIterator work as expected.
  2524. *
  2525. * @return void
  2526. */
  2527. public function testArrayIteratorExtend()
  2528. {
  2529. $iterator = new TestIterator(range(0, 10));
  2530. $this->assertTrue(method_exists($iterator, 'checkValues'));
  2531. $this->assertTrue($iterator->checkValues());
  2532. //We need to perform at least two collection operation to trigger the issue.
  2533. $newIterator = $iterator
  2534. ->filter(function ($item) {
  2535. return $item < 5;
  2536. })
  2537. ->reject(function ($item) {
  2538. return $item > 2;
  2539. });
  2540. $this->assertTrue(method_exists($newIterator, 'checkValues'), 'Our method has gone missing!');
  2541. $this->assertTrue($newIterator->checkValues());
  2542. $this->assertCount(3, $newIterator->toArray());
  2543. }
  2544. /**
  2545. * Tests that elements in a lazy collection are not fetched immediately.
  2546. *
  2547. * @return void
  2548. */
  2549. public function testLazy()
  2550. {
  2551. $items = ['a' => 1, 'b' => 2, 'c' => 3];
  2552. $collection = (new Collection($items))->lazy();
  2553. $callable = $this->getMockBuilder(\StdClass::class)
  2554. ->setMethods(['__invoke'])
  2555. ->getMock();
  2556. $callable->expects($this->never())->method('__invoke');
  2557. $collection->filter($callable)->filter($callable);
  2558. }
  2559. }