nicedump/nicedump

Dump a PHP variable in NiceDump format.

v1.1.0 2021-08-16 16:14 UTC

This package is auto-updated.

Last update: 2021-10-16 16:35:26 UTC


README

Tests StyleCI License Latest Stable Version Total Downloads

Dump a PHP variable according to the NiceDump format specification.

Requirements

  • PHP >= 7.3

Install with composer

$ composer require nicedump/nicedump

Basic usage

Create a NiceDump

<?php

require __DIR__ . '/vendor/autoload.php';

use NiceDump\NiceDump;

// $var can be anything.
$var = 'Foo';

// Create a plain dump.
$niceDump = NiceDump::create($var);

// Create a dump with a name.
$niceDump = NiceDump::create($var, 'var');

// Create a dump with a name and a comment.
$niceDump = NiceDump::create($var, 'var', 'This is my variable');

Output a NiceDump

<?php

require __DIR__ . '/vendor/autoload.php';

use NiceDump\NiceDump;

// $var can be anything.
$var = 'Foo';

// Create a plain dump.
$niceDump = NiceDump::create($var);

// Outputs the NiceDump as:
//
// =====BEGIN NICE-DUMP=====
// eyJ0eXBlIjoic3RyaW5nIiwidmFsdWUiOiJGb28iLCJzaXplIjozfQ==
// =====END NICE-DUMP=====
//
// which corresponds to:
//
// {"type":"string","value":"Foo","size":3}
echo $niceDump;

// Get the output explicitly as a string.
$dumpStr = $niceDump->__toString();

// Outputs the same as above.
echo $dumpStr;

// Output can also be done via the global nice_dump() function.
nice_dump($var);
nice_dump($var, 'var');
nice_dump($var, 'var', 'This is my variable');

// Use nice_dump_html() to enclose the output in an HTML-comment.
nice_dump_html($var);
nice_dump_html($var, 'var');
nice_dump_html($var, 'var', 'This is my variable');

Custom serialization

The NiceDump serialization can be customized for a class by implementing the NiceDumpSerializable interface and the niceDumpSerialize() method:

<?php

require __DIR__ . '/vendor/autoload.php';

use NiceDump\NiceDump;
use NiceDump\NiceDumpSerializable;

class Foo implements NiceDumpSerializable
{
    public function __construct(string $text)
    {
        $this->text = $text;
    }

    public function niceDumpSerialize(): array
    {
        return [
            'type'  => '_text_',
            'value' => $this->text,
        ];
    }

    private $text;
}

$foo = new Foo('Bar');
$niceDump = NiceDump::create($foo);

// Outputs the NiceDump as:
//
// =====BEGIN NICE-DUMP=====
// eyJ0eXBlIjoiX3RleHRfIiwidmFsdWUiOiJCYXIifQ==
// =====END NICE-DUMP=====
//
// which corresponds to:
//
// {"type":"_text_","value":"Bar"}
echo $niceDump;

License

MIT