Highly customizable alternative to var_export for PHP code generation

Overview

PHP Variable Exporter

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/

CI Scrutinizer codecov Packagist

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:

  1. Acquire the composer.phar by running the Composer Command-line installation in your project root.

  2. 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 to false, generation of all extra whitespace is disabled and all other settings that affect whitespace are ignored.

  • hex.capitalize : <boolean> (false)
    When set to true all hexadecimal characters in the output are written using upper case instead of lower case.

  • null.capitalize : <boolean> (false)
    When set to true, all null values are written in upper case instead of lower case.

  • boolean.capitalize : <boolean> (false)
    When set to true, all true and false 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 number 15 as 0xf.

  • float.integers : <boolean|"all"> (false)
    When set to true, 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 value 2.0 will be encoded as 2). To include the values that are not accurately represented, you may set option to "all".

  • float.export : <boolean> (false)
    When set to true floats are encoded using var_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 to false, the PHP ini setting serialize_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 to true any string that is not valid UTF-8 will be encoded in base 64 and wrapped with base64_decode() call.

  • string.escape : <boolean> (true)
    When set to true, 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 and string.escape are set to true, 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 the Riimu namespace like Riimu\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; and use PHPUnit\Framework\TestCase;, you could set up the array as ['Riimu\\Kit\\PHPEncoder\\' => '', 'PHPUnit\\Framework\\TestCase' => 'TestCase']

  • array.short : <boolean> (true)
    When set to true, arrays are enclosed using square brackets [] instead using of the long array notation array().

  • 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 to true, array assignment operators => are aligned to the same column using spaces. Even if enabled, array.omit and array.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 to true, 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 when array.omit is set to false.

  • array.omit : <boolean> (true)
    When set to true, 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 to false, the default PHP_EOL will be used instead.

  • object.method : <boolean> (true)
    When set to true, any encoded object will be checked for methods toPHP() and toPHPValue(). If the method toPHP() exists, the returned string will be used as the PHP code representation of the object. If the method toPHPValue() 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 with unserialize()
    • export mimics the var_export() object representation
    • array casts the object to an array and encodes that array
    • vars turns object into an array using get_object_vars()
    • iterate turns the object into an array by iterating over it with foreach
  • object.cast : <boolean> (true)
    Whether to add an (object) cast in front of arrays generated from objects or not when using the object encoding formats vars, array or iterate.

  • recursion.detect : <boolean> (true)
    When set to true, the encoder will attempt to detect circular references in arrays and objects to avoid infinite loops.

  • recursion.ignore : <boolean> (false)
    When set to true, any circular reference will be replaced with null 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 to false to have no limit.

Credits

This library is Copyright (c) 2013-2020 Riikka Kalliomäki.

See LICENSE for license and copying information.

You might also like...
An alternative Redis session handler for PHP featuring per-session locking and session fixation protection

