Crawler.php 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171
  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 \DOMElement[]
  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 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, $uri = null, $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 = [];
  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(['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 = [];
  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 = [];
  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 = [];
  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) : []);
  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 = [];
  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(['_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 = [];
  555. foreach ($this->nodes as $node) {
  556. $elements = [];
  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. $xpath = sprintf('descendant-or-self::a[contains(concat(\' \', normalize-space(string(.)), \' \'), %s) ', static::xpathLiteral(' '.$value.' ')).
  619. sprintf('or ./img[contains(concat(\' \', normalize-space(string(@alt)), \' \'), %s)]]', static::xpathLiteral(' '.$value.' '));
  620. return $this->filterRelativeXPath($xpath);
  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. $translate = 'translate(@type, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz")';
  644. $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.' ')).
  645. 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)).
  646. 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));
  647. return $this->filterRelativeXPath($xpath);
  648. }
  649. /**
  650. * Returns a Link object for the first node in the list.
  651. *
  652. * @param string $method The method for the link (get by default)
  653. *
  654. * @return Link A Link instance
  655. *
  656. * @throws \InvalidArgumentException If the current node list is empty or the selected node is not instance of DOMElement
  657. */
  658. public function link($method = 'get')
  659. {
  660. if (!$this->nodes) {
  661. throw new \InvalidArgumentException('The current node list is empty.');
  662. }
  663. $node = $this->getNode(0);
  664. if (!$node instanceof \DOMElement) {
  665. throw new \InvalidArgumentException(sprintf('The selected node should be instance of DOMElement, got "%s".', \get_class($node)));
  666. }
  667. return new Link($node, $this->baseHref, $method);
  668. }
  669. /**
  670. * Returns an array of Link objects for the nodes in the list.
  671. *
  672. * @return Link[] An array of Link instances
  673. *
  674. * @throws \InvalidArgumentException If the current node list contains non-DOMElement instances
  675. */
  676. public function links()
  677. {
  678. $links = [];
  679. foreach ($this->nodes as $node) {
  680. if (!$node instanceof \DOMElement) {
  681. throw new \InvalidArgumentException(sprintf('The current node list should contain only DOMElement instances, "%s" found.', \get_class($node)));
  682. }
  683. $links[] = new Link($node, $this->baseHref, 'get');
  684. }
  685. return $links;
  686. }
  687. /**
  688. * Returns an Image object for the first node in the list.
  689. *
  690. * @return Image An Image instance
  691. *
  692. * @throws \InvalidArgumentException If the current node list is empty
  693. */
  694. public function image()
  695. {
  696. if (!\count($this)) {
  697. throw new \InvalidArgumentException('The current node list is empty.');
  698. }
  699. $node = $this->getNode(0);
  700. if (!$node instanceof \DOMElement) {
  701. throw new \InvalidArgumentException(sprintf('The selected node should be instance of DOMElement, got "%s".', \get_class($node)));
  702. }
  703. return new Image($node, $this->baseHref);
  704. }
  705. /**
  706. * Returns an array of Image objects for the nodes in the list.
  707. *
  708. * @return Image[] An array of Image instances
  709. */
  710. public function images()
  711. {
  712. $images = [];
  713. foreach ($this as $node) {
  714. if (!$node instanceof \DOMElement) {
  715. throw new \InvalidArgumentException(sprintf('The current node list should contain only DOMElement instances, "%s" found.', \get_class($node)));
  716. }
  717. $images[] = new Image($node, $this->baseHref);
  718. }
  719. return $images;
  720. }
  721. /**
  722. * Returns a Form object for the first node in the list.
  723. *
  724. * @param array $values An array of values for the form fields
  725. * @param string $method The method for the form
  726. *
  727. * @return Form A Form instance
  728. *
  729. * @throws \InvalidArgumentException If the current node list is empty or the selected node is not instance of DOMElement
  730. */
  731. public function form(array $values = null, $method = null)
  732. {
  733. if (!$this->nodes) {
  734. throw new \InvalidArgumentException('The current node list is empty.');
  735. }
  736. $node = $this->getNode(0);
  737. if (!$node instanceof \DOMElement) {
  738. throw new \InvalidArgumentException(sprintf('The selected node should be instance of DOMElement, got "%s".', \get_class($node)));
  739. }
  740. $form = new Form($node, $this->uri, $method, $this->baseHref);
  741. if (null !== $values) {
  742. $form->setValues($values);
  743. }
  744. return $form;
  745. }
  746. /**
  747. * Overloads a default namespace prefix to be used with XPath and CSS expressions.
  748. *
  749. * @param string $prefix
  750. */
  751. public function setDefaultNamespacePrefix($prefix)
  752. {
  753. $this->defaultNamespacePrefix = $prefix;
  754. }
  755. /**
  756. * @param string $prefix
  757. * @param string $namespace
  758. */
  759. public function registerNamespace($prefix, $namespace)
  760. {
  761. $this->namespaces[$prefix] = $namespace;
  762. }
  763. /**
  764. * Converts string for XPath expressions.
  765. *
  766. * Escaped characters are: quotes (") and apostrophe (').
  767. *
  768. * Examples:
  769. *
  770. * echo Crawler::xpathLiteral('foo " bar');
  771. * //prints 'foo " bar'
  772. *
  773. * echo Crawler::xpathLiteral("foo ' bar");
  774. * //prints "foo ' bar"
  775. *
  776. * echo Crawler::xpathLiteral('a\'b"c');
  777. * //prints concat('a', "'", 'b"c')
  778. *
  779. *
  780. * @param string $s String to be escaped
  781. *
  782. * @return string Converted string
  783. */
  784. public static function xpathLiteral($s)
  785. {
  786. if (false === strpos($s, "'")) {
  787. return sprintf("'%s'", $s);
  788. }
  789. if (false === strpos($s, '"')) {
  790. return sprintf('"%s"', $s);
  791. }
  792. $string = $s;
  793. $parts = [];
  794. while (true) {
  795. if (false !== $pos = strpos($string, "'")) {
  796. $parts[] = sprintf("'%s'", substr($string, 0, $pos));
  797. $parts[] = "\"'\"";
  798. $string = substr($string, $pos + 1);
  799. } else {
  800. $parts[] = "'$string'";
  801. break;
  802. }
  803. }
  804. return sprintf('concat(%s)', implode(', ', $parts));
  805. }
  806. /**
  807. * Filters the list of nodes with an XPath expression.
  808. *
  809. * The XPath expression should already be processed to apply it in the context of each node.
  810. *
  811. * @param string $xpath
  812. *
  813. * @return self
  814. */
  815. private function filterRelativeXPath($xpath)
  816. {
  817. $prefixes = $this->findNamespacePrefixes($xpath);
  818. $crawler = $this->createSubCrawler(null);
  819. foreach ($this->nodes as $node) {
  820. $domxpath = $this->createDOMXPath($node->ownerDocument, $prefixes);
  821. $crawler->add($domxpath->query($xpath, $node));
  822. }
  823. return $crawler;
  824. }
  825. /**
  826. * Make the XPath relative to the current context.
  827. *
  828. * The returned XPath will match elements matching the XPath inside the current crawler
  829. * when running in the context of a node of the crawler.
  830. *
  831. * @param string $xpath
  832. *
  833. * @return string
  834. */
  835. private function relativize($xpath)
  836. {
  837. $expressions = [];
  838. // An expression which will never match to replace expressions which cannot match in the crawler
  839. // We cannot drop
  840. $nonMatchingExpression = 'a[name() = "b"]';
  841. $xpathLen = \strlen($xpath);
  842. $openedBrackets = 0;
  843. $startPosition = strspn($xpath, " \t\n\r\0\x0B");
  844. for ($i = $startPosition; $i <= $xpathLen; ++$i) {
  845. $i += strcspn($xpath, '"\'[]|', $i);
  846. if ($i < $xpathLen) {
  847. switch ($xpath[$i]) {
  848. case '"':
  849. case "'":
  850. if (false === $i = strpos($xpath, $xpath[$i], $i + 1)) {
  851. return $xpath; // The XPath expression is invalid
  852. }
  853. continue 2;
  854. case '[':
  855. ++$openedBrackets;
  856. continue 2;
  857. case ']':
  858. --$openedBrackets;
  859. continue 2;
  860. }
  861. }
  862. if ($openedBrackets) {
  863. continue;
  864. }
  865. if ($startPosition < $xpathLen && '(' === $xpath[$startPosition]) {
  866. // If the union is inside some braces, we need to preserve the opening braces and apply
  867. // the change only inside it.
  868. $j = 1 + strspn($xpath, "( \t\n\r\0\x0B", $startPosition + 1);
  869. $parenthesis = substr($xpath, $startPosition, $j);
  870. $startPosition += $j;
  871. } else {
  872. $parenthesis = '';
  873. }
  874. $expression = rtrim(substr($xpath, $startPosition, $i - $startPosition));
  875. if (0 === strpos($expression, 'self::*/')) {
  876. $expression = './'.substr($expression, 8);
  877. }
  878. // add prefix before absolute element selector
  879. if ('' === $expression) {
  880. $expression = $nonMatchingExpression;
  881. } elseif (0 === strpos($expression, '//')) {
  882. $expression = 'descendant-or-self::'.substr($expression, 2);
  883. } elseif (0 === strpos($expression, './/')) {
  884. $expression = 'descendant-or-self::'.substr($expression, 3);
  885. } elseif (0 === strpos($expression, './')) {
  886. $expression = 'self::'.substr($expression, 2);
  887. } elseif (0 === strpos($expression, 'child::')) {
  888. $expression = 'self::'.substr($expression, 7);
  889. } elseif ('/' === $expression[0] || '.' === $expression[0] || 0 === strpos($expression, 'self::')) {
  890. $expression = $nonMatchingExpression;
  891. } elseif (0 === strpos($expression, 'descendant::')) {
  892. $expression = 'descendant-or-self::'.substr($expression, 12);
  893. } elseif (preg_match('/^(ancestor|ancestor-or-self|attribute|following|following-sibling|namespace|parent|preceding|preceding-sibling)::/', $expression)) {
  894. // the fake root has no parent, preceding or following nodes and also no attributes (even no namespace attributes)
  895. $expression = $nonMatchingExpression;
  896. } elseif (0 !== strpos($expression, 'descendant-or-self::')) {
  897. $expression = 'self::'.$expression;
  898. }
  899. $expressions[] = $parenthesis.$expression;
  900. if ($i === $xpathLen) {
  901. return implode(' | ', $expressions);
  902. }
  903. $i += strspn($xpath, " \t\n\r\0\x0B", $i + 1);
  904. $startPosition = $i + 1;
  905. }
  906. return $xpath; // The XPath expression is invalid
  907. }
  908. /**
  909. * @param int $position
  910. *
  911. * @return \DOMElement|null
  912. */
  913. public function getNode($position)
  914. {
  915. if (isset($this->nodes[$position])) {
  916. return $this->nodes[$position];
  917. }
  918. }
  919. /**
  920. * @return int
  921. */
  922. public function count()
  923. {
  924. return \count($this->nodes);
  925. }
  926. /**
  927. * @return \ArrayIterator|\DOMElement[]
  928. */
  929. public function getIterator()
  930. {
  931. return new \ArrayIterator($this->nodes);
  932. }
  933. /**
  934. * @param \DOMElement $node
  935. * @param string $siblingDir
  936. *
  937. * @return array
  938. */
  939. protected function sibling($node, $siblingDir = 'nextSibling')
  940. {
  941. $nodes = [];
  942. do {
  943. if ($node !== $this->getNode(0) && 1 === $node->nodeType) {
  944. $nodes[] = $node;
  945. }
  946. } while ($node = $node->$siblingDir);
  947. return $nodes;
  948. }
  949. /**
  950. * @param \DOMDocument $document
  951. * @param array $prefixes
  952. *
  953. * @return \DOMXPath
  954. *
  955. * @throws \InvalidArgumentException
  956. */
  957. private function createDOMXPath(\DOMDocument $document, array $prefixes = [])
  958. {
  959. $domxpath = new \DOMXPath($document);
  960. foreach ($prefixes as $prefix) {
  961. $namespace = $this->discoverNamespace($domxpath, $prefix);
  962. if (null !== $namespace) {
  963. $domxpath->registerNamespace($prefix, $namespace);
  964. }
  965. }
  966. return $domxpath;
  967. }
  968. /**
  969. * @param \DOMXPath $domxpath
  970. * @param string $prefix
  971. *
  972. * @return string
  973. *
  974. * @throws \InvalidArgumentException
  975. */
  976. private function discoverNamespace(\DOMXPath $domxpath, $prefix)
  977. {
  978. if (isset($this->namespaces[$prefix])) {
  979. return $this->namespaces[$prefix];
  980. }
  981. // ask for one namespace, otherwise we'd get a collection with an item for each node
  982. $namespaces = $domxpath->query(sprintf('(//namespace::*[name()="%s"])[last()]', $this->defaultNamespacePrefix === $prefix ? '' : $prefix));
  983. if ($node = $namespaces->item(0)) {
  984. return $node->nodeValue;
  985. }
  986. }
  987. /**
  988. * @param string $xpath
  989. *
  990. * @return array
  991. */
  992. private function findNamespacePrefixes($xpath)
  993. {
  994. if (preg_match_all('/(?P<prefix>[a-z_][a-z_0-9\-\.]*+):[^"\/:]/i', $xpath, $matches)) {
  995. return array_unique($matches['prefix']);
  996. }
  997. return [];
  998. }
  999. /**
  1000. * Creates a crawler for some subnodes.
  1001. *
  1002. * @param \DOMElement|\DOMElement[]|\DOMNodeList|null $nodes
  1003. *
  1004. * @return static
  1005. */
  1006. private function createSubCrawler($nodes)
  1007. {
  1008. $crawler = new static($nodes, $this->uri, $this->baseHref);
  1009. $crawler->isHtml = $this->isHtml;
  1010. $crawler->document = $this->document;
  1011. $crawler->namespaces = $this->namespaces;
  1012. return $crawler;
  1013. }
  1014. }