Skip to content

Commit 33395e5

Browse files
authored
improvments
tl;dr; small improvements according to experience with using json, json-array casting in implementation of my cms formatting extract code for JSON casting (which was almost identical for "json" and "json-array") to castAsJson support for "string" and numeric casting: 0x322, 0272, 0b1010101, 1234e0, removing force casting to object as "json" (what was too much according to actual manual)
1 parent cdaffdd commit 33395e5

1 file changed

Lines changed: 32 additions & 21 deletions

File tree

system/Entity.php

Lines changed: 32 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -368,6 +368,7 @@ protected function mutateDate($value)
368368
*
369369
* @return mixed
370370
*/
371+
371372
protected function castAs($value, string $type)
372373
{
373374
switch($type)
@@ -398,29 +399,11 @@ protected function castAs($value, string $type)
398399

399400
$value = (array)$value;
400401
break;
401-
case 'json':
402-
if (function_exists('json_decode') && is_string($value) && (strpos($value, '[') === 0 || strpos($value, '{') === 0))
403-
{
404-
$value = json_decode($value, false);
405-
406-
if(json_last_error() !== JSON_ERROR_NONE)
407-
{
408-
throw CastException::forInvalidJsonFormatException(json_last_error());
409-
}
410-
}
411-
$value = (object)$value;
402+
case 'json':
403+
$value = $this->castAsJson($value, false);
412404
break;
413405
case 'json-array':
414-
if (function_exists('json_decode') && is_string($value) && (strpos($value, '[') === 0 || strpos($value, '{') === 0))
415-
{
416-
$value = json_decode($value, true);
417-
418-
if(json_last_error() !== JSON_ERROR_NONE)
419-
{
420-
throw CastException::forInvalidJsonFormatException(json_last_error());
421-
}
422-
}
423-
$value = (array)$value;
406+
$value = $this->castAsJson($value, true);
424407
break;
425408
case 'datetime':
426409
return new \DateTime($value);
@@ -432,4 +415,32 @@ protected function castAs($value, string $type)
432415

433416
return $value;
434417
}
418+
419+
//--------------------------------------------------------------------
420+
421+
/**
422+
* Cast as JSON
423+
*
424+
* @param mixed $value
425+
* @param bool $asArray
426+
*
427+
* @return mixed
428+
*/
429+
private function castAsJson($value, bool $asArray = false)
430+
{
431+
$tmp = !is_null($value) ? ($asArray ? [] : new \stdClass) : null;
432+
if(function_exists('json_decode'))
433+
{
434+
if((is_string($value) && (strpos($value, '[') === 0 || strpos($value, '{') === 0 || (strpos($value, '"') === 0 && strrpos($value, '"') === 0 ))) || is_numeric($value))
435+
{
436+
$tmp = json_decode($value, $asArray);
437+
438+
if(json_last_error() !== JSON_ERROR_NONE)
439+
{
440+
throw CastException::forInvalidJsonFormatException(json_last_error());
441+
}
442+
}
443+
}
444+
return $tmp;
445+
}
435446
}

0 commit comments

Comments
 (0)