Crawler.php 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174
  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 string|null $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. * @param string|null $selector An optional CSS selector to filter children
  438. *
  439. * @return self
  440. *
  441. * @throws \InvalidArgumentException When current node is empty
  442. * @throws \RuntimeException If the CssSelector Component is not available and $selector is provided
  443. */
  444. public function children(/* string $selector = null */)
  445. {
  446. if (\func_num_args() < 1 && __CLASS__ !== \get_class($this) && __CLASS__ !== (new \ReflectionMethod($this, __FUNCTION__))->getDeclaringClass()->getName() && !$this instanceof \PHPUnit\Framework\MockObject\MockObject && !$this instanceof \Prophecy\Prophecy\ProphecySubjectInterface) {
  447. @trigger_error(sprintf('The "%s()" method will have a new "string $selector = null" argument in version 5.0, not defining it is deprecated since Symfony 4.2.', __METHOD__), E_USER_DEPRECATED);
  448. }
  449. $selector = 0 < \func_num_args() ? func_get_arg(0) : null;
  450. if (!$this->nodes) {
  451. throw new \InvalidArgumentException('The current node list is empty.');
  452. }
  453. if (null !== $selector) {
  454. $converter = $this->createCssSelectorConverter();
  455. $xpath = $converter->toXPath($selector, 'child::');
  456. return $this->filterRelativeXPath($xpath);
  457. }
  458. $node = $this->getNode(0)->firstChild;
  459. return $this->createSubCrawler($node ? $this->sibling($node) : array());
  460. }
  461. /**
  462. * Returns the attribute value of the first node of the list.
  463. *
  464. * @param string $attribute The attribute name
  465. *
  466. * @return string|null The attribute value or null if the attribute does not exist
  467. *
  468. * @throws \InvalidArgumentException When current node is empty
  469. */
  470. public function attr($attribute)
  471. {
  472. if (!$this->nodes) {
  473. throw new \InvalidArgumentException('The current node list is empty.');
  474. }
  475. $node = $this->getNode(0);
  476. return $node->hasAttribute($attribute) ? $node->getAttribute($attribute) : null;
  477. }
  478. /**
  479. * Returns the node name of the first node of the list.
  480. *
  481. * @return string The node name
  482. *
  483. * @throws \InvalidArgumentException When current node is empty
  484. */
  485. public function nodeName()
  486. {
  487. if (!$this->nodes) {
  488. throw new \InvalidArgumentException('The current node list is empty.');
  489. }
  490. return $this->getNode(0)->nodeName;
  491. }
  492. /**
  493. * Returns the node value of the first node of the list.
  494. *
  495. * @return string The node value
  496. *
  497. * @throws \InvalidArgumentException When current node is empty
  498. */
  499. public function text()
  500. {
  501. if (!$this->nodes) {
  502. throw new \InvalidArgumentException('The current node list is empty.');
  503. }
  504. return $this->getNode(0)->nodeValue;
  505. }
  506. /**
  507. * Returns the first node of the list as HTML.
  508. *
  509. * @return string The node html
  510. *
  511. * @throws \InvalidArgumentException When current node is empty
  512. */
  513. public function html()
  514. {
  515. if (!$this->nodes) {
  516. throw new \InvalidArgumentException('The current node list is empty.');
  517. }
  518. $html = '';
  519. foreach ($this->getNode(0)->childNodes as $child) {
  520. $html .= $child->ownerDocument->saveHTML($child);
  521. }
  522. return $html;
  523. }
  524. /**
  525. * Evaluates an XPath expression.
  526. *
  527. * Since an XPath expression might evaluate to either a simple type or a \DOMNodeList,
  528. * this method will return either an array of simple types or a new Crawler instance.
  529. *
  530. * @param string $xpath An XPath expression
  531. *
  532. * @return array|Crawler An array of evaluation results or a new Crawler instance
  533. */
  534. public function evaluate($xpath)
  535. {
  536. if (null === $this->document) {
  537. throw new \LogicException('Cannot evaluate the expression on an uninitialized crawler.');
  538. }
  539. $data = array();
  540. $domxpath = $this->createDOMXPath($this->document, $this->findNamespacePrefixes($xpath));
  541. foreach ($this->nodes as $node) {
  542. $data[] = $domxpath->evaluate($xpath, $node);
  543. }
  544. if (isset($data[0]) && $data[0] instanceof \DOMNodeList) {
  545. return $this->createSubCrawler($data);
  546. }
  547. return $data;
  548. }
  549. /**
  550. * Extracts information from the list of nodes.
  551. *
  552. * You can extract attributes or/and the node value (_text).
  553. *
  554. * Example:
  555. *
  556. * $crawler->filter('h1 a')->extract(array('_text', 'href'));
  557. *
  558. * @param array $attributes An array of attributes
  559. *
  560. * @return array An array of extracted values
  561. */
  562. public function extract($attributes)
  563. {
  564. $attributes = (array) $attributes;
  565. $count = \count($attributes);
  566. $data = array();
  567. foreach ($this->nodes as $node) {
  568. $elements = array();
  569. foreach ($attributes as $attribute) {
  570. if ('_text' === $attribute) {
  571. $elements[] = $node->nodeValue;
  572. } else {
  573. $elements[] = $node->getAttribute($attribute);
  574. }
  575. }
  576. $data[] = 1 === $count ? $elements[0] : $elements;
  577. }
  578. return $data;
  579. }
  580. /**
  581. * Filters the list of nodes with an XPath expression.
  582. *
  583. * The XPath expression is evaluated in the context of the crawler, which
  584. * is considered as a fake parent of the elements inside it.
  585. * This means that a child selector "div" or "./div" will match only
  586. * the div elements of the current crawler, not their children.
  587. *
  588. * @param string $xpath An XPath expression
  589. *
  590. * @return self
  591. */
  592. public function filterXPath($xpath)
  593. {
  594. $xpath = $this->relativize($xpath);
  595. // If we dropped all expressions in the XPath while preparing it, there would be no match
  596. if ('' === $xpath) {
  597. return $this->createSubCrawler(null);
  598. }
  599. return $this->filterRelativeXPath($xpath);
  600. }
  601. /**
  602. * Filters the list of nodes with a CSS selector.
  603. *
  604. * This method only works if you have installed the CssSelector Symfony Component.
  605. *
  606. * @param string $selector A CSS selector
  607. *
  608. * @return self
  609. *
  610. * @throws \RuntimeException if the CssSelector Component is not available
  611. */
  612. public function filter($selector)
  613. {
  614. $converter = $this->createCssSelectorConverter();
  615. // The CssSelector already prefixes the selector with descendant-or-self::
  616. return $this->filterRelativeXPath($converter->toXPath($selector));
  617. }
  618. /**
  619. * Selects links by name or alt value for clickable images.
  620. *
  621. * @param string $value The link text
  622. *
  623. * @return self
  624. */
  625. public function selectLink($value)
  626. {
  627. return $this->filterRelativeXPath(
  628. 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.' '))
  629. );
  630. }
  631. /**
  632. * Selects images by alt value.
  633. *
  634. * @param string $value The image alt
  635. *
  636. * @return self A new instance of Crawler with the filtered list of nodes
  637. */
  638. public function selectImage($value)
  639. {
  640. $xpath = sprintf('descendant-or-self::img[contains(normalize-space(string(@alt)), %s)]', static::xpathLiteral($value));
  641. return $this->filterRelativeXPath($xpath);
  642. }
  643. /**
  644. * Selects a button by name or alt value for images.
  645. *
  646. * @param string $value The button text
  647. *
  648. * @return self
  649. */
  650. public function selectButton($value)
  651. {
  652. return $this->filterRelativeXPath(
  653. 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))
  654. );
  655. }
  656. /**
  657. * Returns a Link object for the first node in the list.
  658. *
  659. * @param string $method The method for the link (get by default)
  660. *
  661. * @return Link A Link instance
  662. *
  663. * @throws \InvalidArgumentException If the current node list is empty or the selected node is not instance of DOMElement
  664. */
  665. public function link($method = 'get')
  666. {
  667. if (!$this->nodes) {
  668. throw new \InvalidArgumentException('The current node list is empty.');
  669. }
  670. $node = $this->getNode(0);
  671. if (!$node instanceof \DOMElement) {
  672. throw new \InvalidArgumentException(sprintf('The selected node should be instance of DOMElement, got "%s".', \get_class($node)));
  673. }
  674. return new Link($node, $this->baseHref, $method);
  675. }
  676. /**
  677. * Returns an array of Link objects for the nodes in the list.
  678. *
  679. * @return Link[] An array of Link instances
  680. *
  681. * @throws \InvalidArgumentException If the current node list contains non-DOMElement instances
  682. */
  683. public function links()
  684. {
  685. $links = array();
  686. foreach ($this->nodes as $node) {
  687. if (!$node instanceof \DOMElement) {
  688. throw new \InvalidArgumentException(sprintf('The current node list should contain only DOMElement instances, "%s" found.', \get_class($node)));
  689. }
  690. $links[] = new Link($node, $this->baseHref, 'get');
  691. }
  692. return $links;
  693. }
  694. /**
  695. * Returns an Image object for the first node in the list.
  696. *
  697. * @return Image An Image instance
  698. *
  699. * @throws \InvalidArgumentException If the current node list is empty
  700. */
  701. public function image()
  702. {
  703. if (!\count($this)) {
  704. throw new \InvalidArgumentException('The current node list is empty.');
  705. }
  706. $node = $this->getNode(0);
  707. if (!$node instanceof \DOMElement) {
  708. throw new \InvalidArgumentException(sprintf('The selected node should be instance of DOMElement, got "%s".', \get_class($node)));
  709. }
  710. return new Image($node, $this->baseHref);
  711. }
  712. /**
  713. * Returns an array of Image objects for the nodes in the list.
  714. *
  715. * @return Image[] An array of Image instances
  716. */
  717. public function images()
  718. {
  719. $images = array();
  720. foreach ($this as $node) {
  721. if (!$node instanceof \DOMElement) {
  722. throw new \InvalidArgumentException(sprintf('The current node list should contain only DOMElement instances, "%s" found.', \get_class($node)));
  723. }
  724. $images[] = new Image($node, $this->baseHref);
  725. }
  726. return $images;
  727. }
  728. /**
  729. * Returns a Form object for the first node in the list.
  730. *
  731. * @param array $values An array of values for the form fields
  732. * @param string $method The method for the form
  733. *
  734. * @return Form A Form instance
  735. *
  736. * @throws \InvalidArgumentException If the current node list is empty or the selected node is not instance of DOMElement
  737. */
  738. public function form(array $values = null, $method = null)
  739. {
  740. if (!$this->nodes) {
  741. throw new \InvalidArgumentException('The current node list is empty.');
  742. }
  743. $node = $this->getNode(0);
  744. if (!$node instanceof \DOMElement) {
  745. throw new \InvalidArgumentException(sprintf('The selected node should be instance of DOMElement, got "%s".', \get_class($node)));
  746. }
  747. $form = new Form($node, $this->uri, $method, $this->baseHref);
  748. if (null !== $values) {
  749. $form->setValues($values);
  750. }
  751. return $form;
  752. }
  753. /**
  754. * Overloads a default namespace prefix to be used with XPath and CSS expressions.
  755. *
  756. * @param string $prefix
  757. */
  758. public function setDefaultNamespacePrefix($prefix)
  759. {
  760. $this->defaultNamespacePrefix = $prefix;
  761. }
  762. /**
  763. * @param string $prefix
  764. * @param string $namespace
  765. */
  766. public function registerNamespace($prefix, $namespace)
  767. {
  768. $this->namespaces[$prefix] = $namespace;
  769. }
  770. /**
  771. * Converts string for XPath expressions.
  772. *
  773. * Escaped characters are: quotes (") and apostrophe (').
  774. *
  775. * Examples:
  776. *
  777. * echo Crawler::xpathLiteral('foo " bar');
  778. * //prints 'foo " bar'
  779. *
  780. * echo Crawler::xpathLiteral("foo ' bar");
  781. * //prints "foo ' bar"
  782. *
  783. * echo Crawler::xpathLiteral('a\'b"c');
  784. * //prints concat('a', "'", 'b"c')
  785. *
  786. *
  787. * @param string $s String to be escaped
  788. *
  789. * @return string Converted string
  790. */
  791. public static function xpathLiteral($s)
  792. {
  793. if (false === strpos($s, "'")) {
  794. return sprintf("'%s'", $s);
  795. }
  796. if (false === strpos($s, '"')) {
  797. return sprintf('"%s"', $s);
  798. }
  799. $string = $s;
  800. $parts = array();
  801. while (true) {
  802. if (false !== $pos = strpos($string, "'")) {
  803. $parts[] = sprintf("'%s'", substr($string, 0, $pos));
  804. $parts[] = "\"'\"";
  805. $string = substr($string, $pos + 1);
  806. } else {
  807. $parts[] = "'$string'";
  808. break;
  809. }
  810. }
  811. return sprintf('concat(%s)', implode(', ', $parts));
  812. }
  813. /**
  814. * Filters the list of nodes with an XPath expression.
  815. *
  816. * The XPath expression should already be processed to apply it in the context of each node.
  817. *
  818. * @param string $xpath
  819. *
  820. * @return self
  821. */
  822. private function filterRelativeXPath($xpath)
  823. {
  824. $prefixes = $this->findNamespacePrefixes($xpath);
  825. $crawler = $this->createSubCrawler(null);
  826. foreach ($this->nodes as $node) {
  827. $domxpath = $this->createDOMXPath($node->ownerDocument, $prefixes);
  828. $crawler->add($domxpath->query($xpath, $node));
  829. }
  830. return $crawler;
  831. }
  832. /**
  833. * Make the XPath relative to the current context.
  834. *
  835. * The returned XPath will match elements matching the XPath inside the current crawler
  836. * when running in the context of a node of the crawler.
  837. */
  838. private function relativize(string $xpath): string
  839. {
  840. $expressions = array();
  841. // An expression which will never match to replace expressions which cannot match in the crawler
  842. // We cannot simply drop
  843. $nonMatchingExpression = 'a[name() = "b"]';
  844. $xpathLen = \strlen($xpath);
  845. $openedBrackets = 0;
  846. $startPosition = strspn($xpath, " \t\n\r\0\x0B");
  847. for ($i = $startPosition; $i <= $xpathLen; ++$i) {
  848. $i += strcspn($xpath, '"\'[]|', $i);
  849. if ($i < $xpathLen) {
  850. switch ($xpath[$i]) {
  851. case '"':
  852. case "'":
  853. if (false === $i = strpos($xpath, $xpath[$i], $i + 1)) {
  854. return $xpath; // The XPath expression is invalid
  855. }
  856. continue 2;
  857. case '[':
  858. ++$openedBrackets;
  859. continue 2;
  860. case ']':
  861. --$openedBrackets;
  862. continue 2;
  863. }
  864. }
  865. if ($openedBrackets) {
  866. continue;
  867. }
  868. if ($startPosition < $xpathLen && '(' === $xpath[$startPosition]) {
  869. // If the union is inside some braces, we need to preserve the opening braces and apply
  870. // the change only inside it.
  871. $j = 1 + strspn($xpath, "( \t\n\r\0\x0B", $startPosition + 1);
  872. $parenthesis = substr($xpath, $startPosition, $j);
  873. $startPosition += $j;
  874. } else {
  875. $parenthesis = '';
  876. }
  877. $expression = rtrim(substr($xpath, $startPosition, $i - $startPosition));
  878. if (0 === strpos($expression, 'self::*/')) {
  879. $expression = './'.substr($expression, 8);
  880. }
  881. // add prefix before absolute element selector
  882. if ('' === $expression) {
  883. $expression = $nonMatchingExpression;
  884. } elseif (0 === strpos($expression, '//')) {
  885. $expression = 'descendant-or-self::'.substr($expression, 2);
  886. } elseif (0 === strpos($expression, './/')) {
  887. $expression = 'descendant-or-self::'.substr($expression, 3);
  888. } elseif (0 === strpos($expression, './')) {
  889. $expression = 'self::'.substr($expression, 2);
  890. } elseif (0 === strpos($expression, 'child::')) {
  891. $expression = 'self::'.substr($expression, 7);
  892. } elseif ('/' === $expression[0] || '.' === $expression[0] || 0 === strpos($expression, 'self::')) {
  893. $expression = $nonMatchingExpression;
  894. } elseif (0 === strpos($expression, 'descendant::')) {
  895. $expression = 'descendant-or-self::'.substr($expression, 12);
  896. } elseif (preg_match('/^(ancestor|ancestor-or-self|attribute|following|following-sibling|namespace|parent|preceding|preceding-sibling)::/', $expression)) {
  897. // the fake root has no parent, preceding or following nodes and also no attributes (even no namespace attributes)
  898. $expression = $nonMatchingExpression;
  899. } elseif (0 !== strpos($expression, 'descendant-or-self::')) {
  900. $expression = 'self::'.$expression;
  901. }
  902. $expressions[] = $parenthesis.$expression;
  903. if ($i === $xpathLen) {
  904. return implode(' | ', $expressions);
  905. }
  906. $i += strspn($xpath, " \t\n\r\0\x0B", $i + 1);
  907. $startPosition = $i + 1;
  908. }
  909. return $xpath; // The XPath expression is invalid
  910. }
  911. /**
  912. * @param int $position
  913. *
  914. * @return \DOMElement|null
  915. */
  916. public function getNode($position)
  917. {
  918. if (isset($this->nodes[$position])) {
  919. return $this->nodes[$position];
  920. }
  921. }
  922. /**
  923. * @return int
  924. */
  925. public function count()
  926. {
  927. return \count($this->nodes);
  928. }
  929. /**
  930. * @return \ArrayIterator|\DOMElement[]
  931. */
  932. public function getIterator()
  933. {
  934. return new \ArrayIterator($this->nodes);
  935. }
  936. /**
  937. * @param \DOMElement $node
  938. * @param string $siblingDir
  939. *
  940. * @return array
  941. */
  942. protected function sibling($node, $siblingDir = 'nextSibling')
  943. {
  944. $nodes = array();
  945. $currentNode = $this->getNode(0);
  946. do {
  947. if ($node !== $currentNode && XML_ELEMENT_NODE === $node->nodeType) {
  948. $nodes[] = $node;
  949. }
  950. } while ($node = $node->$siblingDir);
  951. return $nodes;
  952. }
  953. /**
  954. * @throws \InvalidArgumentException
  955. */
  956. private function createDOMXPath(\DOMDocument $document, array $prefixes = array()): \DOMXPath
  957. {
  958. $domxpath = new \DOMXPath($document);
  959. foreach ($prefixes as $prefix) {
  960. $namespace = $this->discoverNamespace($domxpath, $prefix);
  961. if (null !== $namespace) {
  962. $domxpath->registerNamespace($prefix, $namespace);
  963. }
  964. }
  965. return $domxpath;
  966. }
  967. /**
  968. * @throws \InvalidArgumentException
  969. */
  970. private function discoverNamespace(\DOMXPath $domxpath, string $prefix): ?string
  971. {
  972. if (isset($this->namespaces[$prefix])) {
  973. return $this->namespaces[$prefix];
  974. }
  975. // ask for one namespace, otherwise we'd get a collection with an item for each node
  976. $namespaces = $domxpath->query(sprintf('(//namespace::*[name()="%s"])[last()]', $this->defaultNamespacePrefix === $prefix ? '' : $prefix));
  977. if ($node = $namespaces->item(0)) {
  978. return $node->nodeValue;
  979. }
  980. return null;
  981. }
  982. private function findNamespacePrefixes(string $xpath): array
  983. {
  984. if (preg_match_all('/(?P<prefix>[a-z_][a-z_0-9\-\.]*+):[^"\/:]/i', $xpath, $matches)) {
  985. return array_unique($matches['prefix']);
  986. }
  987. return array();
  988. }
  989. /**
  990. * Creates a crawler for some subnodes.
  991. *
  992. * @param \DOMElement|\DOMElement[]|\DOMNodeList|null $nodes
  993. *
  994. * @return static
  995. */
  996. private function createSubCrawler($nodes)
  997. {
  998. $crawler = new static($nodes, $this->uri, $this->baseHref);
  999. $crawler->isHtml = $this->isHtml;
  1000. $crawler->document = $this->document;
  1001. $crawler->namespaces = $this->namespaces;
  1002. return $crawler;
  1003. }
  1004. /**
  1005. * @throws \RuntimeException If the CssSelector Component is not available
  1006. */
  1007. private function createCssSelectorConverter(): CssSelectorConverter
  1008. {
  1009. if (!\class_exists(CssSelectorConverter::class)) {
  1010. throw new \LogicException('To filter with a CSS selector, install the CssSelector component ("composer require symfony/css-selector"). Or use filterXpath instead.');
  1011. }
  1012. return new CssSelectorConverter($this->isHtml);
  1013. }
  1014. }