Skip to content

Commit

Permalink
cleaning up
Browse files Browse the repository at this point in the history
  • Loading branch information
taylorotwell committed Feb 10, 2017
1 parent e89a30d commit 11e89f3
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 7 deletions.
25 changes: 21 additions & 4 deletions src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php
Expand Up @@ -527,10 +527,7 @@ public function setAttribute($key, $value)
}

if ($this->isJsonCastable($key) && ! is_null($value)) {
$value = $this->asJson($value);
if (false === $value) {
throw JsonEncodingException::forAttribute($key, json_last_error_msg());
}
$value = $this->castAttributeAsJson($key, $value);
}

// If this attribute contains a JSON ->, we'll set the proper value in the
Expand Down Expand Up @@ -613,6 +610,26 @@ protected function getArrayAttributeByKey($key)
$this->fromJson($this->attributes[$key]) : [];
}

/**
* Cast the given attribute to JSON.
*
* @param string $key
* @param mixed $value
* @return string
*/
protected function castAttributeAsJson($key, $value)
{
$value = $this->asJson($value);

if ($value === false) {
throw JsonEncodingException::forAttribute(
$this, $key, json_last_error_msg()
);
}

return $value;
}

/**
* Encode the given value as JSON.
*
Expand Down
7 changes: 5 additions & 2 deletions src/Illuminate/Database/Eloquent/JsonEncodingException.php
Expand Up @@ -21,12 +21,15 @@ public static function forModel($model, $message)
/**
* Create a new JSON encoding exception for an attribute.
*
* @param mixed $model
* @param mixed $key
* @param string $message
* @return static
*/
public static function forAttribute($key, $message)
public static function forAttribute($model, $key, $message)
{
return new static('Error encoding value of attribute ['.$key.'] to JSON: '.$message);
$class = get_class($model);

return new static("Unable to encode attribute [{$key}] for model [{$class}] to JSON: {$message}.");
}
}
1 change: 0 additions & 1 deletion tests/Database/DatabaseEloquentModelTest.php
Expand Up @@ -1468,7 +1468,6 @@ public function testModelAttributeCastingPreservesNull()

/**
* @expectedException \Illuminate\Database\Eloquent\JsonEncodingException
* @expectedExceptionMessage Error encoding value of attribute
*/
public function testModelAttributeCastingFailsOnUnencodableData()
{
Expand Down

0 comments on commit 11e89f3

Please sign in to comment.