simdjson_php icon indicating copy to clipboard operation
simdjson_php copied to clipboard

Add composer library /example snippets to make it easier for projects to automatically choose simdjson if supported

Open TysonAndre opened this issue 2 years ago • 0 comments

// namespace goes here

/**
 * JSON decoder
 */
final class Decoder
{
    private static $simdjsonEnabled = false;

    public static function setAllowSimdjson(bool $allow): void
    {
        self::$simdjsonEnabled = $allow && self::hasWorkingSimdjson();
    }

    public static function hasWorkingSimdjson(): bool
    {
        return version_compare(phpversion('simdjson') ?: '0', '2.1.0', '>=') &&
             class_exists('SimdJsonException');
    }

    /**
     * JSON decodes the given json string $msg
     *
     * @throws JsonException
     */
    public static function jsonDecode(string $msg, bool $associative = false)
    {
        if (self::$simdjsonEnabled) {
            try {
                return simdjson_decode($msg, $associative);
            } catch (\Exception $e) {
                // Assume errors are rare and fall through, to return the exact same Error messages
            }
        }
        $decoded = \json_decode($msg, $associative);
        if (\json_last_error() !== \JSON_ERROR_NONE) {
            throw new \JsonException(\json_last_error_msg(), \json_last_error());  // requires symfony/polyfill-php73 before php 7.3
        }
        return $decoded;
    }
}

Decoder::setAllowSimdjson(true);
use ...\Decoder;
var_export(Decoder::jsonDecode('{"a":"b"}', true));

https://github.com/crazyxman/simdjson_php/tree/master/benchmark - for applications that work with long json strings, the extra method call would be worth it

TysonAndre avatar Oct 14 '22 02:10 TysonAndre