Skip to content

[12.x] Extends AsCollection to map items into objects or other values #55383

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

Merged
Merged
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
44 changes: 39 additions & 5 deletions src/Illuminate/Database/Eloquent/Casts/AsCollection.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use Illuminate\Contracts\Database\Eloquent\Castable;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use InvalidArgumentException;

class AsCollection implements Castable
Expand All @@ -21,6 +22,7 @@ public static function castUsing(array $arguments)
{
public function __construct(protected array $arguments)
{
$this->arguments = array_pad(array_values($this->arguments), 2, '');
}

public function get($model, $key, $value, $attributes)
Expand All @@ -31,13 +33,29 @@ public function get($model, $key, $value, $attributes)

$data = Json::decode($attributes[$key]);

$collectionClass = $this->arguments[0] ?? Collection::class;
$collectionClass = empty($this->arguments[0]) ? Collection::class : $this->arguments[0];

if (! is_a($collectionClass, Collection::class, true)) {
throw new InvalidArgumentException('The provided class must extend ['.Collection::class.'].');
}

return is_array($data) ? new $collectionClass($data) : null;
if (! is_array($data)) {
return null;
}

$instance = new $collectionClass($data);

if (! isset($this->arguments[1]) || ! $this->arguments[1]) {
return $instance;
}

if (is_string($this->arguments[1])) {
$this->arguments[1] = Str::parseCallback($this->arguments[1]);
}

return is_callable($this->arguments[1])
? $instance->map($this->arguments[1])
: $instance->mapInto($this->arguments[1][0]);
}

public function set($model, $key, $value, $attributes)
Expand All @@ -48,13 +66,29 @@ public function set($model, $key, $value, $attributes)
}

/**
* Specify the collection for the cast.
* Specify the type of object each item in the collection should be mapped to.
*
* @param array{class-string, string}|class-string $map
* @return string
*/
public static function of($map)
{
return static::using('', $map);
}

/**
* Specify the collection type for the cast.
*
* @param class-string $class
* @param array{class-string, string}|class-string $map
* @return string
*/
public static function using($class)
public static function using($class, $map = null)
{
return static::class.':'.$class;
if (is_array($map) && is_callable($map)) {
$map = $map[0].'@'.$map[1];
}

return static::class.':'.implode(',', [$class, $map]);
}
}
42 changes: 36 additions & 6 deletions src/Illuminate/Database/Eloquent/Casts/AsEncryptedCollection.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Str;
use InvalidArgumentException;

class AsEncryptedCollection implements Castable
Expand All @@ -22,21 +23,34 @@ public static function castUsing(array $arguments)
{
public function __construct(protected array $arguments)
{
$this->arguments = array_pad(array_values($this->arguments), 2, '');
}

public function get($model, $key, $value, $attributes)
{
$collectionClass = $this->arguments[0] ?? Collection::class;
$collectionClass = empty($this->arguments[0]) ? Collection::class : $this->arguments[0];

if (! is_a($collectionClass, Collection::class, true)) {
throw new InvalidArgumentException('The provided class must extend ['.Collection::class.'].');
}

if (isset($attributes[$key])) {
return new $collectionClass(Json::decode(Crypt::decryptString($attributes[$key])));
if (! isset($attributes[$key])) {
return null;
}

return null;
$instance = new $collectionClass(Json::decode(Crypt::decryptString($attributes[$key])));

if (! isset($this->arguments[1]) || ! $this->arguments[1]) {
return $instance;
}

if (is_string($this->arguments[1])) {
$this->arguments[1] = Str::parseCallback($this->arguments[1]);
}

return is_callable($this->arguments[1])
? $instance->map($this->arguments[1])
: $instance->mapInto($this->arguments[1][0]);
}

public function set($model, $key, $value, $attributes)
Expand All @@ -50,14 +64,30 @@ public function set($model, $key, $value, $attributes)
};
}

/**
* Specify the type of object each item in the collection should be mapped to.
*
* @param array{class-string, string}|class-string $map
* @return string
*/
public static function of($map)
{
return static::using('', $map);
}

/**
* Specify the collection for the cast.
*
* @param class-string $class
* @param array{class-string, string}|class-string $map
* @return string
*/
public static function using($class)
public static function using($class, $map = null)
{
return static::class.':'.$class;
if (is_array($map) && is_callable($map)) {
$map = $map[0].'@'.$map[1];
}

return static::class.':'.implode(',', [$class, $map]);
}
}
76 changes: 76 additions & 0 deletions tests/Integration/Database/DatabaseCustomCastsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@
use Illuminate\Database\Eloquent\Casts\AsStringable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Fluent;
use Illuminate\Support\Stringable;

class DatabaseCustomCastsTest extends DatabaseTestCase
Expand Down Expand Up @@ -151,6 +153,68 @@ public function test_custom_casting_nullable_values()
$model->array_object_json->toArray()
);
}

