Skip to content

Commit

Permalink
Merge pull request #1622 from nowackipawel/patch-29
Browse files Browse the repository at this point in the history
Nullable support for __set.
  • Loading branch information
lonnieezell authored Jan 10, 2019
2 parents 2478a1f + 843cc9e commit 3003609
Showing 1 changed file with 25 additions and 10 deletions.
35 changes: 25 additions & 10 deletions system/Entity.php
Original file line number Diff line number Diff line change
Expand Up @@ -267,24 +267,38 @@ public function __set(string $key, $value = null)
$value = $this->mutateDate($value);
}

// Array casting requires that we serialize the value
// when setting it so that it can easily be stored
// back to the database.
if (array_key_exists($key, $this->_options['casts']) && $this->_options['casts'][$key] === 'array')
$isNullable = false;
$castTo = false;

if(array_key_exists($key, $this->_options['casts']))
{
$value = serialize($value);
$isNullable = substr($this->_options['casts'][$key],0,1) === '?';
$castTo = $isNullable ? substr($this->_options['casts'][$key], 1) : $this->_options['casts'][$key];
}

// 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'))
if(!$isNullable || !is_null($value))
{
$value = json_encode($value);
// Array casting requires that we serialize the value
// when setting it so that it can easily be stored
// back to the database.
if ($castTo === 'array')
{
$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 (($castTo === 'json' || $castTo === 'json-array') && function_exists('json_encode'))
{
$value = json_encode($value);
}

}

// if a set* method exists for this key,
// use that method to insert this value.
// *) should be outside $isNullable check - SO maybe wants to do sth with null value automatically
$method = 'set' . str_replace(' ', '', ucwords(str_replace(['-', '_'], ' ', $key)));
if (method_exists($this, $method))
{
Expand All @@ -304,6 +318,7 @@ public function __set(string $key, $value = null)
return $this;
}


//--------------------------------------------------------------------

/**
Expand Down

0 comments on commit 3003609

Please sign in to comment.