BufferedIteratorTest.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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\Iterator;
  17. use ArrayObject;
  18. use Cake\Collection\Iterator\BufferedIterator;
  19. use Cake\TestSuite\TestCase;
  20. use NoRewindIterator;
  21. /**
  22. * BufferedIterator Test
  23. */
  24. class BufferedIteratorTest extends TestCase
  25. {
  26. /**
  27. * Tests that items are cached once iterated over them
  28. *
  29. * @return void
  30. */
  31. public function testBufferItems()
  32. {
  33. $items = new ArrayObject([
  34. 'a' => 1,
  35. 'b' => 2,
  36. 'c' => 3,
  37. ]);
  38. $iterator = new BufferedIterator($items);
  39. $expected = (array)$items;
  40. $this->assertSame($expected, $iterator->toArray());
  41. $items['c'] = 5;
  42. $buffered = $iterator->toArray();
  43. $this->assertSame($expected, $buffered);
  44. }
  45. /**
  46. * Tests that items are cached once iterated over them
  47. *
  48. * @return void
  49. */
  50. public function testCount()
  51. {
  52. $items = new ArrayObject([
  53. 'a' => 1,
  54. 'b' => 2,
  55. 'c' => 3,
  56. ]);
  57. $iterator = new BufferedIterator($items);
  58. $this->assertCount(3, $iterator);
  59. $buffered = $iterator->toArray();
  60. $this->assertSame((array)$items, $buffered);
  61. $iterator = new BufferedIterator(new NoRewindIterator($items->getIterator()));
  62. $this->assertCount(3, $iterator);
  63. $buffered = $iterator->toArray();
  64. $this->assertSame((array)$items, $buffered);
  65. }
  66. /**
  67. * Tests that partial iteration can be reset.
  68. *
  69. * @return void
  70. */
  71. public function testBufferPartial()
  72. {
  73. $items = new ArrayObject([1, 2, 3]);
  74. $iterator = new BufferedIterator($items);
  75. foreach ($iterator as $key => $value) {
  76. if ($key == 1) {
  77. break;
  78. }
  79. }
  80. $result = [];
  81. foreach ($iterator as $value) {
  82. $result[] = $value;
  83. }
  84. $this->assertEquals([1, 2, 3], $result);
  85. }
  86. }