Skip to content

Commit

Permalink
Support json string on cast setter
Browse files Browse the repository at this point in the history
  • Loading branch information
erikn69 committed Oct 28, 2021
1 parent 714224b commit 798097a
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
13 changes: 12 additions & 1 deletion src/Casts/SchemalessAttributes.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,17 @@ public function get($model, $key, $value, $attributes)
*/
public function set($model, $key, $value, $attributes)
{
return json_encode($value);
return $this->isJson($value) ? $value : json_encode($value);
}

/**
* Verify that a variable is a json string
*
* @param mixed $value
* @return bool
*/
function isJson($value): bool
{
return is_string($value) && str_starts_with($value, '{') && str_ends_with($value, '}');
}
}
21 changes: 21 additions & 0 deletions tests/HasSchemalessAttributesTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,14 @@ public function an_schemaless_attribute_can_be_set()
$this->assertEquals('value', $this->testModel->schemaless_attributes->name);
}

/** @test */
public function an_schemaless_attribute_can_be_set_from_json()
{
$this->testModel->schemaless_attributes = json_encode(['name' => 'value']);

$this->assertEquals('value', $this->testModel->schemaless_attributes->name);
}

/** @test */
public function it_can_determine_if_it_has_a_schemaless_attribute()
{
Expand Down Expand Up @@ -245,6 +253,19 @@ public function it_can_add_and_save_schemaless_attributes_in_one_go()
$this->assertEquals($array, $testModel->schemaless_attributes->all());
}

/** @test */
public function it_can_and_save_schemaless_attributes_from_json()
{
$array = [
'name' => 'value',
'name2' => 'value2',
];

$testModel = TestModel::create(['schemaless_attributes' => json_encode($array)]);

$this->assertEquals($array, $testModel->schemaless_attributes->all());
}

/** @test */
public function it_has_a_scope_to_get_models_with_the_given_schemaless_attributes()
{
Expand Down

0 comments on commit 798097a

Please sign in to comment.