Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

enclose return of getRawSchemaLessAttributes with is_array check #46

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion src/SchemalessAttributes.php
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,12 @@ public static function scopeWithSchemalessAttributes(string $attributeName): Bui

protected function getRawSchemalessAttributes(): array
{
return json_decode($this->model->getAttributes()[$this->sourceAttributeName] ?? '{}', true);
$decoded = json_decode($this->model->getAttributes()[$this->sourceAttributeName] ?? '{}', true);

if (! is_array($decoded)) {
return [];
}

return $decoded;
}
}
10 changes: 10 additions & 0 deletions tests/HasSchemalessAttributesTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -328,6 +328,16 @@ public function if_an_iterable_is_passed_to_set_it_will_defer_to_setMany()
$this->assertEquals('subVal1', $this->testModel->schemaless_attributes->arr['subKey1']);
}

/** @test */
public function if_database_column_does_not_contain_json_decodable_string_it_returns_empty_array()
{
$model = TestModel::create(['schemaless_attributes' => 'null']);

$this->assertEquals('"null"', $model->getAttributes()['schemaless_attributes']);
$this->assertIsNotArray(json_decode($model->getAttributes()['schemaless_attributes'] ?? '{}', true));
$this->assertEquals([], $model->getSchemalessAttributesAttribute()->all());
}

protected function assertContainsModels(array $expectedModels, Collection $actualModels)
{
$assertionFailedMessage = 'Expected '.count($expectedModels).' models. Got '.$actualModels->count().' models';
Expand Down