Skip to content

Commit

Permalink
Small but useful. Entity class. codeigniter4#1176
Browse files Browse the repository at this point in the history
I've changed name which i proposed before (json-object -> json) cuz I use default parameter for json_decode($value, [$assoc = false]) in calling.
  • Loading branch information
nowackipawel authored Aug 30, 2018
1 parent 85588b1 commit 5451c1a
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions system/Entity.php
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,14 @@ public function __set(string $key, $value = null)
$value = serialize($value);
}

// JSON casting requires that we JSONize the value
// when setting it so that it can easily be stored
// back to the database.
if (function_exists('json_encode') && array_key_exists($key, $this->_options['casts']) && ($this->_options['casts'][$key] === 'json' || $this->_options['casts'][$key] === 'json-array'))
{
$value = json_encode($value);
}

// if a set* method exists for this key,

// use that method to insert this value.

$method = 'set' . str_replace(' ', '', ucwords(str_replace(['-', '_'], ' ', $key)));
Expand Down Expand Up @@ -388,6 +396,22 @@ protected function castAs($value, string $type)
$value = unserialize($value);
}

$value = (array)$value;
break;
case 'json':
if (function_exists('json_decode') && is_string($value) && (strpos($value, '[') === 0 || strpos($value, '{') === 0))
{
$value = json_decode($value, false);
}

$value = (object)$value;
break;
case 'json-array':
if (function_exists('json_decode') && is_string($value) && (strpos($value, '[') === 0 || strpos($value, '{') === 0))
{
$value = json_decode($value, true);
}

$value = (array)$value;
break;
case 'datetime':
Expand Down

0 comments on commit 5451c1a

Please sign in to comment.