Skip to content

Commit

Permalink
fix xpath php-string-to-javascript-string
Browse files Browse the repository at this point in the history
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"
  • Loading branch information
divinity76 committed Dec 13, 2023
1 parent 2b7cb13 commit 50a94b6
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) .', 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) .', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue';
}
}

0 comments on commit 50a94b6

Please sign in to comment.