Skip to content

Commit

Permalink
fix: prevent casting empty string to array from triggering json error (
Browse files Browse the repository at this point in the history
  • Loading branch information
calebdw authored Aug 7, 2024
1 parent 763b942 commit 0138d78
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php
Original file line number Diff line number Diff line change
Expand Up @@ -1271,7 +1271,11 @@ protected function asJson($value)
*/
public function fromJson($value, $asObject = false)
{
return Json::decode($value ?? '', ! $asObject);
if ($value === null || $value === '') {
return null;
}

return Json::decode($value, ! $asObject);
}

/**
Expand Down
28 changes: 28 additions & 0 deletions tests/Database/DatabaseConcernsHasAttributesTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,14 @@ public function testWithConstructorArguments()
$attributes = $instance->getMutatedAttributes();
$this->assertEquals(['some_attribute'], $attributes);
}

public function testCastingEmptyStringToArrayDoesNotError()
{
$instance = new HasAttributesWithArrayCast();
$this->assertEquals(['foo' => null], $instance->attributesToArray());

$this->assertTrue(json_last_error() === JSON_ERROR_NONE);
}
}

class HasAttributesWithoutConstructor
Expand All @@ -40,3 +48,23 @@ public function __construct($someValue)
{
}
}

class HasAttributesWithArrayCast
{
use HasAttributes;

public function getArrayableAttributes(): array
{
return ['foo' => ''];
}

public function getCasts(): array
{
return ['foo' => 'array'];
}

public function usesTimestamps(): bool
{
return false;
}
}

0 comments on commit 0138d78

Please sign in to comment.