class PHPEncoder (View source)

A highly customisable library for generating PHP code from variables.

PHPEncoder provides a functionality similar to var_export(), but allows more customisation and wider range of features. Better customisation options make it easier to generate static PHP files when you need the file to formatted in specific way.

Methods

__construct(array $options = [], array $encoders = null)

Creates a new PHPEncoder instance.

addEncoder(Encoder $encoder, bool $prepend = false)

Adds a new encoder.

setOption(string $option, mixed $value)

Sets the value for an encoder option.

string
encode(mixed $variable, array $options = [])

Generates the PHP code for the given value.

array
getAllOptions(array $overrides = [])

Returns a list of all encoder options.

Details

__construct(array $options = [], array $encoders = null)

Creates a new PHPEncoder instance.

The constructor allows you to provide the list of default encoding options used by the encoder. Note that if you are using custom value encoders, you must provide them in the constructor if you are providing options for them or otherwise the options will be considered invalid.

Using the second parameter you can also provide a list of value encoders used by the encoder. If null is provided, the list of default value encoders will be used instead.

Parameters

array $options List of encoder options
array $encoders List of encoders to use or null for defaults

Exceptions

InvalidOptionException If any of the encoder options are invalid

addEncoder(Encoder $encoder, bool $prepend = false)

Adds a new encoder.

Values are always encoded by the first encoder that supports encoding that type of value. By setting the second optional parameter to true, you can prepend the encoder to the list to ensure that it will be tested first.

Parameters

Encoder $encoder Encoder for encoding values
bool $prepend True to prepend the encoder to the list, false to add it as last

setOption(string $option, mixed $value)

Sets the value for an encoder option.

Parameters

string $option Name of the option
mixed $value Value for the option

Exceptions

InvalidOptionException If the provided encoder option is invalid

string encode(mixed $variable, array $options = [])

Generates the PHP code for the given value.

Parameters

mixed $variable Value to encode as PHP
array $options List of encoder options

Return Value

string The PHP code that represents the given value

Exceptions

InvalidOptionException If any of the encoder options are invalid
InvalidArgumentException If the provided value contains an unsupported value type
RuntimeException If max depth is reached or a recursive value is detected

array getAllOptions(array $overrides = [])

Returns a list of all encoder options.

Parameters

array $overrides Options to override in the returned array

Return Value

array List of encoder options

Exceptions

InvalidOptionException If any of the encoder option overrides are invalid