Skip to content

Commit

Permalink
[1.10] Fix xpath php-string-to-javascript-string (#576)
Browse files Browse the repository at this point in the history
* fix xpath php-string-to-javascript-string

TL;DR: addslashes() is not the correct way to convert a php-string to a javascript string. json_encode() is.

For example, addslashes will fail on the PHP string "foo".chr(10)."bar" , the old addslashes() will convert it into
"foo
bar"

which is a javascript syntax error.

Previously this code would fail:
$str = "foo".chr(10)."bar";
$xps = new XPathSelector("//span[contains(text(),'" . $str . "')]");
var_dump($xps->expressionCount());

it would generate a javascript syntax error:
string(134) "document.evaluate("//span[contains(text(),\'foo
bar\')]", document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshot
Length"

now it generates legal javascript:

string(135) "document.evaluate("\/\/span[contains(text(),'foo\nbar')]", document
, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotLength"

* styling

* prettier run-time error messages
  • Loading branch information
divinity76 authored Mar 17, 2024
1 parent 2b7cb13 commit d53f6b5
Showing 1 changed file with 2 additions and 9 deletions.
11 changes: 2 additions & 9 deletions src/Dom/Selector/XPathSelector.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,18 +19,11 @@ public function __construct(string $expression)

public function expressionCount(): string
{
return \sprintf(
'document.evaluate("%s", document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotLength',
\addslashes($this->expression)
);
return 'document.evaluate('.\json_encode($this->expression, \JSON_THROW_ON_ERROR | \JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE).', document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotLength';
}

public function expressionFindOne(int $position): string
{
return \sprintf(
'document.evaluate("%s[%d]", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue',
\addslashes($this->expression),
$position
);
return 'document.evaluate('.\json_encode($this->expression."[{$position}]", \JSON_THROW_ON_ERROR | \JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE).', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue';
}
}

0 comments on commit d53f6b5

Please sign in to comment.