public function test_as_collection_with_map_into()
{
$model = new TestEloquentModelWithCustomCasts();
$model->mergeCasts([
'collection' => AsCollection::of(Fluent::class),
]);

$model->setRawAttributes([
'collection' => json_encode([['foo' => 'bar']]),
]);

$this->assertInstanceOf(Fluent::class, $model->collection->first());
$this->assertSame('bar', $model->collection->first()->foo);
}

public function test_as_custom_collection_with_map_into()
{
$model = new TestEloquentModelWithCustomCasts();
$model->mergeCasts([
'collection' => AsCollection::using(CustomCollection::class, Fluent::class),
]);

$model->setRawAttributes([
'collection' => json_encode([['foo' => 'bar']]),
]);

$this->assertInstanceOf(CustomCollection::class, $model->collection);
$this->assertInstanceOf(Fluent::class, $model->collection->first());
$this->assertSame('bar', $model->collection->first()->foo);
}

public function test_as_collection_with_map_callback(): void
{
$model = new TestEloquentModelWithCustomCasts();
$model->mergeCasts([
'collection' => AsCollection::of([FluentWithCallback::class, 'make']),
]);

$model->setRawAttributes([
'collection' => json_encode([['foo' => 'bar']]),
]);

$this->assertInstanceOf(FluentWithCallback::class, $model->collection->first());
$this->assertSame('bar', $model->collection->first()->foo);
}

public function test_as_custom_collection_with_map_callback(): void
{
$model = new TestEloquentModelWithCustomCasts();
$model->mergeCasts([
'collection' => AsCollection::using(CustomCollection::class, [FluentWithCallback::class, 'make']),
]);

$model->setRawAttributes([
'collection' => json_encode([['foo' => 'bar']]),
]);

$this->assertInstanceOf(CustomCollection::class, $model->collection);
$this->assertInstanceOf(FluentWithCallback::class, $model->collection->first());
$this->assertSame('bar', $model->collection->first()->foo);
}
}

class TestEloquentModelWithCustomCasts extends Model
Expand Down Expand Up @@ -197,3 +261,15 @@ class TestEloquentModelWithCustomCastsNullable extends Model
'stringable' => AsStringable::class,
];
}

class FluentWithCallback extends Fluent
{
public static function make($attributes = [])
{
return new static($attributes);
}
}

class CustomCollection extends Collection
{
}
53 changes: 53 additions & 0 deletions tests/Integration/Database/EloquentModelEncryptedCastingTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Fluent;
use stdClass;

class EloquentModelEncryptedCastingTest extends DatabaseTestCase
Expand Down Expand Up @@ -231,6 +232,58 @@ public function testAsEncryptedCollection()
$this->assertNull($subject->fresh()->secret_collection);
}

public function testAsEncryptedCollectionMap()
{
$this->encrypter->expects('encryptString')
->twice()
->with('[{"key1":"value1"}]')
->andReturn('encrypted-secret-collection-string-1');
$this->encrypter->expects('encryptString')
->times(12)
->with('[{"key1":"value1"},{"key2":"value2"}]')
->andReturn('encrypted-secret-collection-string-2');
$this->encrypter->expects('decryptString')
->once()
->with('encrypted-secret-collection-string-2')
->andReturn('[{"key1":"value1"},{"key2":"value2"}]');

$subject = new EncryptedCast;

$subject->mergeCasts(['secret_collection' => AsEncryptedCollection::of(Fluent::class)]);

$subject->secret_collection = new Collection([new Fluent(['key1' => 'value1'])]);
$subject->secret_collection->push(new Fluent(['key2' => 'value2']));

$subject->save();

$this->assertInstanceOf(Collection::class, $subject->secret_collection);
$this->assertInstanceOf(Fluent::class, $subject->secret_collection->first());
$this->assertSame('value1', $subject->secret_collection->get(0)->key1);
$this->assertSame('value2', $subject->secret_collection->get(1)->key2);
$this->assertDatabaseHas('encrypted_casts', [
'id' => $subject->id,
'secret_collection' => 'encrypted-secret-collection-string-2',
]);

$subject = $subject->fresh();

$this->assertInstanceOf(Collection::class, $subject->secret_collection);
$this->assertInstanceOf(Fluent::class, $subject->secret_collection->first());
$this->assertSame('value1', $subject->secret_collection->get(0)->key1);
$this->assertSame('value2', $subject->secret_collection->get(1)->key2);

$subject->secret_collection = null;
$subject->save();

$this->assertNull($subject->secret_collection);
$this->assertDatabaseHas('encrypted_casts', [
'id' => $subject->id,
'secret_collection' => null,
]);

$this->assertNull($subject->fresh()->secret_collection);
}

public function testAsEncryptedArrayObject()
{
$this->encrypter->expects('encryptString')
Expand Down