|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace ProcessMaker\Support; |
| 4 | + |
| 5 | +use Illuminate\Support\Facades\Log; |
| 6 | + |
| 7 | +class JsonOptimizer |
| 8 | +{ |
| 9 | + /** |
| 10 | + * Global configuration set by ServiceProvider |
| 11 | + */ |
| 12 | + public static bool $useSimdjsonDecode = false; |
| 13 | + |
| 14 | + public static bool $useSimdjsonEncode = false; |
| 15 | + |
| 16 | + /** |
| 17 | + * Decodes a JSON using simdjson if available. |
| 18 | + */ |
| 19 | + public static function decode(string $json, bool $assoc = false, int $depth = 512, int $options = 0) |
| 20 | + { |
| 21 | + if (self::$useSimdjsonDecode) { |
| 22 | + try { |
| 23 | + return simdjson_decode($json, $assoc, $depth); |
| 24 | + } catch (\Throwable $e) { |
| 25 | + Log::warning("simdjson_decode failed: {$e->getMessage()}"); |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + return json_decode($json, $assoc, $depth, $options); |
| 30 | + } |
| 31 | + |
| 32 | + /** |
| 33 | + * Encodes a JSON using simdjson if available. |
| 34 | + * But json_encode is more performant than json_optimization_encode. |
| 35 | + * to_do: research other options for json_encode optimization. |
| 36 | + */ |
| 37 | + public static function encode(mixed $value, int $flags = 0, int $depth = 512): string|false |
| 38 | + { |
| 39 | + if (self::$useSimdjsonEncode) { |
| 40 | + try { |
| 41 | + return simdjson_encode($value, $flags, $depth); |
| 42 | + } catch (\Throwable $e) { |
| 43 | + Log::warning("simdjson_encode failed: {$e->getMessage()}"); |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + return json_encode($value, $flags, $depth); |
| 48 | + } |
| 49 | +} |
0 commit comments