RedisSessionHandler An alternative Redis session handler featuring session locking and session fixation protection. News phpredis v4.1.0 (released on

Calibre OPDS (and HTML) PHP Server : web-based light alternative to Calibre content server / Calibre2OPDS to serve ebooks (epub, mobi, pdf, ...)

COPS COPS stands for Calibre OPDS (and HTML) Php Server. See : COPS's home for more details. Don't forget to check the Wiki. Why ? In my opinion Calib

Alternative to tmpfile() function

TmpFile Alternative to tmpfile() function. Installation You can install the latest version via Composer: composer require denisyukphp/tmpfile This pa

An article about alternative solution for convert object into a JSON Object for your api.

Do we really need a serializer for our JSON API? The last years I did build a lot of JSON APIs but personally was never happy about the magic of using

An alternative to run cron jobs that uses simple HTTP requests

SilverStripe Simple Jobs An alternative to run cron jobs that uses simple HTTP requests. This module require SilverStripe CronTask. Why? Configuring c

Ethereal Billing System is meant to be used as a personal alternative to WHMCS.
Ethereal Billing System is meant to be used as a personal alternative to WHMCS.

Ethereal Billing System is meant to be used as a personal alternative to WHMCS. In no way is this as good or even better than WHMCS apart from the fact that is free and open source to the public.

FUGIO: Automatic Exploit Generation for PHP Object Injection Vulnerabilities

FUGIO FUGIO is the first automatic exploit generation (AEG) tool for PHP object injection (POI) vulnerabilities. When exploiting a POI vulnerability,

A PHP sitemap generation tool.

Cartographer A sitemap generation tool for PHP following the Sitemap Protocol v0.9. Cartographer can handle Sitemaps of any size. When generating site

A next-generation package manager for the front-end
A next-generation package manager for the front-end

Duo is a next-generation package manager that blends the best ideas from Component, Browserify and Go to make organizing and writing front-end code qu

Comments
  • Add test to check if numeric keys are removed

    Add test to check if numeric keys are removed

    There is a suspected bug where the output string does not have numeric array keys removed (when array.omit => true) if array.align is also set to true.

    I added a test case to verify it's existence. As I understand from the README (option documentation), this is not the intended behavior. Could you verify and look into it?

    opened by anroots 4
  • All exceptions should inherit from a base PHPEncoder\Exception

    All exceptions should inherit from a base PHPEncoder\Exception

    Thanks for this project. I have been using it for several months to prettify a configuration array that is modified by a UI and written to a file.

    It would be nice if all exceptions thrown by PHPEncoder would inherit from a base PHPEncoder\Exception class. Currently, InvalidOptionException is the only PHPEncoder specific exception while InvalidArgumentException and RuntimeException are thrown directly. Implementing this recommendation will make it possible to distinguish between PHPEncoder exceptions and other exceptions thrown by an app using PHPEncoder (see example below).

    public function write( $content ) : bool
    {
    
    	try
    	{
    
    		if( !$this->validate( $content ) )
    			throw new APP_Exception( 'SOME USEFUL MESSAGE.' );
    
    		$put = ( new \Riimu\Kit\PHPEncoder\PHPEncoder )->encode( $content );
    
    		if( file_put_contents( $this->path(), $put ) === false )
    			throw new APP_Exception( 'SOME USEFUL MESSAGE.' );
    
    	}
    	catch( APP_Exception $e )
    	{
    		// do something with APP thrown exception
    	}
    	catch( \Riimu\Kit\PHPEncoder\Exception $e )
    	{
    		// do something with PHPEncoder thrown exception
    	}
    
    	return true;
    }
    
    opened by jmwebservices 2
  • Comments

    Comments

    I have a specific need, can it be implemented in this library?

    I want to have dumped array with comments like this:

    return [
        'a' => [
            'a1' => 'one', /// from file-a
        ],
        'b' => [
            'b2' => 'two', /// from file-b
        ],    
    ];
    

    It could be implemented with providing callback:

    public function commentsCallback(array $keys, $value) {
        /// example, actual logic will be other
        if ($keys == ['a','a1'] and $value === 'one') return 'from file a';
        /// ....
        return null;
    }
    

    Thanks in advance!

    opened by hiqsol 2
Releases(v2.4.2)
  • v2.4.2(Dec 10, 2022)

  • v2.4.1(Nov 29, 2020)

  • v2.4.0(Jul 3, 2018)

    • Added string.classes option, which allows to define an array of classes or namespaces to encode using the ::class format, when encountered as strings
    • Added string.imports options, which allows to define the used imports to write the ::class format strings using shorter imported notation
    • Support for HHVM has been dropped, as HHVM no longer aims for PHP compatibility
    • Added travis builds for PHP 7.2
    • Change some rules in the used coding standard
    Source code(tar.gz)
    Source code(zip)
  • v2.3.0(Jul 15, 2017)

    • Added string.utf8 option which causes the string encoder to escape all valid multibyte UTF-8 characters using the PHP7 unicode code point syntax.
    • Added string.binary option which causes the string encoder to encode all non UTF-8 strings using a base64_encode().
    • Added integer.type option that accepts values binary, octal, decimal or hexadecimal which can be used to change the output syntax of integers.
    • Added hex.capitalize option that causes all hexadecimal character in output to appear in upper case
    • Added float.export option that forces float encoder to use var_export for encoding floating point numbers
    • Float encoder now delegates integer encoding to the integer encoder (to allow different integer types).
    Source code(tar.gz)
    Source code(zip)
  • v2.2.0(Jul 8, 2017)

    • Increase the minimum PHP version requirement to 5.6
    • Update to latest coding standards
    • Update tests to work with PHPUnit 6
    • Update travis build to test for PHP 7.1
    Source code(tar.gz)
    Source code(zip)
  • v2.1.3(Nov 8, 2015)

  • v2.1.2(Aug 22, 2015)

  • v2.1.1(Aug 8, 2015)

    • Fixed object encoder not throwing an exception on some incorrect object.format values.
    • Fixed coding standards issues around the code and api documentation
    • Improved Travis build process
    Source code(tar.gz)
    Source code(zip)
  • v2.1.0(Apr 18, 2015)

    • Encoder options with null default value will now be recognized
    • The integer encoder will now add an (int) cast in front of integers, if their value equals PHP_INT_MAX * -1 - 1.
    • If float.integers is set to true, the float encoder will now only encode floats as integers if the value is accurately represented by the float. Set the value to "all" to restore the previous behavior.
    • The float encoder no longer breaks if the PHP locale uses comma as a decimal separator.
    • The float encoder now behaves slightly differently when deciding whether to use the exponential float notation or not.
    • The float encoder now uses serialize_precision when the option precision is set to false
    • Several methods will now throw an InvalidOptionException if any invalid encoder options have been provided
    Source code(tar.gz)
    Source code(zip)
  • v2.0.2(Jan 21, 2015)

    • array.align will now respect array.omit and array.inline settings if all the keys in the array can be omitted.
    • Clarified documentation on how these settings are intended to work together.
    Source code(tar.gz)
    Source code(zip)
  • v2.0.1(Jan 11, 2015)

Owner
Riikka Kalliomäki
Riikka Kalliomäki
A self-hosted alternative to putting your code snippets on Gist.

WP-Gistpen Contributors: JamesDiGioia Donate link: http://jamesdigioia.com/ Tags: gist, code snippets, codepen Requires at least: 5.2 Requires PHP: 5.

Intraxia 71 Nov 15, 2022
A collection of command line scripts for Magento 2 code generation, and a PHP module system for organizing command line scripts.

What is Pestle? Pestle is A PHP Framework for creating and organizing command line programs An experiment in implementing python style module imports

Alan Storm 526 Dec 5, 2022
Blacksmith is a code generation tool which automates the creation of common files that you'd typically create for each entity in your application.

Blacksmith is a code generation tool which automates the creation of common files that you'd typically create for each entity in your application.

Indatus 197 Dec 30, 2022
A highly compressed version of the magento 1.9 sample data and a script to create it.

Compressed Magento 1.9 Sample Data The following variations are available: 65M compressed-magento-sample-data-1.9.2.4.tgz 64M compressed-magento-sampl

Vinai Kopp 120 Sep 9, 2022
SPAM Registration Stopper is a Q2A plugin that prevents highly probable SPAM user registrations based on well-known SPAM checking services and other techniques

SPAM Registration Stopper [by Gabriel Zanetti] Description SPAM Registration Stopper is a Question2Answer plugin that prevents highly probable SPAM us

Gabriel Zanetti 2 Jan 23, 2022
Simple customizable captcha script for bot prevention in php language.

phpCaptcha Simple customizable captcha script for bot prevention in php language. Usage <?php session_start(); $status = ""; if ($_SESSION['captcha']

Филип Арсовски 11 Oct 10, 2022
Yclas Self Hosted is a powerful script that can transform any domain into a fully customizable classifieds site within a few seconds.

Yclas 4.4.0. Description Yclas self-hosted is a powerful script that can transform any domain into a fully customizable classifieds site within a few

Yclas 299 May 29, 2022
A Customizable Fishing Rod for PocketMine-MP servers.

Custom Fishing Rod About [ENG] This is a PocketMine-MP (or forks) plugin that implements a customizable fishing rod to your server. [FRA] C'est un plu

null 6 May 25, 2022
A customizable decentralized micro-blog (Twitter) and cms (Wordpress) that only you host and moderate.

Consider this --> each Miter account is individually hosted on a user's personal and private third party server (host) - either purchased or free - as

Vije Miller 3 Jun 8, 2022
An extremely customizable BuildBattle mini-game designed for scalability and simplicity.

BuildBattle An extremely customizable BuildBattle mini-game designed for scalability and simplicity. Features Customisable messages and scoreboard Mul

null 11 Sep 18, 2022