Skip to content

Commit

Permalink
refactoring the json model helper
Browse files Browse the repository at this point in the history
  • Loading branch information
jturbide committed Feb 29, 2024
1 parent ab78b80 commit 60f6c16
Showing 1 changed file with 25 additions and 8 deletions.
33 changes: 25 additions & 8 deletions src/Mvc/Model/Json.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,20 +14,37 @@
trait Json
{
/**
* JSON Encode or fallback to value
* @see json_encode
* Encodes a value to JSON.
*
* @param mixed $value The value to be encoded.
* @param int $flags [Optional] Bitmask of JSON encode options.
* Defaults to JSON_UNESCAPED_SLASHES.
* @param int $depth [Optional] The maximum depth of recursion when encoding nested objects.
* Defaults to 512.
*
* @return string|false The JSON encoded string on success, or `false` on failure.
*/
public function jsonEncode($value, int $flags = JSON_UNESCAPED_SLASHES, int $depth = 512)
public function jsonEncode(mixed $value, int $flags = JSON_UNESCAPED_SLASHES, int $depth = 512): string|false
{
return json_encode($value, $flags, $depth) ?: $value;
return json_encode($value, $flags, $depth);
}

/**
* JSON Decode or fallback to value
* @see json_decode
* Decodes a JSON string.
*
* @param string $json The JSON string to be decoded.
* @param bool|null $associative [Optional] When `true`, returned objects will be converted into associative arrays.
* When `false`, objects will be returned as generic objects. If `null`, objects
* will be returned based on the JSON_NUMERIC_CHECK flag.
* @param int $depth [Optional] The maximum depth of recursion when decoding nested objects.
* Defaults to 512.
* @param int $flags [Optional] Bitmask of JSON decode options.
* Defaults to 0.
*
* @return mixed The decoded value on success, or the original JSON string on failure.
*/
public function jsonDecode(string $json, ?bool $associative = null, int $depth = 512, int $flags = 0)
public function jsonDecode(string $json, ?bool $associative = null, int $depth = 512, int $flags = 0): mixed
{
return json_decode($json, $associative, $depth, $flags) ?: $json;
return json_decode($json, $associative, $depth, $flags);
}
}

0 comments on commit 60f6c16

Please sign in to comment.