Skip to content

Commit

Permalink
Allow casting from an array to a collection.
Browse files Browse the repository at this point in the history
  • Loading branch information
nickescobedo committed Oct 5, 2024
1 parent eacb2cf commit c7d73f8
Show file tree
Hide file tree
Showing 4 changed files with 11 additions and 0 deletions.
3 changes: 3 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@
"scripts": {
"lint": [
"@php vendor/bin/phpstan analyse"
],
"test": [
"@php vendor/bin/phpunit"
]
}
}
4 changes: 4 additions & 0 deletions src/CastRequestAttributes.php
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,10 @@ protected function castAttribute($key, $value)
case 'json':
return $this->fromJson($value);
case 'collection':
if (is_array($value)) {
return new BaseCollection($value);
}

return new BaseCollection($this->fromJson($value));
case 'date':
return $this->asDate($value);
Expand Down
2 changes: 2 additions & 0 deletions tests/CastTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ public function testRequestCastsNameToIntToString(): void
'toJson' => '{"key":"value"}',

'toCollection' => '[1,2,3]',
'toCollection2' => [1, 2, 3],

'toDate' => '2021-01-01',

Expand Down Expand Up @@ -83,6 +84,7 @@ public function testRequestCastsNameToIntToString(): void

$this->assertInstanceOf(Collection::class, $request->castedInput('toCollection'));
$this->assertSame([1, 2, 3], $request->castedInput('toCollection')->all());
$this->assertSame([1, 2, 3], $request->castedInput('toCollection2')->all());

$this->assertInstanceOf(Carbon::class, $request->castedInput('toDate'));

Expand Down
2 changes: 2 additions & 0 deletions tests/SupportFiles/Cast.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ public function rules(): array
'toJson' => 'string',

'toCollection' => 'string',
'toCollection2' => 'array',

'toDate' => 'date',

Expand Down Expand Up @@ -75,6 +76,7 @@ public function casts()
'toJson' => 'json',

'toCollection' => 'collection',
'toCollection2' => 'collection',

'toDate' => 'date',

Expand Down

0 comments on commit c7d73f8

Please sign in to comment.