BufferedIteratorTest.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  11. * @link https://cakephp.org CakePHP(tm) Project
  12. * @since 3.0.0
  13. * @license https://opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Test\TestCase\Collection\Iterator;
  16. use ArrayObject;
  17. use Cake\Collection\Iterator\BufferedIterator;
  18. use Cake\TestSuite\TestCase;
  19. use NoRewindIterator;
  20. /**
  21. * BufferedIterator Test
  22. */
  23. class BufferedIteratorTest extends TestCase
  24. {
  25. /**
  26. * Tests that items are cached once iterated over them
  27. *
  28. * @return void
  29. */
  30. public function testBufferItems()
  31. {
  32. $items = new ArrayObject([
  33. 'a' => 1,
  34. 'b' => 2,
  35. 'c' => 3,
  36. ]);
  37. $iterator = new BufferedIterator($items);
  38. $expected = (array)$items;
  39. $this->assertSame($expected, $iterator->toArray());
  40. $items['c'] = 5;
  41. $buffered = $iterator->toArray();
  42. $this->assertSame($expected, $buffered);
  43. }
  44. /**
  45. * Tests that items are cached once iterated over them
  46. *
  47. * @return void
  48. */
  49. public function testCount()
  50. {
  51. $items = new ArrayObject([
  52. 'a' => 1,
  53. 'b' => 2,
  54. 'c' => 3,
  55. ]);
  56. $iterator = new BufferedIterator($items);
  57. $this->assertCount(3, $iterator);
  58. $buffered = $iterator->toArray();
  59. $this->assertSame((array)$items, $buffered);
  60. $iterator = new BufferedIterator(new NoRewindIterator($items->getIterator()));
  61. $this->assertCount(3, $iterator);
  62. $buffered = $iterator->toArray();
  63. $this->assertSame((array)$items, $buffered);
  64. }
  65. /**
  66. * Tests that partial iteration can be reset.
  67. *
  68. * @return void
  69. */
  70. public function testBufferPartial()
  71. {
  72. $items = new ArrayObject([1, 2, 3]);
  73. $iterator = new BufferedIterator($items);
  74. foreach ($iterator as $key => $value) {
  75. if ($key == 1) {
  76. break;
  77. }
  78. }
  79. $result = [];
  80. foreach ($iterator as $value) {
  81. $result[] = $value;
  82. }
  83. $this->assertEquals([1, 2, 3], $result);
  84. }
  85. }