- Notifications
You must be signed in to change notification settings - Fork4
Highly customizable alternative to var_export for PHP code generation
License
Riimu/Kit-PHPEncoder
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
PHPEncoder is a PHP library for exporting variables and generating PHP coderepresentations for said variables similar to the built in functionvar_export(). Compared to the built in function, however, this libraryprovides more options to customize the output, which makes it easier to generatecode for different kinds of purposes such as readable configuration files oroptimized cache files.
The purpose of this library is to address some of the shortcomings with thebuilt invar_export(). For example, there is no way to control the amount ofwhitespace in the output and there is no way to choose between different arraynotations. This library also provides functionality to convert objects into PHPcode that is actually useful when compared to the built in function.
The large number of customization options in this library allows you to createcode that fits your purposes. You can create very compact code, when you need tolimit the size of the output, or you can create code in the style that actuallyfits in any of your dynamically generated PHP files.
The API documentation is available at:http://kit.riimu.net/api/phpencoder/
- The minimum supported PHP version is 5.6
The easiest way to install this library is to use Composer to handle yourdependencies. In order to install this library via Composer, simply followthese two steps:
Acquire the
composer.pharby running the ComposerCommand-line installationin your project root.Once you have run the installation script, you should have the
composer.pharfile 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 byincluding thevendor/autoload.php file that was generated by Composer duringthe installation.
If you are already familiar with how to use Composer, you may alternatively addthe library as a dependency by adding the followingcomposer.json file to yourproject and running thecomposer install command:
{"require": {"riimu/kit-phpencoder":"^2.3" }}If you do not wish to use Composer to load the library, you may also downloadthe library manually by downloading thelatest releaseand extracting thesrc folder to your project. You may then include theprovidedsrc/autoload.php file to load the library classes.
The most relevant method provided by this library is theencode() methodprovided byPHPEncoder. The method takes any value as an argument and returnsthe PHP code representation for that value.
For example:
<?phprequire'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 tocustomize the created the PHP code. As the second argument, theencode()method takes an array of options, which can be used to customize the returnedPHP code. For example:
<?phprequire'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, ],]Encoding options allow you to customize the output of theencode() method. Itis possible to set these options in three different ways:
- Options can be provided as an array to the
PHPEncoderconstructor. - 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 theencode() method are only temporary and do notapply to following calls.
whitespace : <boolean> (true)
When set tofalse, generation of all extra whitespace is disabled and allother settings that affect whitespace are ignored.hex.capitalize : <boolean> (false)
When set totrueall hexadecimal characters in the output are writtenusing upper case instead of lower case.null.capitalize : <boolean> (false)
When set totrue, allnullvalues are written in upper case instead oflower case.boolean.capitalize : <boolean> (false)
When set totrue, alltrueandfalsevalues are written in upper caseinstead 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 number15as0xf.float.integers : <boolean|"all"> (false)
When set totrue, any float that represents an integer and has a valuethat is accurately represented by the floating point number will be encodedas an integer instead of a float. (e.g. the value2.0will be encoded as2). To include the values that are not accurately represented, you may setoption to"all".float.export : <boolean> (false)
When set totruefloats are encoded usingvar_export(), which causes aslightly different output on non integer floating point numbers compared tothe standard implemented method. In some cases, this may produce moreaccurate numbers but with less cleaner representation.float.precision : <integer|false> (17)
The maximum precision of encoded floating point values, which usually alsomeans the maximum number of digits in encoded floats. If the value is set tofalse, the PHP ini settingserialize_precisionwill be used instead.Note that due to the way floating point values work, a value greater than 17does not provide any additional precision.string.binary : <boolean> (false)
When set totrueany string that is not valid UTF-8 will be encoded inbase 64 and wrapped withbase64_decode()call.string.escape : <boolean> (true)
When set totrue, all strings containing bytes outside the 32-126 ASCIIrange will be written with double quotes and the characters outside therange will be escaped.string.utf8 : <boolean> (false)
When both this option andstring.escapeare set totrue, all validmultibyte UTF-8 characters in strings are encoded using the PHP7 unicodecode point syntax. Note that this syntax does not work in PHP versionsearlier than 7.0.string.classes : <string[]> ([])
Defines a list of classes or class namespace prefixes for classes thatcan be encoded using the class resolution operator::classwhenencountered in strings. e.g. providing the value['Riimu\\']would encodeall strings that look like class names in theRiimunamespace likeRiimu\Kit\PHPEncoder::class.string.imports : <string[]> ([])
List of imports used in the resulting code file, which allows class namesto be written using shorter format. The list should be an associative arraywith the namespace or class as the key and the used name as the value. Useempty 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[]insteadusing of the long array notationarray().array.base : <integer|string> (0)
Base indentation for arrays as a number of spaces or as a string. Providesconvenience when you need to output code to a file with specific level ofindentation.array.indent : <integer|string> (4)
Amount of indentation for single level of indentation as a number of spacesor a string.array.align : <boolean> (false)
When set totrue, array assignment operators=>are aligned to the samecolumn using spaces. Even if enabled,array.omitandarray.inlineoptions are still respected, but only if all the keys in the specific arraycan be omitted.array.inline : <boolean|integer> (70)
When set totrue, any array that can be written without any array keyswill be written in a single line. If an integer is provided instead, thearray will be written as a single line only if it does not exceed thatnumber of characters. This option has no effect whenarray.omitis set tofalse.array.omit : <boolean> (true)
When set totrue, any redundant array keys will not be included (e.g. thearray[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, thedefaultPHP_EOLwill 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 willbe used as the PHP code representation of the object. If the methodtoPHPValue()exists instead, the returned value will be encoded as PHP andused as the code representation of the object.object.format : <string> ('vars')
Default object encoding format. The possible values are:stringcasts the object to string and then encodes that string as PHP.serializeserializes the object and wraps it withunserialize()exportmimics thevar_export()object representationarraycasts the object to an array and encodes that arrayvarsturns object into an array usingget_object_vars()iterateturns 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 objectsor not when using the object encoding formatsvars,arrayoriterate.recursion.detect : <boolean> (true)
When set totrue, the encoder will attempt to detect circular referencesin arrays and objects to avoid infinite loops.recursion.ignore : <boolean> (false)
When set totrue, any circular reference will be replaced withnullinstead of throwing an exception.recursion.max : <integer|false> (false)
Maximum number of levels when encoding arrays and objects. Exception isthrown when the maximum is exceeded. Set tofalseto have no limit.
This library is Copyright (c) 2013-2022 Riikka Kalliomäki.
See LICENSE for license and copying information.
About
Highly customizable alternative to var_export for PHP code generation
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.