summaryrefslogtreecommitdiffstats
path: root/vendor/gipfl/json/src/JsonString.php
diff options
context:
space:
mode:
authorDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-14 13:23:16 +0000
committerDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-14 13:23:16 +0000
commit3e97c51418e6d27e9a81906f347fcb7c78e27d4f (patch)
treeee596ce1bc9840661386f96f9b8d1f919a106317 /vendor/gipfl/json/src/JsonString.php
parentInitial commit. (diff)
downloadicingaweb2-module-incubator-3e97c51418e6d27e9a81906f347fcb7c78e27d4f.tar.xz
icingaweb2-module-incubator-3e97c51418e6d27e9a81906f347fcb7c78e27d4f.zip
Adding upstream version 0.20.0.upstream/0.20.0
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'vendor/gipfl/json/src/JsonString.php')
-rw-r--r--vendor/gipfl/json/src/JsonString.php68
1 files changed, 68 insertions, 0 deletions
diff --git a/vendor/gipfl/json/src/JsonString.php b/vendor/gipfl/json/src/JsonString.php
new file mode 100644
index 0000000..b9e22b6
--- /dev/null
+++ b/vendor/gipfl/json/src/JsonString.php
@@ -0,0 +1,68 @@
+<?php
+
+namespace gipfl\Json;
+
+use function json_decode;
+use function json_encode;
+use function json_last_error;
+
+class JsonString
+{
+ const DEFAULT_FLAGS = JSON_PRESERVE_ZERO_FRACTION | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE;
+
+ /**
+ * Encode with well-known flags, as we require the result to be reproducible
+ *
+ * @param $mixed
+ * @param int|null $flags
+ * @return string
+ * @throws JsonEncodeException
+ */
+ public static function encode($mixed, $flags = null)
+ {
+ if ($flags === null) {
+ $flags = self::DEFAULT_FLAGS;
+ } else {
+ $flags = self::DEFAULT_FLAGS | $flags;
+ }
+ $result = json_encode($mixed, $flags);
+
+ if ($result === false && json_last_error() !== JSON_ERROR_NONE) {
+ throw JsonEncodeException::forLastJsonError();
+ }
+
+ return $result;
+ }
+
+ /**
+ * Decode the given JSON string and make sure we get a meaningful Exception
+ *
+ * @param string $string
+ * @return mixed
+ * @throws JsonDecodeException
+ */
+ public static function decode($string)
+ {
+ $result = json_decode($string);
+
+ if ($result === null && json_last_error() !== JSON_ERROR_NONE) {
+ throw JsonDecodeException::forLastJsonError();
+ }
+
+ return $result;
+ }
+
+ /**
+ * @param $string
+ * @return ?string
+ * @throws JsonDecodeException
+ */
+ public static function decodeOptional($string)
+ {
+ if ($string === null) {
+ return null;
+ }
+
+ return static::decode($string);
+ }
+}