riimu / kit-phpencoder
Highly customizable alternative to var_export for PHP code generation
Installs: 5 806 010
Dependents: 36
Suggesters: 0
Security: 0
Stars: 71
Watchers: 7
Forks: 4
Open Issues: 2
Requires
- php: >=5.6.0
README
PHPEncoder is a PHP library for exporting variables and generating PHP code
representations for said variables similar to the built in function
var_export()
. Compared to the built in function, however, this library
provides more options to customize the output, which makes it easier to generate
code for different kinds of purposes such as readable configuration files or
optimized cache files.
The purpose of this library is to address some of the shortcomings with the
built in var_export()
. For example, there is no way to control the amount of
whitespace in the output and there is no way to choose between different array
notations. This library also provides functionality to convert objects into PHP
code that is actually useful when compared to the built in function.
The large number of customization options in this library allows you to create code that fits your purposes. You can create very compact code, when you need to limit the size of the output, or you can create code in the style that actually fits in any of your dynamically generated PHP files.
The API documentation is available at: http://kit.riimu.net/api/phpencoder/
Requirements
- The minimum supported PHP version is 5.6
Installation
Installation with Composer
The easiest way to install this library is to use Composer to handle your dependencies. In order to install this library via Composer, simply follow these two steps:
-
Acquire the
composer.phar
by running the Composer Command-line installation in your project root. -
Once you have run the installation script, you should have the
composer.phar
file in you project root and you can run the following command:php composer.phar require "riimu/kit-phpencoder:^2.3"
After installing this library via Composer, you can load the library by
including the vendor/autoload.php
file that was generated by Composer during
the installation.
Adding the library as a dependency
If you are already familiar with how to use Composer, you may alternatively add
the library as a dependency by adding the following composer.json
file to your
project and running the composer install
command:
{ "require": { "riimu/kit-phpencoder": "^2.3" } }
Manual installation
If you do not wish to use Composer to load the library, you may also download
the library manually by downloading the latest release
and extracting the src
folder to your project. You may then include the
provided src/autoload.php
file to load the library classes.
Usage
The most relevant method provided by this library is the encode()
method
provided by PHPEncoder
. The method takes any value as an argument and returns
the PHP code representation for that value.
For example:
<?php require 'vendor/autoload.php'; $encoder = new \Riimu\Kit\PHPEncoder\PHPEncoder(); echo $encoder->encode(['foo' => 'bar', [1, true, false, null, 1.0]]);
This would create the following output:
[
'foo' => 'bar',
[1, true, false, null, 1.0],
]
Of course, the most important feature of this library is the ability to
customize the created the PHP code. As the second argument, the encode()
method takes an array of options, which can be used to customize the returned
PHP code. For example:
<?php require 'vendor/autoload.php'; $encoder = new \Riimu\Kit\PHPEncoder\PHPEncoder(); echo $encoder->encode(['foo' => 'bar', [1, true, false, null, 1.0]], [ 'array.inline' => false, 'array.omit' => false, 'array.indent' => 2, 'boolean.capitalize' => true, 'null.capitalize' => true, ]);
This would create the following output:
[
'foo' => 'bar',
0 => [
0 => 1,
1 => TRUE,
2 => FALSE,
3 => NULL,
4 => 1.0,
],
]
Options
Encoding options allow you to customize the output of the encode()
method. It
is possible to set these options in three different ways:
- Options can be provided as an array to the
PHPEncoder
constructor. - Option values can be set via the
setOption()
method. - Options can be passed as an array as the second argument to the
encode()
method.
Note that options passed to the encode()
method are only temporary and do not
apply to following calls.
List of Options
-
whitespace : <boolean> (true)
When set tofalse
, generation of all extra whitespace is disabled and all other settings that affect whitespace are ignored. -
hex.capitalize : <boolean> (false)
When set totrue
all hexadecimal characters in the output are written using upper case instead of lower case. -
null.capitalize : <boolean> (false)
When set totrue
, allnull
values are written in upper case instead of lower case. -
boolean.capitalize : <boolean> (false)
When set totrue
, alltrue
andfalse
values are written in upper case instead of lower case. -
integer.type : <"binary"|"octal"|"decimal"|"hexadecimal"> ("decimal")
Change the output syntax of integers. For example, using the type"hexadecimal"
would output the number15
as0xf
. -
float.integers : <boolean|"all"> (false)
When set totrue
, any float that represents an integer and has a value that is accurately represented by the floating point number will be encoded as an integer instead of a float. (e.g. the value2.0
will be encoded as2
). To include the values that are not accurately represented, you may set option to"all"
. -
float.export : <boolean> (false)
When set totrue
floats are encoded usingvar_export()
, which causes a slightly different output on non integer floating point numbers compared to the standard implemented method. In some cases, this may produce more accurate numbers but with less cleaner representation. -
float.precision : <integer|false> (17)
The maximum precision of encoded floating point values, which usually also means the maximum number of digits in encoded floats. If the value is set tofalse
, the PHP ini settingserialize_precision
will be used instead. Note that due to the way floating point values work, a value greater than 17 does not provide any additional precision. -
string.binary : <boolean> (false)
When set totrue
any string that is not valid UTF-8 will be encoded in base 64 and wrapped withbase64_decode()
call. -
string.escape : <boolean> (true)
When set totrue
, all strings containing bytes outside the 32-126 ASCII range will be written with double quotes and the characters outside the range will be escaped. -
string.utf8 : <boolean> (false)
When both this option andstring.escape
are set totrue
, all valid multibyte UTF-8 characters in strings are encoded using the PHP7 unicode code point syntax. Note that this syntax does not work in PHP versions earlier than 7.0. -
string.classes : <string[]> ([])
Defines a list of classes or class namespace prefixes for classes that can be encoded using the class resolution operator::class
when encountered in strings. e.g. providing the value['Riimu\\']
would encode all strings that look like class names in theRiimu
namespace likeRiimu\Kit\PHPEncoder::class
. -
string.imports : <string[]> ([])
List of imports used in the resulting code file, which allows class names to be written using shorter format. The list should be an associative array with the namespace or class as the key and the used name as the value. Use empty string to indicate the current namespace.For example, if the resulting file would have
namespace Riimu\Kit\PHPEncoder;
anduse PHPUnit\Framework\TestCase;
, you could set up the array as['Riimu\\Kit\\PHPEncoder\\' => '', 'PHPUnit\\Framework\\TestCase' => 'TestCase']
-
array.short : <boolean> (true)
When set totrue
, arrays are enclosed using square brackets[]
instead using of the long array notationarray()
. -
array.base : <integer|string> (0)
Base indentation for arrays as a number of spaces or as a string. Provides convenience when you need to output code to a file with specific level of indentation. -
array.indent : <integer|string> (4)
Amount of indentation for single level of indentation as a number of spaces or a string. -
array.align : <boolean> (false)
When set totrue
, array assignment operators=>
are aligned to the same column using spaces. Even if enabled,array.omit
andarray.inline
options are still respected, but only if all the keys in the specific array can be omitted. -
array.inline : <boolean|integer> (70)
When set totrue
, any array that can be written without any array keys will be written in a single line. If an integer is provided instead, the array will be written as a single line only if it does not exceed that number of characters. This option has no effect whenarray.omit
is set to false. -
array.omit : <boolean> (true)
When set totrue
, any redundant array keys will not be included (e.g. the array[0 => 'a', 1 => 'b']
would be encoded just as['a', 'b']
). -
array.eol : <string|false> (false)
The end of line character used by array output. When set tofalse
, the defaultPHP_EOL
will be used instead. -
object.method : <boolean> (true)
When set totrue
, any encoded object will be checked for methodstoPHP()
andtoPHPValue()
. If the methodtoPHP()
exists, the returned string will be used as the PHP code representation of the object. If the methodtoPHPValue()
exists instead, the returned value will be encoded as PHP and used as the code representation of the object. -
object.format : <string> ('vars')
Default object encoding format. The possible values are:string
casts the object to string and then encodes that string as PHP.serialize
serializes the object and wraps it withunserialize()
export
mimics thevar_export()
object representationarray
casts the object to an array and encodes that arrayvars
turns object into an array usingget_object_vars()
iterate
turns the object into an array by iterating over it withforeach
-
object.cast : <boolean> (true)
Whether to add an(object)
cast in front of arrays generated from objects or not when using the object encoding formatsvars
,array
oriterate
. -
recursion.detect : <boolean> (true)
When set totrue
, the encoder will attempt to detect circular references in arrays and objects to avoid infinite loops. -
recursion.ignore : <boolean> (false)
When set totrue
, any circular reference will be replaced withnull
instead of throwing an exception. -
recursion.max : <integer|false> (false)
Maximum number of levels when encoding arrays and objects. Exception is thrown when the maximum is exceeded. Set tofalse
to have no limit.
Credits
This library is Copyright (c) 2013-2022 Riikka Kalliomäki.
See LICENSE for license and copying information.