Skip to content

Instantly share code, notes, and snippets.

@davidwebca
Last active March 17, 2023 13:28
Show Gist options
  • Save davidwebca/ad2890ad8c0dc3156036051294b6e3ae to your computer and use it in GitHub Desktop.
Save davidwebca/ad2890ad8c0dc3156036051294b6e3ae to your computer and use it in GitHub Desktop.
JsondTwigExtension to fix some weird json_encode issues
<?php
/**
* Based on Indigo Viking's Twig Extension
* @see https://github.com/IndigoViking/Jsond/
*/
namespace modules\twigextensions;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
use Twig\TwigFunction;
use Craft;
/**
* @author The Indigo Viking
* @package Jsond
* @since 1
*/
class JsondTwigExtension extends AbstractExtension
{
// Public Methods
// =========================================================================
/**
* @inheritdoc
*/
public function getName()
{
return 'Jsond';
}
/**
* @inheritdoc
*/
public function getFilters()
{
return [
new TwigFilter('json_decoded', [$this, 'jsondecoded']),
new TwigFilter('json_last_error_msg', [$this, 'jsonErrorMessage']),
new TwigFilter('json_last_error', [$this, 'jsonError']),
new TwigFilter('json_encode', [$this, 'jsonEncode']),
];
}
/**
* @inheritdoc
*/
public function getFunctions()
{
return [
new TwigFunction('json_decoded', [$this, 'jsondecoded']),
new TwigFunction('json_last_error_msg', [$this, 'jsonErrorMessage']),
new TwigFunction('json_last_error', [$this, 'jsonError']),
new TwigFunction('json_encode', [$this, 'jsonEncode']),
];
}
/**
* @param null $text
*
* @return string
*/
public function jsondecoded($json, $type = false, $depth = 512, $options = null)
{
if ($options != null)
{
$decoded = json_decode($json, $type, $depth, $options);
}
else {
$decoded = json_decode($json, $type, $depth);
}
return $decoded;
}
public function jsonErrorMessage($json, $type = 'decode')
{
$error = '';
if ($type == 'encode')
{
json_encode($json);
$error = json_last_error_msg();
}
else
{
json_decode($json);
$error = json_last_error_msg();
}
return $error;
}
public function jsonError($json, $type = 'decode')
{
$error = '';
if ($type == 'encode')
{
json_encode($json);
$error = json_last_error();
}
else
{
json_decode($json);
$error = json_last_error();
}
return $error;
}
public function jsonEncode(mixed $value, int $flags = 0, int $depth = 512): string|false {
return json_encode($value, JSON_INVALID_UTF8_IGNORE | $flags, $depth);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment