Version 1
[yaffs-website] / vendor / masterminds / html5 / src / HTML5 / Parser / StringInputStream.php
1 <?php
2 /**
3  * Loads a string to be parsed.
4  */
5 namespace Masterminds\HTML5\Parser;
6
7 /*
8  *
9 * Based on code from html5lib:
10
11 Copyright 2009 Geoffrey Sneddon <http://gsnedders.com/>
12
13 Permission is hereby granted, free of charge, to any person obtaining a
14 copy of this software and associated documentation files (the
15     "Software"), to deal in the Software without restriction, including
16 without limitation the rights to use, copy, modify, merge, publish,
17 distribute, sublicense, and/or sell copies of the Software, and to
18 permit persons to whom the Software is furnished to do so, subject to
19 the following conditions:
20
21 The above copyright notice and this permission notice shall be included
22 in all copies or substantial portions of the Software.
23
24 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
25 OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
27 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
28 CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
29 TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
30 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
31
32 */
33
34 // Some conventions:
35 // - /* */ indicates verbatim text from the HTML 5 specification
36 //   MPB: Not sure which version of the spec. Moving from HTML5lib to
37 //   HTML5-PHP, I have been using this version:
38 //   http://www.w3.org/TR/2012/CR-html5-20121217/Overview.html#contents
39 //
40 // - // indicates regular comments
41
42 class StringInputStream implements InputStream
43 {
44
45     /**
46      * The string data we're parsing.
47      */
48     private $data;
49
50     /**
51      * The current integer byte position we are in $data
52      */
53     private $char;
54
55     /**
56      * Length of $data; when $char === $data, we are at the end-of-file.
57      */
58     private $EOF;
59
60     /**
61      * Parse errors.
62      */
63     public $errors = array();
64
65     /**
66      * Create a new InputStream wrapper.
67      *
68      * @param $data Data
69      *            to parse
70      */
71     public function __construct($data, $encoding = 'UTF-8', $debug = '')
72     {
73         $data = UTF8Utils::convertToUTF8($data, $encoding);
74         if ($debug)
75             fprintf(STDOUT, $debug, $data, strlen($data));
76
77             // There is good reason to question whether it makes sense to
78             // do this here, since most of these checks are done during
79             // parsing, and since this check doesn't actually *do* anything.
80         $this->errors = UTF8Utils::checkForIllegalCodepoints($data);
81         // if (!empty($e)) {
82         // throw new ParseError("UTF-8 encoding issues: " . implode(', ', $e));
83         // }
84
85         $data = $this->replaceLinefeeds($data);
86
87         $this->data = $data;
88         $this->char = 0;
89         $this->EOF = strlen($data);
90     }
91
92     /**
93      * Replace linefeed characters according to the spec.
94      */
95     protected function replaceLinefeeds($data)
96     {
97         /*
98          * U+000D CARRIAGE RETURN (CR) characters and U+000A LINE FEED (LF) characters are treated specially. Any CR characters that are followed by LF characters must be removed, and any CR characters not followed by LF characters must be converted to LF characters. Thus, newlines in HTML DOMs are represented by LF characters, and there are never any CR characters in the input to the tokenization stage.
99          */
100         $crlfTable = array(
101             "\0" => "\xEF\xBF\xBD",
102             "\r\n" => "\n",
103             "\r" => "\n"
104         );
105
106         return strtr($data, $crlfTable);
107     }
108
109     /**
110      * Returns the current line that the tokenizer is at.
111      */
112     public function currentLine()
113     {
114         if (empty($this->EOF) || $this->char == 0) {
115             return 1;
116         }
117         // Add one to $this->char because we want the number for the next
118         // byte to be processed.
119         return substr_count($this->data, "\n", 0, min($this->char, $this->EOF)) + 1;
120     }
121
122     /**
123      *
124      * @deprecated
125      *
126      */
127     public function getCurrentLine()
128     {
129         return currentLine();
130     }
131
132     /**
133      * Returns the current column of the current line that the tokenizer is at.
134      *
135      * Newlines are column 0. The first char after a newline is column 1.
136      *
137      * @return int The column number.
138      */
139     public function columnOffset()
140     {
141         // Short circuit for the first char.
142         if ($this->char == 0) {
143             return 0;
144         }
145         // strrpos is weird, and the offset needs to be negative for what we
146         // want (i.e., the last \n before $this->char). This needs to not have
147         // one (to make it point to the next character, the one we want the
148         // position of) added to it because strrpos's behaviour includes the
149         // final offset byte.
150         $backwardFrom = $this->char - 1 - strlen($this->data);
151         $lastLine = strrpos($this->data, "\n", $backwardFrom);
152
153         // However, for here we want the length up until the next byte to be
154         // processed, so add one to the current byte ($this->char).
155         if ($lastLine !== false) {
156             $findLengthOf = substr($this->data, $lastLine + 1, $this->char - 1 - $lastLine);
157         } else {
158             // After a newline.
159             $findLengthOf = substr($this->data, 0, $this->char);
160         }
161
162         return UTF8Utils::countChars($findLengthOf);
163     }
164
165     /**
166      *
167      * @deprecated
168      *
169      */
170     public function getColumnOffset()
171     {
172         return $this->columnOffset();
173     }
174
175     /**
176      * Get the current character.
177      *
178      * @return string The current character.
179      */
180     public function current()
181     {
182         return $this->data[$this->char];
183     }
184
185     /**
186      * Advance the pointer.
187      * This is part of the Iterator interface.
188      */
189     public function next()
190     {
191         $this->char ++;
192     }
193
194     /**
195      * Rewind to the start of the string.
196      */
197     public function rewind()
198     {
199         $this->char = 0;
200     }
201
202     /**
203      * Is the current pointer location valid.
204      *
205      * @return bool Is the current pointer location valid.
206      */
207     public function valid()
208     {
209         if ($this->char < $this->EOF) {
210             return true;
211         }
212
213         return false;
214     }
215
216     /**
217      * Get all characters until EOF.
218      *
219      * This reads to the end of the file, and sets the read marker at the
220      * end of the file.
221      *
222      * @note This performs bounds checking
223      *
224      * @return string Returns the remaining text. If called when the InputStream is
225      *         already exhausted, it returns an empty string.
226      */
227     public function remainingChars()
228     {
229         if ($this->char < $this->EOF) {
230             $data = substr($this->data, $this->char);
231             $this->char = $this->EOF;
232
233             return $data;
234         }
235
236         return ''; // false;
237     }
238
239     /**
240      * Read to a particular match (or until $max bytes are consumed).
241      *
242      * This operates on byte sequences, not characters.
243      *
244      * Matches as far as possible until we reach a certain set of bytes
245      * and returns the matched substring.
246      *
247      * @param string $bytes
248      *            Bytes to match.
249      * @param int $max
250      *            Maximum number of bytes to scan.
251      * @return mixed Index or false if no match is found. You should use strong
252      *         equality when checking the result, since index could be 0.
253      */
254     public function charsUntil($bytes, $max = null)
255     {
256         if ($this->char >= $this->EOF) {
257             return false;
258         }
259
260         if ($max === 0 || $max) {
261             $len = strcspn($this->data, $bytes, $this->char, $max);
262         } else {
263             $len = strcspn($this->data, $bytes, $this->char);
264         }
265
266         $string = (string) substr($this->data, $this->char, $len);
267         $this->char += $len;
268
269         return $string;
270     }
271
272     /**
273      * Returns the string so long as $bytes matches.
274      *
275      * Matches as far as possible with a certain set of bytes
276      * and returns the matched substring.
277      *
278      * @param string $bytes
279      *            A mask of bytes to match. If ANY byte in this mask matches the
280      *            current char, the pointer advances and the char is part of the
281      *            substring.
282      * @param int $max
283      *            The max number of chars to read.
284      */
285     public function charsWhile($bytes, $max = null)
286     {
287         if ($this->char >= $this->EOF) {
288             return false;
289         }
290
291         if ($max === 0 || $max) {
292             $len = strspn($this->data, $bytes, $this->char, $max);
293         } else {
294             $len = strspn($this->data, $bytes, $this->char);
295         }
296         $string = (string) substr($this->data, $this->char, $len);
297         $this->char += $len;
298
299         return $string;
300     }
301
302     /**
303      * Unconsume characters.
304      *
305      * @param int $howMany
306      *            The number of characters to unconsume.
307      */
308     public function unconsume($howMany = 1)
309     {
310         if (($this->char - $howMany) >= 0) {
311             $this->char = $this->char - $howMany;
312         }
313     }
314
315     /**
316      * Look ahead without moving cursor.
317      */
318     public function peek()
319     {
320         if (($this->char + 1) <= $this->EOF) {
321             return $this->data[$this->char + 1];
322         }
323
324         return false;
325     }
326
327     public function key()
328     {
329         return $this->char;
330     }
331 }