Crawler.php 34 KB

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