Chris@0
|
1 <?php
|
Chris@0
|
2
|
Chris@0
|
3 /*
|
Chris@0
|
4 * This file is part of the Symfony package.
|
Chris@0
|
5 *
|
Chris@0
|
6 * (c) Fabien Potencier <fabien@symfony.com>
|
Chris@0
|
7 *
|
Chris@0
|
8 * For the full copyright and license information, please view the LICENSE
|
Chris@0
|
9 * file that was distributed with this source code.
|
Chris@0
|
10 */
|
Chris@0
|
11
|
Chris@0
|
12 namespace Symfony\Component\DomCrawler;
|
Chris@0
|
13
|
Chris@0
|
14 use Symfony\Component\CssSelector\CssSelectorConverter;
|
Chris@0
|
15
|
Chris@0
|
16 /**
|
Chris@0
|
17 * Crawler eases navigation of a list of \DOMNode objects.
|
Chris@0
|
18 *
|
Chris@0
|
19 * @author Fabien Potencier <fabien@symfony.com>
|
Chris@0
|
20 */
|
Chris@0
|
21 class Crawler implements \Countable, \IteratorAggregate
|
Chris@0
|
22 {
|
Chris@0
|
23 protected $uri;
|
Chris@0
|
24
|
Chris@0
|
25 /**
|
Chris@0
|
26 * @var string The default namespace prefix to be used with XPath and CSS expressions
|
Chris@0
|
27 */
|
Chris@0
|
28 private $defaultNamespacePrefix = 'default';
|
Chris@0
|
29
|
Chris@0
|
30 /**
|
Chris@0
|
31 * @var array A map of manually registered namespaces
|
Chris@0
|
32 */
|
Chris@17
|
33 private $namespaces = [];
|
Chris@0
|
34
|
Chris@0
|
35 /**
|
Chris@0
|
36 * @var string The base href value
|
Chris@0
|
37 */
|
Chris@0
|
38 private $baseHref;
|
Chris@0
|
39
|
Chris@0
|
40 /**
|
Chris@0
|
41 * @var \DOMDocument|null
|
Chris@0
|
42 */
|
Chris@0
|
43 private $document;
|
Chris@0
|
44
|
Chris@0
|
45 /**
|
Chris@0
|
46 * @var \DOMElement[]
|
Chris@0
|
47 */
|
Chris@17
|
48 private $nodes = [];
|
Chris@0
|
49
|
Chris@0
|
50 /**
|
Chris@0
|
51 * Whether the Crawler contains HTML or XML content (used when converting CSS to XPath).
|
Chris@0
|
52 *
|
Chris@0
|
53 * @var bool
|
Chris@0
|
54 */
|
Chris@0
|
55 private $isHtml = true;
|
Chris@0
|
56
|
Chris@0
|
57 /**
|
Chris@12
|
58 * @param mixed $node A Node to use as the base for the crawling
|
Chris@12
|
59 * @param string $uri The current URI
|
Chris@12
|
60 * @param string $baseHref The base href value
|
Chris@0
|
61 */
|
Chris@12
|
62 public function __construct($node = null, $uri = null, $baseHref = null)
|
Chris@0
|
63 {
|
Chris@12
|
64 $this->uri = $uri;
|
Chris@12
|
65 $this->baseHref = $baseHref ?: $uri;
|
Chris@0
|
66
|
Chris@0
|
67 $this->add($node);
|
Chris@0
|
68 }
|
Chris@0
|
69
|
Chris@0
|
70 /**
|
Chris@0
|
71 * Returns the current URI.
|
Chris@0
|
72 *
|
Chris@0
|
73 * @return string
|
Chris@0
|
74 */
|
Chris@0
|
75 public function getUri()
|
Chris@0
|
76 {
|
Chris@0
|
77 return $this->uri;
|
Chris@0
|
78 }
|
Chris@0
|
79
|
Chris@0
|
80 /**
|
Chris@0
|
81 * Returns base href.
|
Chris@0
|
82 *
|
Chris@0
|
83 * @return string
|
Chris@0
|
84 */
|
Chris@0
|
85 public function getBaseHref()
|
Chris@0
|
86 {
|
Chris@0
|
87 return $this->baseHref;
|
Chris@0
|
88 }
|
Chris@0
|
89
|
Chris@0
|
90 /**
|
Chris@0
|
91 * Removes all the nodes.
|
Chris@0
|
92 */
|
Chris@0
|
93 public function clear()
|
Chris@0
|
94 {
|
Chris@17
|
95 $this->nodes = [];
|
Chris@0
|
96 $this->document = null;
|
Chris@0
|
97 }
|
Chris@0
|
98
|
Chris@0
|
99 /**
|
Chris@0
|
100 * Adds a node to the current list of nodes.
|
Chris@0
|
101 *
|
Chris@0
|
102 * This method uses the appropriate specialized add*() method based
|
Chris@0
|
103 * on the type of the argument.
|
Chris@0
|
104 *
|
Chris@0
|
105 * @param \DOMNodeList|\DOMNode|array|string|null $node A node
|
Chris@0
|
106 *
|
Chris@12
|
107 * @throws \InvalidArgumentException when node is not the expected type
|
Chris@0
|
108 */
|
Chris@0
|
109 public function add($node)
|
Chris@0
|
110 {
|
Chris@0
|
111 if ($node instanceof \DOMNodeList) {
|
Chris@0
|
112 $this->addNodeList($node);
|
Chris@0
|
113 } elseif ($node instanceof \DOMNode) {
|
Chris@0
|
114 $this->addNode($node);
|
Chris@17
|
115 } elseif (\is_array($node)) {
|
Chris@0
|
116 $this->addNodes($node);
|
Chris@17
|
117 } elseif (\is_string($node)) {
|
Chris@0
|
118 $this->addContent($node);
|
Chris@0
|
119 } elseif (null !== $node) {
|
Chris@17
|
120 throw new \InvalidArgumentException(sprintf('Expecting a DOMNodeList or DOMNode instance, an array, a string, or null, but got "%s".', \is_object($node) ? \get_class($node) : \gettype($node)));
|
Chris@0
|
121 }
|
Chris@0
|
122 }
|
Chris@0
|
123
|
Chris@0
|
124 /**
|
Chris@0
|
125 * Adds HTML/XML content.
|
Chris@0
|
126 *
|
Chris@12
|
127 * If the charset is not set via the content type, it is assumed to be UTF-8,
|
Chris@12
|
128 * or ISO-8859-1 as a fallback, which is the default charset defined by the
|
Chris@0
|
129 * HTTP 1.1 specification.
|
Chris@0
|
130 *
|
Chris@0
|
131 * @param string $content A string to parse as HTML/XML
|
Chris@17
|
132 * @param string|null $type The content type of the string
|
Chris@0
|
133 */
|
Chris@0
|
134 public function addContent($content, $type = null)
|
Chris@0
|
135 {
|
Chris@0
|
136 if (empty($type)) {
|
Chris@0
|
137 $type = 0 === strpos($content, '<?xml') ? 'application/xml' : 'text/html';
|
Chris@0
|
138 }
|
Chris@0
|
139
|
Chris@0
|
140 // DOM only for HTML/XML content
|
Chris@0
|
141 if (!preg_match('/(x|ht)ml/i', $type, $xmlMatches)) {
|
Chris@0
|
142 return;
|
Chris@0
|
143 }
|
Chris@0
|
144
|
Chris@0
|
145 $charset = null;
|
Chris@0
|
146 if (false !== $pos = stripos($type, 'charset=')) {
|
Chris@0
|
147 $charset = substr($type, $pos + 8);
|
Chris@0
|
148 if (false !== $pos = strpos($charset, ';')) {
|
Chris@0
|
149 $charset = substr($charset, 0, $pos);
|
Chris@0
|
150 }
|
Chris@0
|
151 }
|
Chris@0
|
152
|
Chris@0
|
153 // http://www.w3.org/TR/encoding/#encodings
|
Chris@0
|
154 // http://www.w3.org/TR/REC-xml/#NT-EncName
|
Chris@0
|
155 if (null === $charset &&
|
Chris@0
|
156 preg_match('/\<meta[^\>]+charset *= *["\']?([a-zA-Z\-0-9_:.]+)/i', $content, $matches)) {
|
Chris@0
|
157 $charset = $matches[1];
|
Chris@0
|
158 }
|
Chris@0
|
159
|
Chris@0
|
160 if (null === $charset) {
|
Chris@12
|
161 $charset = preg_match('//u', $content) ? 'UTF-8' : 'ISO-8859-1';
|
Chris@0
|
162 }
|
Chris@0
|
163
|
Chris@0
|
164 if ('x' === $xmlMatches[1]) {
|
Chris@0
|
165 $this->addXmlContent($content, $charset);
|
Chris@0
|
166 } else {
|
Chris@0
|
167 $this->addHtmlContent($content, $charset);
|
Chris@0
|
168 }
|
Chris@0
|
169 }
|
Chris@0
|
170
|
Chris@0
|
171 /**
|
Chris@0
|
172 * Adds an HTML content to the list of nodes.
|
Chris@0
|
173 *
|
Chris@0
|
174 * The libxml errors are disabled when the content is parsed.
|
Chris@0
|
175 *
|
Chris@0
|
176 * If you want to get parsing errors, be sure to enable
|
Chris@0
|
177 * internal errors via libxml_use_internal_errors(true)
|
Chris@0
|
178 * and then, get the errors via libxml_get_errors(). Be
|
Chris@0
|
179 * sure to clear errors with libxml_clear_errors() afterward.
|
Chris@0
|
180 *
|
Chris@0
|
181 * @param string $content The HTML content
|
Chris@0
|
182 * @param string $charset The charset
|
Chris@0
|
183 */
|
Chris@0
|
184 public function addHtmlContent($content, $charset = 'UTF-8')
|
Chris@0
|
185 {
|
Chris@0
|
186 $internalErrors = libxml_use_internal_errors(true);
|
Chris@0
|
187 $disableEntities = libxml_disable_entity_loader(true);
|
Chris@0
|
188
|
Chris@0
|
189 $dom = new \DOMDocument('1.0', $charset);
|
Chris@0
|
190 $dom->validateOnParse = true;
|
Chris@0
|
191
|
Chris@0
|
192 set_error_handler(function () { throw new \Exception(); });
|
Chris@0
|
193
|
Chris@0
|
194 try {
|
Chris@0
|
195 // Convert charset to HTML-entities to work around bugs in DOMDocument::loadHTML()
|
Chris@0
|
196 $content = mb_convert_encoding($content, 'HTML-ENTITIES', $charset);
|
Chris@0
|
197 } catch (\Exception $e) {
|
Chris@0
|
198 }
|
Chris@0
|
199
|
Chris@0
|
200 restore_error_handler();
|
Chris@0
|
201
|
Chris@0
|
202 if ('' !== trim($content)) {
|
Chris@0
|
203 @$dom->loadHTML($content);
|
Chris@0
|
204 }
|
Chris@0
|
205
|
Chris@0
|
206 libxml_use_internal_errors($internalErrors);
|
Chris@0
|
207 libxml_disable_entity_loader($disableEntities);
|
Chris@0
|
208
|
Chris@0
|
209 $this->addDocument($dom);
|
Chris@0
|
210
|
Chris@17
|
211 $base = $this->filterRelativeXPath('descendant-or-self::base')->extract(['href']);
|
Chris@0
|
212
|
Chris@0
|
213 $baseHref = current($base);
|
Chris@17
|
214 if (\count($base) && !empty($baseHref)) {
|
Chris@0
|
215 if ($this->baseHref) {
|
Chris@0
|
216 $linkNode = $dom->createElement('a');
|
Chris@0
|
217 $linkNode->setAttribute('href', $baseHref);
|
Chris@0
|
218 $link = new Link($linkNode, $this->baseHref);
|
Chris@0
|
219 $this->baseHref = $link->getUri();
|
Chris@0
|
220 } else {
|
Chris@0
|
221 $this->baseHref = $baseHref;
|
Chris@0
|
222 }
|
Chris@0
|
223 }
|
Chris@0
|
224 }
|
Chris@0
|
225
|
Chris@0
|
226 /**
|
Chris@0
|
227 * Adds an XML content to the list of nodes.
|
Chris@0
|
228 *
|
Chris@0
|
229 * The libxml errors are disabled when the content is parsed.
|
Chris@0
|
230 *
|
Chris@0
|
231 * If you want to get parsing errors, be sure to enable
|
Chris@0
|
232 * internal errors via libxml_use_internal_errors(true)
|
Chris@0
|
233 * and then, get the errors via libxml_get_errors(). Be
|
Chris@0
|
234 * sure to clear errors with libxml_clear_errors() afterward.
|
Chris@0
|
235 *
|
Chris@0
|
236 * @param string $content The XML content
|
Chris@0
|
237 * @param string $charset The charset
|
Chris@0
|
238 * @param int $options Bitwise OR of the libxml option constants
|
Chris@0
|
239 * LIBXML_PARSEHUGE is dangerous, see
|
Chris@0
|
240 * http://symfony.com/blog/security-release-symfony-2-0-17-released
|
Chris@0
|
241 */
|
Chris@0
|
242 public function addXmlContent($content, $charset = 'UTF-8', $options = LIBXML_NONET)
|
Chris@0
|
243 {
|
Chris@0
|
244 // remove the default namespace if it's the only namespace to make XPath expressions simpler
|
Chris@0
|
245 if (!preg_match('/xmlns:/', $content)) {
|
Chris@0
|
246 $content = str_replace('xmlns', 'ns', $content);
|
Chris@0
|
247 }
|
Chris@0
|
248
|
Chris@0
|
249 $internalErrors = libxml_use_internal_errors(true);
|
Chris@0
|
250 $disableEntities = libxml_disable_entity_loader(true);
|
Chris@0
|
251
|
Chris@0
|
252 $dom = new \DOMDocument('1.0', $charset);
|
Chris@0
|
253 $dom->validateOnParse = true;
|
Chris@0
|
254
|
Chris@0
|
255 if ('' !== trim($content)) {
|
Chris@0
|
256 @$dom->loadXML($content, $options);
|
Chris@0
|
257 }
|
Chris@0
|
258
|
Chris@0
|
259 libxml_use_internal_errors($internalErrors);
|
Chris@0
|
260 libxml_disable_entity_loader($disableEntities);
|
Chris@0
|
261
|
Chris@0
|
262 $this->addDocument($dom);
|
Chris@0
|
263
|
Chris@0
|
264 $this->isHtml = false;
|
Chris@0
|
265 }
|
Chris@0
|
266
|
Chris@0
|
267 /**
|
Chris@0
|
268 * Adds a \DOMDocument to the list of nodes.
|
Chris@0
|
269 *
|
Chris@0
|
270 * @param \DOMDocument $dom A \DOMDocument instance
|
Chris@0
|
271 */
|
Chris@0
|
272 public function addDocument(\DOMDocument $dom)
|
Chris@0
|
273 {
|
Chris@0
|
274 if ($dom->documentElement) {
|
Chris@0
|
275 $this->addNode($dom->documentElement);
|
Chris@0
|
276 }
|
Chris@0
|
277 }
|
Chris@0
|
278
|
Chris@0
|
279 /**
|
Chris@0
|
280 * Adds a \DOMNodeList to the list of nodes.
|
Chris@0
|
281 *
|
Chris@0
|
282 * @param \DOMNodeList $nodes A \DOMNodeList instance
|
Chris@0
|
283 */
|
Chris@0
|
284 public function addNodeList(\DOMNodeList $nodes)
|
Chris@0
|
285 {
|
Chris@0
|
286 foreach ($nodes as $node) {
|
Chris@0
|
287 if ($node instanceof \DOMNode) {
|
Chris@0
|
288 $this->addNode($node);
|
Chris@0
|
289 }
|
Chris@0
|
290 }
|
Chris@0
|
291 }
|
Chris@0
|
292
|
Chris@0
|
293 /**
|
Chris@0
|
294 * Adds an array of \DOMNode instances to the list of nodes.
|
Chris@0
|
295 *
|
Chris@0
|
296 * @param \DOMNode[] $nodes An array of \DOMNode instances
|
Chris@0
|
297 */
|
Chris@0
|
298 public function addNodes(array $nodes)
|
Chris@0
|
299 {
|
Chris@0
|
300 foreach ($nodes as $node) {
|
Chris@0
|
301 $this->add($node);
|
Chris@0
|
302 }
|
Chris@0
|
303 }
|
Chris@0
|
304
|
Chris@0
|
305 /**
|
Chris@0
|
306 * Adds a \DOMNode instance to the list of nodes.
|
Chris@0
|
307 *
|
Chris@0
|
308 * @param \DOMNode $node A \DOMNode instance
|
Chris@0
|
309 */
|
Chris@0
|
310 public function addNode(\DOMNode $node)
|
Chris@0
|
311 {
|
Chris@0
|
312 if ($node instanceof \DOMDocument) {
|
Chris@0
|
313 $node = $node->documentElement;
|
Chris@0
|
314 }
|
Chris@0
|
315
|
Chris@0
|
316 if (null !== $this->document && $this->document !== $node->ownerDocument) {
|
Chris@0
|
317 throw new \InvalidArgumentException('Attaching DOM nodes from multiple documents in the same crawler is forbidden.');
|
Chris@0
|
318 }
|
Chris@0
|
319
|
Chris@0
|
320 if (null === $this->document) {
|
Chris@0
|
321 $this->document = $node->ownerDocument;
|
Chris@0
|
322 }
|
Chris@0
|
323
|
Chris@0
|
324 // Don't add duplicate nodes in the Crawler
|
Chris@17
|
325 if (\in_array($node, $this->nodes, true)) {
|
Chris@0
|
326 return;
|
Chris@0
|
327 }
|
Chris@0
|
328
|
Chris@0
|
329 $this->nodes[] = $node;
|
Chris@0
|
330 }
|
Chris@0
|
331
|
Chris@0
|
332 /**
|
Chris@0
|
333 * Returns a node given its position in the node list.
|
Chris@0
|
334 *
|
Chris@0
|
335 * @param int $position The position
|
Chris@0
|
336 *
|
Chris@0
|
337 * @return self
|
Chris@0
|
338 */
|
Chris@0
|
339 public function eq($position)
|
Chris@0
|
340 {
|
Chris@0
|
341 if (isset($this->nodes[$position])) {
|
Chris@0
|
342 return $this->createSubCrawler($this->nodes[$position]);
|
Chris@0
|
343 }
|
Chris@0
|
344
|
Chris@0
|
345 return $this->createSubCrawler(null);
|
Chris@0
|
346 }
|
Chris@0
|
347
|
Chris@0
|
348 /**
|
Chris@0
|
349 * Calls an anonymous function on each node of the list.
|
Chris@0
|
350 *
|
Chris@0
|
351 * The anonymous function receives the position and the node wrapped
|
Chris@0
|
352 * in a Crawler instance as arguments.
|
Chris@0
|
353 *
|
Chris@0
|
354 * Example:
|
Chris@0
|
355 *
|
Chris@0
|
356 * $crawler->filter('h1')->each(function ($node, $i) {
|
Chris@0
|
357 * return $node->text();
|
Chris@0
|
358 * });
|
Chris@0
|
359 *
|
Chris@0
|
360 * @param \Closure $closure An anonymous function
|
Chris@0
|
361 *
|
Chris@0
|
362 * @return array An array of values returned by the anonymous function
|
Chris@0
|
363 */
|
Chris@0
|
364 public function each(\Closure $closure)
|
Chris@0
|
365 {
|
Chris@17
|
366 $data = [];
|
Chris@0
|
367 foreach ($this->nodes as $i => $node) {
|
Chris@0
|
368 $data[] = $closure($this->createSubCrawler($node), $i);
|
Chris@0
|
369 }
|
Chris@0
|
370
|
Chris@0
|
371 return $data;
|
Chris@0
|
372 }
|
Chris@0
|
373
|
Chris@0
|
374 /**
|
Chris@0
|
375 * Slices the list of nodes by $offset and $length.
|
Chris@0
|
376 *
|
Chris@0
|
377 * @param int $offset
|
Chris@0
|
378 * @param int $length
|
Chris@0
|
379 *
|
Chris@0
|
380 * @return self
|
Chris@0
|
381 */
|
Chris@0
|
382 public function slice($offset = 0, $length = null)
|
Chris@0
|
383 {
|
Chris@17
|
384 return $this->createSubCrawler(\array_slice($this->nodes, $offset, $length));
|
Chris@0
|
385 }
|
Chris@0
|
386
|
Chris@0
|
387 /**
|
Chris@0
|
388 * Reduces the list of nodes by calling an anonymous function.
|
Chris@0
|
389 *
|
Chris@0
|
390 * To remove a node from the list, the anonymous function must return false.
|
Chris@0
|
391 *
|
Chris@0
|
392 * @param \Closure $closure An anonymous function
|
Chris@0
|
393 *
|
Chris@0
|
394 * @return self
|
Chris@0
|
395 */
|
Chris@0
|
396 public function reduce(\Closure $closure)
|
Chris@0
|
397 {
|
Chris@17
|
398 $nodes = [];
|
Chris@0
|
399 foreach ($this->nodes as $i => $node) {
|
Chris@0
|
400 if (false !== $closure($this->createSubCrawler($node), $i)) {
|
Chris@0
|
401 $nodes[] = $node;
|
Chris@0
|
402 }
|
Chris@0
|
403 }
|
Chris@0
|
404
|
Chris@0
|
405 return $this->createSubCrawler($nodes);
|
Chris@0
|
406 }
|
Chris@0
|
407
|
Chris@0
|
408 /**
|
Chris@0
|
409 * Returns the first node of the current selection.
|
Chris@0
|
410 *
|
Chris@0
|
411 * @return self
|
Chris@0
|
412 */
|
Chris@0
|
413 public function first()
|
Chris@0
|
414 {
|
Chris@0
|
415 return $this->eq(0);
|
Chris@0
|
416 }
|
Chris@0
|
417
|
Chris@0
|
418 /**
|
Chris@0
|
419 * Returns the last node of the current selection.
|
Chris@0
|
420 *
|
Chris@0
|
421 * @return self
|
Chris@0
|
422 */
|
Chris@0
|
423 public function last()
|
Chris@0
|
424 {
|
Chris@17
|
425 return $this->eq(\count($this->nodes) - 1);
|
Chris@0
|
426 }
|
Chris@0
|
427
|
Chris@0
|
428 /**
|
Chris@0
|
429 * Returns the siblings nodes of the current selection.
|
Chris@0
|
430 *
|
Chris@0
|
431 * @return self
|
Chris@0
|
432 *
|
Chris@0
|
433 * @throws \InvalidArgumentException When current node is empty
|
Chris@0
|
434 */
|
Chris@0
|
435 public function siblings()
|
Chris@0
|
436 {
|
Chris@0
|
437 if (!$this->nodes) {
|
Chris@0
|
438 throw new \InvalidArgumentException('The current node list is empty.');
|
Chris@0
|
439 }
|
Chris@0
|
440
|
Chris@0
|
441 return $this->createSubCrawler($this->sibling($this->getNode(0)->parentNode->firstChild));
|
Chris@0
|
442 }
|
Chris@0
|
443
|
Chris@0
|
444 /**
|
Chris@0
|
445 * Returns the next siblings nodes of the current selection.
|
Chris@0
|
446 *
|
Chris@0
|
447 * @return self
|
Chris@0
|
448 *
|
Chris@0
|
449 * @throws \InvalidArgumentException When current node is empty
|
Chris@0
|
450 */
|
Chris@0
|
451 public function nextAll()
|
Chris@0
|
452 {
|
Chris@0
|
453 if (!$this->nodes) {
|
Chris@0
|
454 throw new \InvalidArgumentException('The current node list is empty.');
|
Chris@0
|
455 }
|
Chris@0
|
456
|
Chris@0
|
457 return $this->createSubCrawler($this->sibling($this->getNode(0)));
|
Chris@0
|
458 }
|
Chris@0
|
459
|
Chris@0
|
460 /**
|
Chris@0
|
461 * Returns the previous sibling nodes of the current selection.
|
Chris@0
|
462 *
|
Chris@0
|
463 * @return self
|
Chris@0
|
464 *
|
Chris@0
|
465 * @throws \InvalidArgumentException
|
Chris@0
|
466 */
|
Chris@0
|
467 public function previousAll()
|
Chris@0
|
468 {
|
Chris@0
|
469 if (!$this->nodes) {
|
Chris@0
|
470 throw new \InvalidArgumentException('The current node list is empty.');
|
Chris@0
|
471 }
|
Chris@0
|
472
|
Chris@0
|
473 return $this->createSubCrawler($this->sibling($this->getNode(0), 'previousSibling'));
|
Chris@0
|
474 }
|
Chris@0
|
475
|
Chris@0
|
476 /**
|
Chris@0
|
477 * Returns the parents nodes of the current selection.
|
Chris@0
|
478 *
|
Chris@0
|
479 * @return self
|
Chris@0
|
480 *
|
Chris@0
|
481 * @throws \InvalidArgumentException When current node is empty
|
Chris@0
|
482 */
|
Chris@0
|
483 public function parents()
|
Chris@0
|
484 {
|
Chris@0
|
485 if (!$this->nodes) {
|
Chris@0
|
486 throw new \InvalidArgumentException('The current node list is empty.');
|
Chris@0
|
487 }
|
Chris@0
|
488
|
Chris@0
|
489 $node = $this->getNode(0);
|
Chris@17
|
490 $nodes = [];
|
Chris@0
|
491
|
Chris@0
|
492 while ($node = $node->parentNode) {
|
Chris@0
|
493 if (XML_ELEMENT_NODE === $node->nodeType) {
|
Chris@0
|
494 $nodes[] = $node;
|
Chris@0
|
495 }
|
Chris@0
|
496 }
|
Chris@0
|
497
|
Chris@0
|
498 return $this->createSubCrawler($nodes);
|
Chris@0
|
499 }
|
Chris@0
|
500
|
Chris@0
|
501 /**
|
Chris@0
|
502 * Returns the children nodes of the current selection.
|
Chris@0
|
503 *
|
Chris@0
|
504 * @return self
|
Chris@0
|
505 *
|
Chris@0
|
506 * @throws \InvalidArgumentException When current node is empty
|
Chris@0
|
507 */
|
Chris@0
|
508 public function children()
|
Chris@0
|
509 {
|
Chris@0
|
510 if (!$this->nodes) {
|
Chris@0
|
511 throw new \InvalidArgumentException('The current node list is empty.');
|
Chris@0
|
512 }
|
Chris@0
|
513
|
Chris@0
|
514 $node = $this->getNode(0)->firstChild;
|
Chris@0
|
515
|
Chris@17
|
516 return $this->createSubCrawler($node ? $this->sibling($node) : []);
|
Chris@0
|
517 }
|
Chris@0
|
518
|
Chris@0
|
519 /**
|
Chris@0
|
520 * Returns the attribute value of the first node of the list.
|
Chris@0
|
521 *
|
Chris@0
|
522 * @param string $attribute The attribute name
|
Chris@0
|
523 *
|
Chris@0
|
524 * @return string|null The attribute value or null if the attribute does not exist
|
Chris@0
|
525 *
|
Chris@0
|
526 * @throws \InvalidArgumentException When current node is empty
|
Chris@0
|
527 */
|
Chris@0
|
528 public function attr($attribute)
|
Chris@0
|
529 {
|
Chris@0
|
530 if (!$this->nodes) {
|
Chris@0
|
531 throw new \InvalidArgumentException('The current node list is empty.');
|
Chris@0
|
532 }
|
Chris@0
|
533
|
Chris@0
|
534 $node = $this->getNode(0);
|
Chris@0
|
535
|
Chris@0
|
536 return $node->hasAttribute($attribute) ? $node->getAttribute($attribute) : null;
|
Chris@0
|
537 }
|
Chris@0
|
538
|
Chris@0
|
539 /**
|
Chris@0
|
540 * Returns the node name of the first node of the list.
|
Chris@0
|
541 *
|
Chris@0
|
542 * @return string The node name
|
Chris@0
|
543 *
|
Chris@0
|
544 * @throws \InvalidArgumentException When current node is empty
|
Chris@0
|
545 */
|
Chris@0
|
546 public function nodeName()
|
Chris@0
|
547 {
|
Chris@0
|
548 if (!$this->nodes) {
|
Chris@0
|
549 throw new \InvalidArgumentException('The current node list is empty.');
|
Chris@0
|
550 }
|
Chris@0
|
551
|
Chris@0
|
552 return $this->getNode(0)->nodeName;
|
Chris@0
|
553 }
|
Chris@0
|
554
|
Chris@0
|
555 /**
|
Chris@0
|
556 * Returns the node value of the first node of the list.
|
Chris@0
|
557 *
|
Chris@0
|
558 * @return string The node value
|
Chris@0
|
559 *
|
Chris@0
|
560 * @throws \InvalidArgumentException When current node is empty
|
Chris@0
|
561 */
|
Chris@0
|
562 public function text()
|
Chris@0
|
563 {
|
Chris@0
|
564 if (!$this->nodes) {
|
Chris@0
|
565 throw new \InvalidArgumentException('The current node list is empty.');
|
Chris@0
|
566 }
|
Chris@0
|
567
|
Chris@0
|
568 return $this->getNode(0)->nodeValue;
|
Chris@0
|
569 }
|
Chris@0
|
570
|
Chris@0
|
571 /**
|
Chris@0
|
572 * Returns the first node of the list as HTML.
|
Chris@0
|
573 *
|
Chris@0
|
574 * @return string The node html
|
Chris@0
|
575 *
|
Chris@0
|
576 * @throws \InvalidArgumentException When current node is empty
|
Chris@0
|
577 */
|
Chris@0
|
578 public function html()
|
Chris@0
|
579 {
|
Chris@0
|
580 if (!$this->nodes) {
|
Chris@0
|
581 throw new \InvalidArgumentException('The current node list is empty.');
|
Chris@0
|
582 }
|
Chris@0
|
583
|
Chris@0
|
584 $html = '';
|
Chris@0
|
585 foreach ($this->getNode(0)->childNodes as $child) {
|
Chris@0
|
586 $html .= $child->ownerDocument->saveHTML($child);
|
Chris@0
|
587 }
|
Chris@0
|
588
|
Chris@0
|
589 return $html;
|
Chris@0
|
590 }
|
Chris@0
|
591
|
Chris@0
|
592 /**
|
Chris@0
|
593 * Evaluates an XPath expression.
|
Chris@0
|
594 *
|
Chris@0
|
595 * Since an XPath expression might evaluate to either a simple type or a \DOMNodeList,
|
Chris@0
|
596 * this method will return either an array of simple types or a new Crawler instance.
|
Chris@0
|
597 *
|
Chris@0
|
598 * @param string $xpath An XPath expression
|
Chris@0
|
599 *
|
Chris@0
|
600 * @return array|Crawler An array of evaluation results or a new Crawler instance
|
Chris@0
|
601 */
|
Chris@0
|
602 public function evaluate($xpath)
|
Chris@0
|
603 {
|
Chris@0
|
604 if (null === $this->document) {
|
Chris@0
|
605 throw new \LogicException('Cannot evaluate the expression on an uninitialized crawler.');
|
Chris@0
|
606 }
|
Chris@0
|
607
|
Chris@17
|
608 $data = [];
|
Chris@0
|
609 $domxpath = $this->createDOMXPath($this->document, $this->findNamespacePrefixes($xpath));
|
Chris@0
|
610
|
Chris@0
|
611 foreach ($this->nodes as $node) {
|
Chris@0
|
612 $data[] = $domxpath->evaluate($xpath, $node);
|
Chris@0
|
613 }
|
Chris@0
|
614
|
Chris@0
|
615 if (isset($data[0]) && $data[0] instanceof \DOMNodeList) {
|
Chris@0
|
616 return $this->createSubCrawler($data);
|
Chris@0
|
617 }
|
Chris@0
|
618
|
Chris@0
|
619 return $data;
|
Chris@0
|
620 }
|
Chris@0
|
621
|
Chris@0
|
622 /**
|
Chris@0
|
623 * Extracts information from the list of nodes.
|
Chris@0
|
624 *
|
Chris@0
|
625 * You can extract attributes or/and the node value (_text).
|
Chris@0
|
626 *
|
Chris@0
|
627 * Example:
|
Chris@0
|
628 *
|
Chris@17
|
629 * $crawler->filter('h1 a')->extract(['_text', 'href']);
|
Chris@0
|
630 *
|
Chris@0
|
631 * @param array $attributes An array of attributes
|
Chris@0
|
632 *
|
Chris@0
|
633 * @return array An array of extracted values
|
Chris@0
|
634 */
|
Chris@0
|
635 public function extract($attributes)
|
Chris@0
|
636 {
|
Chris@0
|
637 $attributes = (array) $attributes;
|
Chris@17
|
638 $count = \count($attributes);
|
Chris@0
|
639
|
Chris@17
|
640 $data = [];
|
Chris@0
|
641 foreach ($this->nodes as $node) {
|
Chris@17
|
642 $elements = [];
|
Chris@0
|
643 foreach ($attributes as $attribute) {
|
Chris@0
|
644 if ('_text' === $attribute) {
|
Chris@0
|
645 $elements[] = $node->nodeValue;
|
Chris@0
|
646 } else {
|
Chris@0
|
647 $elements[] = $node->getAttribute($attribute);
|
Chris@0
|
648 }
|
Chris@0
|
649 }
|
Chris@0
|
650
|
Chris@13
|
651 $data[] = 1 === $count ? $elements[0] : $elements;
|
Chris@0
|
652 }
|
Chris@0
|
653
|
Chris@0
|
654 return $data;
|
Chris@0
|
655 }
|
Chris@0
|
656
|
Chris@0
|
657 /**
|
Chris@0
|
658 * Filters the list of nodes with an XPath expression.
|
Chris@0
|
659 *
|
Chris@0
|
660 * The XPath expression is evaluated in the context of the crawler, which
|
Chris@0
|
661 * is considered as a fake parent of the elements inside it.
|
Chris@0
|
662 * This means that a child selector "div" or "./div" will match only
|
Chris@0
|
663 * the div elements of the current crawler, not their children.
|
Chris@0
|
664 *
|
Chris@0
|
665 * @param string $xpath An XPath expression
|
Chris@0
|
666 *
|
Chris@0
|
667 * @return self
|
Chris@0
|
668 */
|
Chris@0
|
669 public function filterXPath($xpath)
|
Chris@0
|
670 {
|
Chris@0
|
671 $xpath = $this->relativize($xpath);
|
Chris@0
|
672
|
Chris@0
|
673 // If we dropped all expressions in the XPath while preparing it, there would be no match
|
Chris@0
|
674 if ('' === $xpath) {
|
Chris@0
|
675 return $this->createSubCrawler(null);
|
Chris@0
|
676 }
|
Chris@0
|
677
|
Chris@0
|
678 return $this->filterRelativeXPath($xpath);
|
Chris@0
|
679 }
|
Chris@0
|
680
|
Chris@0
|
681 /**
|
Chris@0
|
682 * Filters the list of nodes with a CSS selector.
|
Chris@0
|
683 *
|
Chris@0
|
684 * This method only works if you have installed the CssSelector Symfony Component.
|
Chris@0
|
685 *
|
Chris@0
|
686 * @param string $selector A CSS selector
|
Chris@0
|
687 *
|
Chris@0
|
688 * @return self
|
Chris@0
|
689 *
|
Chris@0
|
690 * @throws \RuntimeException if the CssSelector Component is not available
|
Chris@0
|
691 */
|
Chris@0
|
692 public function filter($selector)
|
Chris@0
|
693 {
|
Chris@12
|
694 if (!class_exists(CssSelectorConverter::class)) {
|
Chris@12
|
695 throw new \RuntimeException('To filter with a CSS selector, install the CssSelector component ("composer require symfony/css-selector"). Or use filterXpath instead.');
|
Chris@0
|
696 }
|
Chris@0
|
697
|
Chris@0
|
698 $converter = new CssSelectorConverter($this->isHtml);
|
Chris@0
|
699
|
Chris@0
|
700 // The CssSelector already prefixes the selector with descendant-or-self::
|
Chris@0
|
701 return $this->filterRelativeXPath($converter->toXPath($selector));
|
Chris@0
|
702 }
|
Chris@0
|
703
|
Chris@0
|
704 /**
|
Chris@0
|
705 * Selects links by name or alt value for clickable images.
|
Chris@0
|
706 *
|
Chris@0
|
707 * @param string $value The link text
|
Chris@0
|
708 *
|
Chris@0
|
709 * @return self
|
Chris@0
|
710 */
|
Chris@0
|
711 public function selectLink($value)
|
Chris@0
|
712 {
|
Chris@0
|
713 $xpath = sprintf('descendant-or-self::a[contains(concat(\' \', normalize-space(string(.)), \' \'), %s) ', static::xpathLiteral(' '.$value.' ')).
|
Chris@0
|
714 sprintf('or ./img[contains(concat(\' \', normalize-space(string(@alt)), \' \'), %s)]]', static::xpathLiteral(' '.$value.' '));
|
Chris@0
|
715
|
Chris@0
|
716 return $this->filterRelativeXPath($xpath);
|
Chris@0
|
717 }
|
Chris@0
|
718
|
Chris@0
|
719 /**
|
Chris@0
|
720 * Selects images by alt value.
|
Chris@0
|
721 *
|
Chris@0
|
722 * @param string $value The image alt
|
Chris@0
|
723 *
|
Chris@0
|
724 * @return self A new instance of Crawler with the filtered list of nodes
|
Chris@0
|
725 */
|
Chris@0
|
726 public function selectImage($value)
|
Chris@0
|
727 {
|
Chris@0
|
728 $xpath = sprintf('descendant-or-self::img[contains(normalize-space(string(@alt)), %s)]', static::xpathLiteral($value));
|
Chris@0
|
729
|
Chris@0
|
730 return $this->filterRelativeXPath($xpath);
|
Chris@0
|
731 }
|
Chris@0
|
732
|
Chris@0
|
733 /**
|
Chris@0
|
734 * Selects a button by name or alt value for images.
|
Chris@0
|
735 *
|
Chris@0
|
736 * @param string $value The button text
|
Chris@0
|
737 *
|
Chris@0
|
738 * @return self
|
Chris@0
|
739 */
|
Chris@0
|
740 public function selectButton($value)
|
Chris@0
|
741 {
|
Chris@0
|
742 $translate = 'translate(@type, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz")';
|
Chris@12
|
743 $xpath = sprintf('descendant-or-self::input[((contains(%s, "submit") or contains(%1$s, "button")) and contains(concat(\' \', normalize-space(string(@value)), \' \'), %s)) ', $translate, static::xpathLiteral(' '.$value.' ')).
|
Chris@0
|
744 sprintf('or (contains(%s, "image") and contains(concat(\' \', normalize-space(string(@alt)), \' \'), %s)) or @id=%s or @name=%s] ', $translate, static::xpathLiteral(' '.$value.' '), static::xpathLiteral($value), static::xpathLiteral($value)).
|
Chris@0
|
745 sprintf('| descendant-or-self::button[contains(concat(\' \', normalize-space(string(.)), \' \'), %s) or @id=%s or @name=%s]', static::xpathLiteral(' '.$value.' '), static::xpathLiteral($value), static::xpathLiteral($value));
|
Chris@0
|
746
|
Chris@0
|
747 return $this->filterRelativeXPath($xpath);
|
Chris@0
|
748 }
|
Chris@0
|
749
|
Chris@0
|
750 /**
|
Chris@0
|
751 * Returns a Link object for the first node in the list.
|
Chris@0
|
752 *
|
Chris@0
|
753 * @param string $method The method for the link (get by default)
|
Chris@0
|
754 *
|
Chris@0
|
755 * @return Link A Link instance
|
Chris@0
|
756 *
|
Chris@0
|
757 * @throws \InvalidArgumentException If the current node list is empty or the selected node is not instance of DOMElement
|
Chris@0
|
758 */
|
Chris@0
|
759 public function link($method = 'get')
|
Chris@0
|
760 {
|
Chris@0
|
761 if (!$this->nodes) {
|
Chris@0
|
762 throw new \InvalidArgumentException('The current node list is empty.');
|
Chris@0
|
763 }
|
Chris@0
|
764
|
Chris@0
|
765 $node = $this->getNode(0);
|
Chris@0
|
766
|
Chris@0
|
767 if (!$node instanceof \DOMElement) {
|
Chris@17
|
768 throw new \InvalidArgumentException(sprintf('The selected node should be instance of DOMElement, got "%s".', \get_class($node)));
|
Chris@0
|
769 }
|
Chris@0
|
770
|
Chris@0
|
771 return new Link($node, $this->baseHref, $method);
|
Chris@0
|
772 }
|
Chris@0
|
773
|
Chris@0
|
774 /**
|
Chris@0
|
775 * Returns an array of Link objects for the nodes in the list.
|
Chris@0
|
776 *
|
Chris@0
|
777 * @return Link[] An array of Link instances
|
Chris@0
|
778 *
|
Chris@0
|
779 * @throws \InvalidArgumentException If the current node list contains non-DOMElement instances
|
Chris@0
|
780 */
|
Chris@0
|
781 public function links()
|
Chris@0
|
782 {
|
Chris@17
|
783 $links = [];
|
Chris@0
|
784 foreach ($this->nodes as $node) {
|
Chris@0
|
785 if (!$node instanceof \DOMElement) {
|
Chris@17
|
786 throw new \InvalidArgumentException(sprintf('The current node list should contain only DOMElement instances, "%s" found.', \get_class($node)));
|
Chris@0
|
787 }
|
Chris@0
|
788
|
Chris@0
|
789 $links[] = new Link($node, $this->baseHref, 'get');
|
Chris@0
|
790 }
|
Chris@0
|
791
|
Chris@0
|
792 return $links;
|
Chris@0
|
793 }
|
Chris@0
|
794
|
Chris@0
|
795 /**
|
Chris@0
|
796 * Returns an Image object for the first node in the list.
|
Chris@0
|
797 *
|
Chris@0
|
798 * @return Image An Image instance
|
Chris@0
|
799 *
|
Chris@0
|
800 * @throws \InvalidArgumentException If the current node list is empty
|
Chris@0
|
801 */
|
Chris@0
|
802 public function image()
|
Chris@0
|
803 {
|
Chris@17
|
804 if (!\count($this)) {
|
Chris@0
|
805 throw new \InvalidArgumentException('The current node list is empty.');
|
Chris@0
|
806 }
|
Chris@0
|
807
|
Chris@0
|
808 $node = $this->getNode(0);
|
Chris@0
|
809
|
Chris@0
|
810 if (!$node instanceof \DOMElement) {
|
Chris@17
|
811 throw new \InvalidArgumentException(sprintf('The selected node should be instance of DOMElement, got "%s".', \get_class($node)));
|
Chris@0
|
812 }
|
Chris@0
|
813
|
Chris@0
|
814 return new Image($node, $this->baseHref);
|
Chris@0
|
815 }
|
Chris@0
|
816
|
Chris@0
|
817 /**
|
Chris@0
|
818 * Returns an array of Image objects for the nodes in the list.
|
Chris@0
|
819 *
|
Chris@0
|
820 * @return Image[] An array of Image instances
|
Chris@0
|
821 */
|
Chris@0
|
822 public function images()
|
Chris@0
|
823 {
|
Chris@17
|
824 $images = [];
|
Chris@0
|
825 foreach ($this as $node) {
|
Chris@0
|
826 if (!$node instanceof \DOMElement) {
|
Chris@17
|
827 throw new \InvalidArgumentException(sprintf('The current node list should contain only DOMElement instances, "%s" found.', \get_class($node)));
|
Chris@0
|
828 }
|
Chris@0
|
829
|
Chris@0
|
830 $images[] = new Image($node, $this->baseHref);
|
Chris@0
|
831 }
|
Chris@0
|
832
|
Chris@0
|
833 return $images;
|
Chris@0
|
834 }
|
Chris@0
|
835
|
Chris@0
|
836 /**
|
Chris@0
|
837 * Returns a Form object for the first node in the list.
|
Chris@0
|
838 *
|
Chris@0
|
839 * @param array $values An array of values for the form fields
|
Chris@0
|
840 * @param string $method The method for the form
|
Chris@0
|
841 *
|
Chris@0
|
842 * @return Form A Form instance
|
Chris@0
|
843 *
|
Chris@0
|
844 * @throws \InvalidArgumentException If the current node list is empty or the selected node is not instance of DOMElement
|
Chris@0
|
845 */
|
Chris@0
|
846 public function form(array $values = null, $method = null)
|
Chris@0
|
847 {
|
Chris@0
|
848 if (!$this->nodes) {
|
Chris@0
|
849 throw new \InvalidArgumentException('The current node list is empty.');
|
Chris@0
|
850 }
|
Chris@0
|
851
|
Chris@0
|
852 $node = $this->getNode(0);
|
Chris@0
|
853
|
Chris@0
|
854 if (!$node instanceof \DOMElement) {
|
Chris@17
|
855 throw new \InvalidArgumentException(sprintf('The selected node should be instance of DOMElement, got "%s".', \get_class($node)));
|
Chris@0
|
856 }
|
Chris@0
|
857
|
Chris@0
|
858 $form = new Form($node, $this->uri, $method, $this->baseHref);
|
Chris@0
|
859
|
Chris@0
|
860 if (null !== $values) {
|
Chris@0
|
861 $form->setValues($values);
|
Chris@0
|
862 }
|
Chris@0
|
863
|
Chris@0
|
864 return $form;
|
Chris@0
|
865 }
|
Chris@0
|
866
|
Chris@0
|
867 /**
|
Chris@0
|
868 * Overloads a default namespace prefix to be used with XPath and CSS expressions.
|
Chris@0
|
869 *
|
Chris@0
|
870 * @param string $prefix
|
Chris@0
|
871 */
|
Chris@0
|
872 public function setDefaultNamespacePrefix($prefix)
|
Chris@0
|
873 {
|
Chris@0
|
874 $this->defaultNamespacePrefix = $prefix;
|
Chris@0
|
875 }
|
Chris@0
|
876
|
Chris@0
|
877 /**
|
Chris@0
|
878 * @param string $prefix
|
Chris@0
|
879 * @param string $namespace
|
Chris@0
|
880 */
|
Chris@0
|
881 public function registerNamespace($prefix, $namespace)
|
Chris@0
|
882 {
|
Chris@0
|
883 $this->namespaces[$prefix] = $namespace;
|
Chris@0
|
884 }
|
Chris@0
|
885
|
Chris@0
|
886 /**
|
Chris@0
|
887 * Converts string for XPath expressions.
|
Chris@0
|
888 *
|
Chris@0
|
889 * Escaped characters are: quotes (") and apostrophe (').
|
Chris@0
|
890 *
|
Chris@0
|
891 * Examples:
|
Chris@17
|
892 *
|
Chris@0
|
893 * echo Crawler::xpathLiteral('foo " bar');
|
Chris@0
|
894 * //prints 'foo " bar'
|
Chris@0
|
895 *
|
Chris@0
|
896 * echo Crawler::xpathLiteral("foo ' bar");
|
Chris@0
|
897 * //prints "foo ' bar"
|
Chris@0
|
898 *
|
Chris@0
|
899 * echo Crawler::xpathLiteral('a\'b"c');
|
Chris@0
|
900 * //prints concat('a', "'", 'b"c')
|
Chris@17
|
901 *
|
Chris@0
|
902 *
|
Chris@0
|
903 * @param string $s String to be escaped
|
Chris@0
|
904 *
|
Chris@0
|
905 * @return string Converted string
|
Chris@0
|
906 */
|
Chris@0
|
907 public static function xpathLiteral($s)
|
Chris@0
|
908 {
|
Chris@0
|
909 if (false === strpos($s, "'")) {
|
Chris@0
|
910 return sprintf("'%s'", $s);
|
Chris@0
|
911 }
|
Chris@0
|
912
|
Chris@0
|
913 if (false === strpos($s, '"')) {
|
Chris@0
|
914 return sprintf('"%s"', $s);
|
Chris@0
|
915 }
|
Chris@0
|
916
|
Chris@0
|
917 $string = $s;
|
Chris@17
|
918 $parts = [];
|
Chris@0
|
919 while (true) {
|
Chris@0
|
920 if (false !== $pos = strpos($string, "'")) {
|
Chris@0
|
921 $parts[] = sprintf("'%s'", substr($string, 0, $pos));
|
Chris@0
|
922 $parts[] = "\"'\"";
|
Chris@0
|
923 $string = substr($string, $pos + 1);
|
Chris@0
|
924 } else {
|
Chris@0
|
925 $parts[] = "'$string'";
|
Chris@0
|
926 break;
|
Chris@0
|
927 }
|
Chris@0
|
928 }
|
Chris@0
|
929
|
Chris@0
|
930 return sprintf('concat(%s)', implode(', ', $parts));
|
Chris@0
|
931 }
|
Chris@0
|
932
|
Chris@0
|
933 /**
|
Chris@0
|
934 * Filters the list of nodes with an XPath expression.
|
Chris@0
|
935 *
|
Chris@0
|
936 * The XPath expression should already be processed to apply it in the context of each node.
|
Chris@0
|
937 *
|
Chris@0
|
938 * @param string $xpath
|
Chris@0
|
939 *
|
Chris@0
|
940 * @return self
|
Chris@0
|
941 */
|
Chris@0
|
942 private function filterRelativeXPath($xpath)
|
Chris@0
|
943 {
|
Chris@0
|
944 $prefixes = $this->findNamespacePrefixes($xpath);
|
Chris@0
|
945
|
Chris@0
|
946 $crawler = $this->createSubCrawler(null);
|
Chris@0
|
947
|
Chris@0
|
948 foreach ($this->nodes as $node) {
|
Chris@0
|
949 $domxpath = $this->createDOMXPath($node->ownerDocument, $prefixes);
|
Chris@0
|
950 $crawler->add($domxpath->query($xpath, $node));
|
Chris@0
|
951 }
|
Chris@0
|
952
|
Chris@0
|
953 return $crawler;
|
Chris@0
|
954 }
|
Chris@0
|
955
|
Chris@0
|
956 /**
|
Chris@0
|
957 * Make the XPath relative to the current context.
|
Chris@0
|
958 *
|
Chris@0
|
959 * The returned XPath will match elements matching the XPath inside the current crawler
|
Chris@0
|
960 * when running in the context of a node of the crawler.
|
Chris@0
|
961 *
|
Chris@0
|
962 * @param string $xpath
|
Chris@0
|
963 *
|
Chris@0
|
964 * @return string
|
Chris@0
|
965 */
|
Chris@0
|
966 private function relativize($xpath)
|
Chris@0
|
967 {
|
Chris@17
|
968 $expressions = [];
|
Chris@0
|
969
|
Chris@0
|
970 // An expression which will never match to replace expressions which cannot match in the crawler
|
Chris@18
|
971 // We cannot drop
|
Chris@0
|
972 $nonMatchingExpression = 'a[name() = "b"]';
|
Chris@0
|
973
|
Chris@17
|
974 $xpathLen = \strlen($xpath);
|
Chris@0
|
975 $openedBrackets = 0;
|
Chris@0
|
976 $startPosition = strspn($xpath, " \t\n\r\0\x0B");
|
Chris@0
|
977
|
Chris@0
|
978 for ($i = $startPosition; $i <= $xpathLen; ++$i) {
|
Chris@0
|
979 $i += strcspn($xpath, '"\'[]|', $i);
|
Chris@0
|
980
|
Chris@0
|
981 if ($i < $xpathLen) {
|
Chris@0
|
982 switch ($xpath[$i]) {
|
Chris@0
|
983 case '"':
|
Chris@0
|
984 case "'":
|
Chris@0
|
985 if (false === $i = strpos($xpath, $xpath[$i], $i + 1)) {
|
Chris@0
|
986 return $xpath; // The XPath expression is invalid
|
Chris@0
|
987 }
|
Chris@0
|
988 continue 2;
|
Chris@0
|
989 case '[':
|
Chris@0
|
990 ++$openedBrackets;
|
Chris@0
|
991 continue 2;
|
Chris@0
|
992 case ']':
|
Chris@0
|
993 --$openedBrackets;
|
Chris@0
|
994 continue 2;
|
Chris@0
|
995 }
|
Chris@0
|
996 }
|
Chris@0
|
997 if ($openedBrackets) {
|
Chris@0
|
998 continue;
|
Chris@0
|
999 }
|
Chris@0
|
1000
|
Chris@0
|
1001 if ($startPosition < $xpathLen && '(' === $xpath[$startPosition]) {
|
Chris@0
|
1002 // If the union is inside some braces, we need to preserve the opening braces and apply
|
Chris@0
|
1003 // the change only inside it.
|
Chris@0
|
1004 $j = 1 + strspn($xpath, "( \t\n\r\0\x0B", $startPosition + 1);
|
Chris@0
|
1005 $parenthesis = substr($xpath, $startPosition, $j);
|
Chris@0
|
1006 $startPosition += $j;
|
Chris@0
|
1007 } else {
|
Chris@0
|
1008 $parenthesis = '';
|
Chris@0
|
1009 }
|
Chris@0
|
1010 $expression = rtrim(substr($xpath, $startPosition, $i - $startPosition));
|
Chris@0
|
1011
|
Chris@0
|
1012 if (0 === strpos($expression, 'self::*/')) {
|
Chris@0
|
1013 $expression = './'.substr($expression, 8);
|
Chris@0
|
1014 }
|
Chris@0
|
1015
|
Chris@0
|
1016 // add prefix before absolute element selector
|
Chris@0
|
1017 if ('' === $expression) {
|
Chris@0
|
1018 $expression = $nonMatchingExpression;
|
Chris@0
|
1019 } elseif (0 === strpos($expression, '//')) {
|
Chris@0
|
1020 $expression = 'descendant-or-self::'.substr($expression, 2);
|
Chris@0
|
1021 } elseif (0 === strpos($expression, './/')) {
|
Chris@0
|
1022 $expression = 'descendant-or-self::'.substr($expression, 3);
|
Chris@0
|
1023 } elseif (0 === strpos($expression, './')) {
|
Chris@0
|
1024 $expression = 'self::'.substr($expression, 2);
|
Chris@0
|
1025 } elseif (0 === strpos($expression, 'child::')) {
|
Chris@0
|
1026 $expression = 'self::'.substr($expression, 7);
|
Chris@0
|
1027 } elseif ('/' === $expression[0] || '.' === $expression[0] || 0 === strpos($expression, 'self::')) {
|
Chris@0
|
1028 $expression = $nonMatchingExpression;
|
Chris@0
|
1029 } elseif (0 === strpos($expression, 'descendant::')) {
|
Chris@0
|
1030 $expression = 'descendant-or-self::'.substr($expression, 12);
|
Chris@0
|
1031 } elseif (preg_match('/^(ancestor|ancestor-or-self|attribute|following|following-sibling|namespace|parent|preceding|preceding-sibling)::/', $expression)) {
|
Chris@0
|
1032 // the fake root has no parent, preceding or following nodes and also no attributes (even no namespace attributes)
|
Chris@0
|
1033 $expression = $nonMatchingExpression;
|
Chris@0
|
1034 } elseif (0 !== strpos($expression, 'descendant-or-self::')) {
|
Chris@0
|
1035 $expression = 'self::'.$expression;
|
Chris@0
|
1036 }
|
Chris@0
|
1037 $expressions[] = $parenthesis.$expression;
|
Chris@0
|
1038
|
Chris@0
|
1039 if ($i === $xpathLen) {
|
Chris@0
|
1040 return implode(' | ', $expressions);
|
Chris@0
|
1041 }
|
Chris@0
|
1042
|
Chris@0
|
1043 $i += strspn($xpath, " \t\n\r\0\x0B", $i + 1);
|
Chris@0
|
1044 $startPosition = $i + 1;
|
Chris@0
|
1045 }
|
Chris@0
|
1046
|
Chris@0
|
1047 return $xpath; // The XPath expression is invalid
|
Chris@0
|
1048 }
|
Chris@0
|
1049
|
Chris@0
|
1050 /**
|
Chris@0
|
1051 * @param int $position
|
Chris@0
|
1052 *
|
Chris@0
|
1053 * @return \DOMElement|null
|
Chris@0
|
1054 */
|
Chris@0
|
1055 public function getNode($position)
|
Chris@0
|
1056 {
|
Chris@0
|
1057 if (isset($this->nodes[$position])) {
|
Chris@0
|
1058 return $this->nodes[$position];
|
Chris@0
|
1059 }
|
Chris@0
|
1060 }
|
Chris@0
|
1061
|
Chris@0
|
1062 /**
|
Chris@0
|
1063 * @return int
|
Chris@0
|
1064 */
|
Chris@0
|
1065 public function count()
|
Chris@0
|
1066 {
|
Chris@17
|
1067 return \count($this->nodes);
|
Chris@0
|
1068 }
|
Chris@0
|
1069
|
Chris@0
|
1070 /**
|
Chris@12
|
1071 * @return \ArrayIterator|\DOMElement[]
|
Chris@0
|
1072 */
|
Chris@0
|
1073 public function getIterator()
|
Chris@0
|
1074 {
|
Chris@0
|
1075 return new \ArrayIterator($this->nodes);
|
Chris@0
|
1076 }
|
Chris@0
|
1077
|
Chris@0
|
1078 /**
|
Chris@0
|
1079 * @param \DOMElement $node
|
Chris@0
|
1080 * @param string $siblingDir
|
Chris@0
|
1081 *
|
Chris@0
|
1082 * @return array
|
Chris@0
|
1083 */
|
Chris@0
|
1084 protected function sibling($node, $siblingDir = 'nextSibling')
|
Chris@0
|
1085 {
|
Chris@17
|
1086 $nodes = [];
|
Chris@0
|
1087
|
Chris@0
|
1088 do {
|
Chris@12
|
1089 if ($node !== $this->getNode(0) && 1 === $node->nodeType) {
|
Chris@0
|
1090 $nodes[] = $node;
|
Chris@0
|
1091 }
|
Chris@0
|
1092 } while ($node = $node->$siblingDir);
|
Chris@0
|
1093
|
Chris@0
|
1094 return $nodes;
|
Chris@0
|
1095 }
|
Chris@0
|
1096
|
Chris@0
|
1097 /**
|
Chris@0
|
1098 * @param \DOMDocument $document
|
Chris@0
|
1099 * @param array $prefixes
|
Chris@0
|
1100 *
|
Chris@0
|
1101 * @return \DOMXPath
|
Chris@0
|
1102 *
|
Chris@0
|
1103 * @throws \InvalidArgumentException
|
Chris@0
|
1104 */
|
Chris@17
|
1105 private function createDOMXPath(\DOMDocument $document, array $prefixes = [])
|
Chris@0
|
1106 {
|
Chris@0
|
1107 $domxpath = new \DOMXPath($document);
|
Chris@0
|
1108
|
Chris@0
|
1109 foreach ($prefixes as $prefix) {
|
Chris@0
|
1110 $namespace = $this->discoverNamespace($domxpath, $prefix);
|
Chris@0
|
1111 if (null !== $namespace) {
|
Chris@0
|
1112 $domxpath->registerNamespace($prefix, $namespace);
|
Chris@0
|
1113 }
|
Chris@0
|
1114 }
|
Chris@0
|
1115
|
Chris@0
|
1116 return $domxpath;
|
Chris@0
|
1117 }
|
Chris@0
|
1118
|
Chris@0
|
1119 /**
|
Chris@0
|
1120 * @param \DOMXPath $domxpath
|
Chris@0
|
1121 * @param string $prefix
|
Chris@0
|
1122 *
|
Chris@0
|
1123 * @return string
|
Chris@0
|
1124 *
|
Chris@0
|
1125 * @throws \InvalidArgumentException
|
Chris@0
|
1126 */
|
Chris@0
|
1127 private function discoverNamespace(\DOMXPath $domxpath, $prefix)
|
Chris@0
|
1128 {
|
Chris@0
|
1129 if (isset($this->namespaces[$prefix])) {
|
Chris@0
|
1130 return $this->namespaces[$prefix];
|
Chris@0
|
1131 }
|
Chris@0
|
1132
|
Chris@0
|
1133 // ask for one namespace, otherwise we'd get a collection with an item for each node
|
Chris@0
|
1134 $namespaces = $domxpath->query(sprintf('(//namespace::*[name()="%s"])[last()]', $this->defaultNamespacePrefix === $prefix ? '' : $prefix));
|
Chris@0
|
1135
|
Chris@0
|
1136 if ($node = $namespaces->item(0)) {
|
Chris@0
|
1137 return $node->nodeValue;
|
Chris@0
|
1138 }
|
Chris@0
|
1139 }
|
Chris@0
|
1140
|
Chris@0
|
1141 /**
|
Chris@0
|
1142 * @param string $xpath
|
Chris@0
|
1143 *
|
Chris@0
|
1144 * @return array
|
Chris@0
|
1145 */
|
Chris@0
|
1146 private function findNamespacePrefixes($xpath)
|
Chris@0
|
1147 {
|
Chris@0
|
1148 if (preg_match_all('/(?P<prefix>[a-z_][a-z_0-9\-\.]*+):[^"\/:]/i', $xpath, $matches)) {
|
Chris@0
|
1149 return array_unique($matches['prefix']);
|
Chris@0
|
1150 }
|
Chris@0
|
1151
|
Chris@17
|
1152 return [];
|
Chris@0
|
1153 }
|
Chris@0
|
1154
|
Chris@0
|
1155 /**
|
Chris@0
|
1156 * Creates a crawler for some subnodes.
|
Chris@0
|
1157 *
|
Chris@0
|
1158 * @param \DOMElement|\DOMElement[]|\DOMNodeList|null $nodes
|
Chris@0
|
1159 *
|
Chris@0
|
1160 * @return static
|
Chris@0
|
1161 */
|
Chris@0
|
1162 private function createSubCrawler($nodes)
|
Chris@0
|
1163 {
|
Chris@0
|
1164 $crawler = new static($nodes, $this->uri, $this->baseHref);
|
Chris@0
|
1165 $crawler->isHtml = $this->isHtml;
|
Chris@0
|
1166 $crawler->document = $this->document;
|
Chris@0
|
1167 $crawler->namespaces = $this->namespaces;
|
Chris@0
|
1168
|
Chris@0
|
1169 return $crawler;
|
Chris@0
|
1170 }
|
Chris@0
|
1171 }
|