Oihana PHP

AlterJSONParsePropertyTrait

Decodes a JSON string property into its native PHP representation.

This alteration is declared with the Alter::JSON_PARSE type. It is used in property transformation pipelines to turn a JSON-encoded string (often coming from a database column or an API payload) back into an object, array or scalar before the value is used:

Property::METADATA => Alter::JSON_PARSE ,

Only valid JSON strings are decoded (validated with json_validate()); any other value — including malformed JSON and non-string values — is returned unchanged. The extra elements of the alter definition are forwarded as the remaining arguments of json_decode() (associative, depth, flags), so the decoding mode is fully configurable.

The $modified flag is set to true only when an actual JSON decode is performed.

Tags
author

Marc Alcaraz (ekameleon)

since
1.0.0

Table of Contents

Methods

alterJsonParseProperty()  : mixed
Decodes a JSON-encoded string into its native PHP value.

Methods

alterJsonParseProperty()

Decodes a JSON-encoded string into its native PHP value.

public alterJsonParseProperty(mixed $value[, array<string|int, mixed> $definition = [] ][, bool &$modified = false ]) : mixed

The value is decoded only when it is a string that passes json_validate(); otherwise it is returned as-is. The optional $definition entries are passed straight to json_decode() after the value (associative, depth, flags).

Parameters
$value : mixed

The value to decode. Decoded only when it is a valid JSON string; any other value is returned unchanged.

$definition : array<string|int, mixed> = []

Extra arguments forwarded to json_decode(): [ associative , depth , flags ]. Defaults to standard json_decode() behavior (objects for JSON objects).

$modified : bool = false

Reference flag set to true when the value was decoded.

Tags
example
use oihana\models\traits\alters\AlterJSONParsePropertyTrait;

class Record
{
    use AlterJSONParsePropertyTrait;
}

$record   = new Record();
$modified = false;

// Decode to an associative array
$meta = $record->alterJsonParseProperty( '{"a":1,"b":2}' , [ true ] , $modified );
// $meta     === [ 'a' => 1 , 'b' => 2 ]
// $modified === true

// Non-JSON input is left untouched
$plain = $record->alterJsonParseProperty( 'hello' , [] , $modified );
// $plain === 'hello'
Return values
mixed

The decoded value (object, array, scalar or null), or the original value when it was not a valid JSON string.

On this page

Search results