EventStack.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. <?php
  2. namespace Masterminds\HTML5\Tests\Parser;
  3. use Masterminds\HTML5\Elements;
  4. use Masterminds\HTML5\Parser\EventHandler;
  5. /**
  6. * This testing class gathers events from a parser and builds a stack of events.
  7. * It is useful for checking the output of a tokenizer.
  8. *
  9. * IMPORTANT:
  10. *
  11. * The startTag event also kicks the parser into TEXT_RAW when it encounters
  12. * script or pre tags. This is to match the behavior required by the HTML5 spec,
  13. * which says that the tree builder must tell the tokenizer when to switch states.
  14. */
  15. class EventStack implements EventHandler
  16. {
  17. protected $stack;
  18. public function __construct()
  19. {
  20. $this->stack = array();
  21. }
  22. /**
  23. * Get the event stack.
  24. */
  25. public function events()
  26. {
  27. return $this->stack;
  28. }
  29. public function depth()
  30. {
  31. return count($this->stack);
  32. }
  33. public function get($index)
  34. {
  35. return $this->stack[$index];
  36. }
  37. protected function store($event, $data = null)
  38. {
  39. $this->stack[] = array(
  40. 'name' => $event,
  41. 'data' => $data,
  42. );
  43. }
  44. public function doctype($name, $type = 0, $id = null, $quirks = false)
  45. {
  46. $args = array(
  47. $name,
  48. $type,
  49. $id,
  50. $quirks,
  51. );
  52. $this->store('doctype', $args);
  53. }
  54. public function startTag($name, $attributes = array(), $selfClosing = false)
  55. {
  56. $args = func_get_args();
  57. $this->store('startTag', $args);
  58. if ('pre' == $name || 'script' == $name) {
  59. return Elements::TEXT_RAW;
  60. }
  61. }
  62. public function endTag($name)
  63. {
  64. $this->store('endTag', array(
  65. $name,
  66. ));
  67. }
  68. public function comment($cdata)
  69. {
  70. $this->store('comment', array(
  71. $cdata,
  72. ));
  73. }
  74. public function cdata($data)
  75. {
  76. $this->store('cdata', func_get_args());
  77. }
  78. public function text($cdata)
  79. {
  80. // fprintf(STDOUT, "Received TEXT event with: " . $cdata);
  81. $this->store('text', array(
  82. $cdata,
  83. ));
  84. }
  85. public function eof()
  86. {
  87. $this->store('eof');
  88. }
  89. public function parseError($msg, $line, $col)
  90. {
  91. // throw new EventStackParseError(sprintf("%s (line %d, col %d)", $msg, $line, $col));
  92. // $this->store(sprintf("%s (line %d, col %d)", $msg, $line, $col));
  93. $this->store('error', func_get_args());
  94. }
  95. public function processingInstruction($name, $data = null)
  96. {
  97. $this->store('pi', func_get_args());
  98. }
  99. }