CountsEnumerations.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. <?php
  2. namespace Illuminate\Tests\Support\Concerns;
  3. use Illuminate\Support\Collection;
  4. use Illuminate\Support\LazyCollection;
  5. trait CountsEnumerations
  6. {
  7. protected function makeGeneratorFunctionWithRecorder($numbers = 10)
  8. {
  9. $recorder = new Collection();
  10. $generatorFunction = function () use ($numbers, $recorder) {
  11. for ($i = 1; $i <= $numbers; $i++) {
  12. $recorder->push($i);
  13. yield $i;
  14. }
  15. };
  16. return [$generatorFunction, $recorder];
  17. }
  18. protected function assertDoesNotEnumerate(callable $executor)
  19. {
  20. $this->assertEnumerates(0, $executor);
  21. }
  22. protected function assertDoesNotEnumerateCollection(
  23. LazyCollection $collection,
  24. callable $executor
  25. ) {
  26. $this->assertEnumeratesCollection($collection, 0, $executor);
  27. }
  28. protected function assertEnumerates($count, callable $executor)
  29. {
  30. $this->assertEnumeratesCollection(
  31. LazyCollection::times(100),
  32. $count,
  33. $executor
  34. );
  35. }
  36. protected function assertEnumeratesCollection(
  37. LazyCollection $collection,
  38. $count,
  39. callable $executor
  40. ) {
  41. $enumerated = 0;
  42. $data = $this->countEnumerations($collection, $enumerated);
  43. $executor($data);
  44. $this->assertEnumerations($count, $enumerated);
  45. }
  46. protected function assertEnumeratesOnce(callable $executor)
  47. {
  48. $this->assertEnumeratesCollectionOnce(LazyCollection::times(10), $executor);
  49. }
  50. protected function assertEnumeratesCollectionOnce(
  51. LazyCollection $collection,
  52. callable $executor
  53. ) {
  54. $enumerated = 0;
  55. $count = $collection->count();
  56. $collection = $this->countEnumerations($collection, $enumerated);
  57. $executor($collection);
  58. $this->assertEquals(
  59. $count,
  60. $enumerated,
  61. $count > $enumerated ? 'Failed to enumerate in full.' : 'Enumerated more than once.'
  62. );
  63. }
  64. protected function assertEnumerations($expected, $actual)
  65. {
  66. $this->assertEquals(
  67. $expected,
  68. $actual,
  69. "Failed asserting that {$actual} items that were enumerated matches expected {$expected}."
  70. );
  71. }
  72. protected function countEnumerations(LazyCollection $collection, &$count)
  73. {
  74. return $collection->tapEach(function () use (&$count) {
  75. $count++;
  76. });
  77. }
  78. }