Skip to content

Commit

Permalink
fix json escaper
Browse files Browse the repository at this point in the history
  • Loading branch information
jturbide committed Feb 21, 2024
1 parent 0a251ef commit 22066de
Showing 1 changed file with 7 additions and 24 deletions.
31 changes: 7 additions & 24 deletions src/Html/Escaper.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,40 +11,23 @@

namespace Zemit\Html;

use Zemit\Filters;

/**
* {@inheritDoc}
*/
class Escaper extends \Phalcon\Html\Escaper
{
/**
* Execute the rawurlencode function on the json string
* Will also encode the parameter in json format if the passed
* parameter is not a valid json
* Escapes a JSON string by raw URL encoding it.
*
* Frontend JS side must:
* JSON.parse(decodeURIComponent('<?= $this->escaper->escapeJson([]);?>'));
* JS side could decode and parse this way:
* JSON.parse(decodeURIComponent('<?= $this->escaper->escapeJson([]);?>'));
*
* @param mixed|string $json Json string or anything else
* @return string
* @param mixed|null $json The JSON string to escape. If null, an empty string is escaped.
* @return string Returns the raw URL encoded JSON string.
*/
public function escapeJson($json = null): string
public function escapeJson(mixed $json = null): string
{

// if it's a not empty string
if (is_string($json) && !empty($json)) {

// check if it's a valid json
$ret = (new Filters\Json())->filter($json);
}

// not a valid json, json encode it
if (empty($ret)) {
$ret = json_encode($json);
}

// raw url encode
return rawurlencode($ret);
return rawurlencode(json_validate($json) ? $json : json_encode($json));
}
}

0 comments on commit 22066de

Please sign in to comment.