Crawler.php 34 KB

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