CollectionTest.php 83 KB

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