Skip to content

Commit

Permalink
Escape: Unify string casting
Browse files Browse the repository at this point in the history
  • Loading branch information
jakubboucek committed Feb 28, 2022
1 parent a7bc4ce commit 0b98a8d
Showing 1 changed file with 11 additions and 8 deletions.
19 changes: 11 additions & 8 deletions src/Escape.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ class Escape
public static function html($data): string
{
if ($data instanceof HtmlStringable || $data instanceof IHtmlString) {
return $data->__toString();
return (string)$data;
}
return htmlspecialchars((string)$data, ENT_QUOTES | ENT_HTML5 | ENT_SUBSTITUTE);
}
Expand Down Expand Up @@ -78,10 +78,11 @@ public static function htmlComment($data): string
*/
public static function xml($data): string
{
$data = (string)$data;
// XML 1.0: \x09 \x0A \x0D and C1 allowed directly, C0 forbidden
// XML 1.1: \x00 forbidden directly and as a character reference,
// \x09 \x0A \x0D \x85 allowed directly, C0, C1 and \x7F allowed as character references
$data = preg_replace('#[\x00-\x08\x0B\x0C\x0E-\x1F]#', "\u{FFFD}", (string)$data);
$data = preg_replace('#[\x00-\x08\x0B\x0C\x0E-\x1F]#', "\u{FFFD}", $data);
return htmlspecialchars($data, ENT_QUOTES | ENT_XML1 | ENT_SUBSTITUTE, 'UTF-8');
}

Expand All @@ -95,7 +96,7 @@ public static function xml($data): string
public static function js($data): string
{
if ($data instanceof HtmlStringable || $data instanceof IHtmlString) {
$data = $data->__toString();
$data = (string)$data;
}

$json = Json::encode($data);
Expand All @@ -112,8 +113,9 @@ public static function js($data): string
*/
public static function css($data): string
{
$data = (string)$data;
// http://www.w3.org/TR/2006/WD-CSS21-20060411/syndata.html#q6
return addcslashes((string)$data, "\x00..\x1F!\"#$%&'()*+,./:;<=>?@[\\]^`{|}~");
return addcslashes($data, "\x00..\x1F!\"#$%&'()*+,./:;<=>?@[\\]^`{|}~");
}

/**
Expand All @@ -123,17 +125,18 @@ public static function css($data): string
*/
public static function url($url): string
{
return urlencode((string)$url);
$url = (string)$url;
return urlencode($url);
}

/**
* Just returns argument as is without any escaping
* Method is useful to mark code as intentionally unescaped as opposed to simple neglected
* @param string|mixed $url
* @param string|mixed $data
* @return string
*/
public static function noescape($url): string
public static function noescape($data): string
{
return (string)$url;
return (string)$data;
}
}

0 comments on commit 0b98a8d

Please sign in to comment.