master

laravel/framework

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

Json.php

TLDR

This file contains the Json class, which provides methods to encode and decode JSON values. It also allows users to set custom JSON encoders and decoders.

Methods

encode

This method encodes the given value into a JSON string. If a custom encoder is set, it uses that encoder; otherwise, it uses the built-in json_encode function.

decode

This method decodes the given JSON string into a PHP value. If a custom decoder is set, it uses that decoder; otherwise, it uses the built-in json_decode function. The second argument determines whether the decoded value should be converted into an associative array.

encodeUsing

This method sets a custom JSON encoder to be used by the encode method.

decodeUsing

This method sets a custom JSON decoder to be used by the decode method.

<?php

namespace Illuminate\Database\Eloquent\Casts;

class Json
{
    /**
     * The custom JSON encoder.
     *
     * @var callable|null
     */
    protected static $encoder;

    /**
     * The custom JSON decode.
     *
     * @var callable|null
     */
    protected static $decoder;

    /**
     * Encode the given value.
     */
    public static function encode(mixed $value): mixed
    {
        return isset(static::$encoder) ? (static::$encoder)($value) : json_encode($value);
    }

    /**
     * Decode the given value.
     */
    public static function decode(mixed $value, ?bool $associative = true): mixed
    {
        return isset(static::$decoder)
                ? (static::$decoder)($value, $associative)
                : json_decode($value, $associative);
    }

    /**
     * Encode all values using the given callable.
     */
    public static function encodeUsing(?callable $encoder): void
    {
        static::$encoder = $encoder;
    }

    /**
     * Decode all values using the given callable.
     */
    public static function decodeUsing(?callable $decoder): void
    {
        static::$decoder = $decoder;
    }
}