Oihana PHP

AlterJSONStringifyPropertyTrait

Encodes a property value into its JSON string representation.

This alteration is declared with the Alter::JSON_STRINGIFY type. It is the counterpart of AlterJSONParsePropertyTrait and is used in property transformation pipelines to serialize an array or object into a JSON string before it is persisted or sent over the wire:

Property::METADATA => Alter::JSON_STRINGIFY ,

The extra elements of the alter definition are forwarded as the remaining arguments of json_encode() (flags, depth), allowing options such as JSON_PRETTY_PRINT or JSON_UNESCAPED_UNICODE to be configured per property.

The $modified flag is always set to true since the encoding pass is unconditional.

Tags
author

Marc Alcaraz (ekameleon)

since
1.0.0

Table of Contents

Methods

alterJsonStringifyProperty()  : string|null|false
Encodes a value into its JSON string representation.

Methods

alterJsonStringifyProperty()

Encodes a value into its JSON string representation.

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

The value is always passed to json_encode(); the optional $definition entries are forwarded as the following arguments (flags, depth). A false result from json_encode() is normalized to null.

Parameters
$value : mixed

The value to encode (array, object, scalar, etc.).

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

Extra arguments forwarded to json_encode(): [ flags , depth ] (e.g. JSON_PRETTY_PRINT). Empty by default.

$modified : bool = false

Reference flag; always set to true.

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

class Record
{
    use AlterJSONStringifyPropertyTrait;
}

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

$json = $record->alterJsonStringifyProperty( [ 'a' => 1 , 'b' => 2 ] , [] , $modified );
// $json     === '{"a":1,"b":2}'
// $modified === true

// With pretty-print flag
$pretty = $record->alterJsonStringifyProperty( [ 'a' => 1 ] , [ JSON_PRETTY_PRINT ] , $modified );
// $pretty === "{\n    \"a\": 1\n}"
Return values
string|null|false

The JSON string, or null when encoding fails.

On this page

Search results