master

laravel/framework

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

AsStringable.php

TLDR

This file defines the AsStringable class, which is a castable class for Eloquent models in Laravel. The class allows for the casting of model attributes to Stringable objects, which provides additional functionality for manipulating strings.

Methods

There are no additional methods in this file.

Classes

AsStringable

The AsStringable class is a castable class that implements the Castable interface. This class is used for casting Eloquent model attributes to Stringable objects, which allows for convenient string manipulation. The class contains a static castUsing method that returns an anonymous class implementing the CastsAttributes interface. This anonymous class contains the get and set methods, which are responsible for retrieving and setting the casted attribute value respectively. When getting a value, the get method returns a Stringable object created from the attribute value. When setting a value, the set method converts the value to a string if it is not null. Otherwise, it returns null.

<?php

namespace Illuminate\Database\Eloquent\Casts;

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

class AsStringable 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\Stringable, string|\Stringable>
     */
    public static function castUsing(array $arguments)
    {
        return new class implements CastsAttributes
        {
            public function get($model, $key, $value, $attributes)
            {
                return isset($value) ? Str::of($value) : null;
            }

            public function set($model, $key, $value, $attributes)
            {
                return isset($value) ? (string) $value : null;
            }
        };
    }
}