master

laravel/framework

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

AsArrayObject.php

TLDR

This file defines the AsArrayObject class, which is a castable class for Laravel Eloquent. It allows for casting an attribute to an ArrayObject object when retrieving from the database and casting it back to a JSON string when storing it in the database.

Methods

There are no methods defined in this file.

Classes

AsArrayObject

The AsArrayObject class implements the Castable interface and serves as a castable class for Laravel Eloquent. It provides methods for casting the attribute to an ArrayObject object when retrieving from the database and casting it back to a JSON string when storing it in the database.

The AsArrayObject class has a single static method:

castUsing(array $arguments)

This static method returns an anonymous class that implements the CastsAttributes interface. This anonymous class provides the implementation for the get(), set(), and serialize() methods.

The get() method checks if the given attribute exists in the $attributes array. If it does, it decodes the JSON string and returns an ArrayObject object. If not, it returns null.

The set() method encodes the value as a JSON string and returns it in an array with the attribute name as the key.

The serialize() method returns the ArrayObject object's underlying array using the getArrayCopy() method.

<?php

namespace Illuminate\Database\Eloquent\Casts;

use Illuminate\Contracts\Database\Eloquent\Castable;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;

class AsArrayObject 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;
                }

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

                return is_array($data) ? new ArrayObject($data) : null;
            }

            public function set($model, $key, $value, $attributes)
            {
                return [$key => Json::encode($value)];
            }

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