NodeIteratorTest.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. declare(strict_types=1);
  3. /*
  4. * This file is part of the league/commonmark package.
  5. *
  6. * (c) Colin O'Dell <colinodell@gmail.com>
  7. *
  8. * For the full copyright and license information, please view the LICENSE
  9. * file that was distributed with this source code.
  10. */
  11. namespace League\CommonMark\Tests\Unit\Node;
  12. use League\CommonMark\Extension\CommonMark\Node\Inline\Emphasis;
  13. use League\CommonMark\Node\Block\Document;
  14. use League\CommonMark\Node\Block\Paragraph;
  15. use League\CommonMark\Node\Inline\Text;
  16. use PHPUnit\Framework\TestCase;
  17. final class NodeIteratorTest extends TestCase
  18. {
  19. public function testIterator(): void
  20. {
  21. $document = new Document();
  22. $document->appendChild($paragraph1 = new Paragraph());
  23. $paragraph1->appendChild($text1 = new Text());
  24. $paragraph1->appendChild($emphasis = new Emphasis('*'));
  25. $emphasis->appendChild($text2 = new Text());
  26. $document->appendChild($paragraph2 = new Paragraph());
  27. $paragraph2->appendChild($text3 = new Text());
  28. $iterator = $document->iterator();
  29. $expected = [
  30. 0 => $document,
  31. 1 => $paragraph1,
  32. 2 => $text1,
  33. 3 => $emphasis,
  34. 4 => $text2,
  35. 5 => $paragraph2,
  36. 6 => $text3,
  37. ];
  38. $this->assertSame($expected, \iterator_to_array($iterator));
  39. }
  40. public function testSiblingChangesWhileIterating(): void
  41. {
  42. $document = new Document();
  43. $document->appendChild($paragraph1 = new Paragraph());
  44. $paragraph1->appendChild($text1 = new Text());
  45. $paragraph1->appendChild($emphasis = new Emphasis('*'));
  46. $emphasis->appendChild($text2 = new Text());
  47. $paragraph1->appendChild($text3 = new Text());
  48. $this->assertCount(6, \iterator_to_array($document->iterator()));
  49. $nodes = [];
  50. foreach ($document->iterator() as $node) {
  51. $nodes[] = $node;
  52. // While iterating, removing the next() sibling node
  53. if ($node === $text1) {
  54. $emphasis->detach();
  55. }
  56. }
  57. $this->assertCount(6, $nodes); // All of the nodes were visited, including the detached sibling...
  58. $this->assertCount(4, \iterator_to_array($document->iterator())); // Even though that emphasis and its child were actually removed
  59. }
  60. }