CollectionTest.php 86 KB

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