Search by

proqualex / javascript-formatters-core

rsotolongo

Formats JSON as a JavaScript declaration.

Package info

github.com/rsotolongo/javascript-formatters-core

pkg:composer/proqualex/javascript-formatters-core

Statistics

Installs: 3

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

0.1.0 2026-12-01 01:37 UTC

This package is auto-updated.

Last update: 2026-12-01 02:00:35 UTC


README

PHP 8.3+ library for rendering JSON as a JavaScript variable declaration, distributed under the MIT license.

Install the published package with composer require proqualex/javascript-formatters-core.

For local development, add this path repository to the consuming project's composer.json, adjusting the URL relative to that file, then run the same command.

{
    "type": "path",
    "url": "../javascript-formatters/core",
    "options": {
        "versions": {
            "proqualex/javascript-formatters-core": "0.1.0"
        }
    }
}

Load your application's Composer autoloader before using the serializer.

use ProQualEx\JavaScriptFormatters\Core\JavaScriptOutputFormatterOptions;
use ProQualEx\JavaScriptFormatters\Core\JavaScriptSerializer;

$serializer = new JavaScriptSerializer;
echo $serializer->serializeJson('{"items":[1,2]}', new JavaScriptOutputFormatterOptions(
    writeCompacted: true,
    bindingName: 'data',
));
// const data={items:[1,2]};

echo $serializer->serializeValue('null', new JavaScriptOutputFormatterOptions(bindingName: 'label'));
// const label = "null";

serializeJson() accepts a JSON document and preserves its numeric tokens. serializeValue() encodes a PHP value as JSON before formatting it and raises JsonException if encoding fails.

Both methods default to const value with readable indentation. Set writeCompacted: true to omit formatting whitespace. Pass a string to declarationKind to select const, let, or var. Pass a string to bindingName to set the identifier, or omit it to use value. The options constructor throws InvalidArgumentException for invalid declaration keywords or binding identifiers. serializeJson() throws InvalidArgumentException for invalid JSON.

Set quotePropertyNames: true to quote property names. Special keys such as __proto__ retain computed property syntax. Set exportAsDefault: true to generate an ES module default export. In that mode the serializer ignores bindingName and declarationKind.

Run composer install and composer test from this directory to run the direct formatter tests.