master

laravel/framework

Last updated at: 29/12/2023 09:22

AsEncryptedArrayObject.php

TLDR

This file defines the AsEncryptedArrayObject class, which implements the Castable interface. The class is used to cast encrypted array objects when working with the Eloquent ORM.

Methods

castUsing(array $arguments)

This method is static and returns an anonymous class that implements the CastsAttributes interface. It is responsible for decrypting and encrypting the array object when reading and writing values from and to the database.

Classes

AsEncryptedArrayObject

This class implements the Castable interface and provides the functionality to cast encrypted array objects. It uses the castUsing method to define the logic for decrypting and encrypting the array object.

<?php

namespace Illuminate\Database\Eloquent\Casts;

use Illuminate\Contracts\Database\Eloquent\Castable;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Support\Facades\Crypt;

class AsEncryptedArrayObject 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\Database\Eloquent\Casts\ArrayObject<array-key, mixed>, iterable>
     */
    public static function castUsing(array $arguments)
    {
        return new class implements CastsAttributes
        {
            public function get($model, $key, $value, $attributes)
            {
                if (isset($attributes[$key])) {
                    return new ArrayObject(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;
            }

            public function serialize($model, string $key, $value, array $attributes)
            {
                return ! is_null($value) ? $value->getArrayCopy() : null;
            }
        };
    }
}