AsEncryptedCollection.php
TLDR
This file (AsEncryptedCollection.php
) contains the implementation of the AsEncryptedCollection
class, which is a castable class for encrypting and decrypting collections in Laravel Eloquent.
Methods
No methods are defined in this file.
Classes
AsEncryptedCollection
This class is used for casting collections to an encrypted format and vice versa in Laravel Eloquent. It implements the Castable
interface. The class has two methods:
-
castUsing(array $arguments)
: This method returns an anonymous class that implements theCastsAttributes
interface. It takes an array of arguments and checks if the provided class extends theIlluminate\Support\Collection
class. If it does, it decrypts the encrypted collection value and returns a new instance of the collection. If the collection value is not set, it returns null. If the provided class does not extend theIlluminate\Support\Collection
class, anInvalidArgumentException
is thrown. -
using(string $class)
: This static method returns a string representation of the cast, indicating that the cast uses theAsEncryptedCollection
class and the specified collection class.
<?php
namespace Illuminate\Database\Eloquent\Casts;
use Illuminate\Contracts\Database\Eloquent\Castable;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Crypt;
use InvalidArgumentException;
class AsEncryptedCollection implements Castable
{
/**
* Get the caster class to use when casting from / to this cast target.
*
* @param array $arguments
* @return \Illuminate\Contracts\Database\Eloquent\CastsAttributes<\Illuminate\Support\Collection<array-key, mixed>, iterable>
*/
public static function castUsing(array $arguments)
{
return new class($arguments) implements CastsAttributes
{
public function __construct(protected array $arguments)
{
}
public function get($model, $key, $value, $attributes)
{
$collectionClass = $this->arguments[0] ?? Collection::class;
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])));
}
return null;
}
public function set($model, $key, $value, $attributes)
{
if (! is_null($value)) {
return [$key => Crypt::encryptString(Json::encode($value))];
}
return null;
}
};
}
/**
* Specify the collection for the cast.
*
* @param class-string $class
* @return string
*/
public static function using($class)
{
return static::class.':'.$class;
}
}