Advanced Usage of the VarDumper Component

Advanced Usage of the VarDumper Component

The dump() function is just a thin wrapper and a more convenient way to call [VarDumper::dump()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/VarDumper/VarDumper.php "Symfony\Component\VarDumper\VarDumper::dump()"). You can change the behavior of this function by calling [VarDumper::setHandler($callable)](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/VarDumper/VarDumper.php "Symfony\Component\VarDumper\VarDumper::setHandler()"). Calls to dump() will then be forwarded to $callable.

By adding a handler, you can customize the Cloners, Dumpers and Casters as explained below. A simple implementation of a handler function might look like this:

  1. use Symfony\Component\VarDumper\Cloner\VarCloner;
  2. use Symfony\Component\VarDumper\Dumper\CliDumper;
  3. use Symfony\Component\VarDumper\Dumper\HtmlDumper;
  4. use Symfony\Component\VarDumper\VarDumper;
  5. VarDumper::setHandler(function ($var) {
  6. $cloner = new VarCloner();
  7. $dumper = 'cli' === PHP_SAPI ? new CliDumper() : new HtmlDumper();
  8. $dumper->dump($cloner->cloneVar($var));
  9. });

Cloners

A cloner is used to create an intermediate representation of any PHP variable. Its output is a Symfony\Component\VarDumper\Cloner\Data object that wraps this representation.

You can create a Data object this way:

  1. use Symfony\Component\VarDumper\Cloner\VarCloner;
  2. $cloner = new VarCloner();
  3. $data = $cloner->cloneVar($myVar);
  4. // this is commonly then passed to the dumper
  5. // see the example at the top of this page
  6. // $dumper->dump($data);

Whatever the cloned data structure, resulting Data objects are always serializable.

A cloner applies limits when creating the representation, so that one can represent only a subset of the cloned variable. Before calling [cloneVar()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/VarDumper/Cloner/VarCloner.php "Symfony\Component\VarDumper\Cloner\VarCloner::cloneVar()"), you can configure these limits:

[setMaxItems()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/VarDumper/Cloner/VarCloner.php "Symfony\Component\VarDumper\Cloner\VarCloner::setMaxItems()")

Configures the maximum number of items that will be cloned past the minimum nesting depth. Items are counted using a breadth-first algorithm so that lower level items have higher priority than deeply nested items. Specifying -1 removes the limit.

[setMinDepth()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/VarDumper/Cloner/VarCloner.php "Symfony\Component\VarDumper\Cloner\VarCloner::setMinDepth()")

Configures the minimum tree depth where we are guaranteed to clone all the items. After this depth is reached, only setMaxItems items will be cloned. The default value is 1, which is consistent with older Symfony versions.

[setMaxString()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/VarDumper/Cloner/VarCloner.php "Symfony\Component\VarDumper\Cloner\VarCloner::setMaxString()")

Configures the maximum number of characters that will be cloned before cutting overlong strings. Specifying -1 removes the limit.

Before dumping it, you can further limit the resulting Symfony\Component\VarDumper\Cloner\Data object using the following methods:

[withMaxDepth()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/VarDumper/Cloner/Data.php "Symfony\Component\VarDumper\Cloner\Data::withMaxDepth()")

Limits dumps in the depth dimension.

[withMaxItemsPerDepth()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/VarDumper/Cloner/Data.php "Symfony\Component\VarDumper\Cloner\Data::withMaxItemsPerDepth()")

Limits the number of items per depth level.

[withRefHandles()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/VarDumper/Cloner/Data.php "Symfony\Component\VarDumper\Cloner\Data::withRefHandles()")

Removes internal objects’ handles for sparser output (useful for tests).

[seek()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/VarDumper/Cloner/Data.php "Symfony\Component\VarDumper\Cloner\Data::seek()")

Selects only sub-parts of already cloned arrays, objects or resources.

Unlike the previous limits on cloners that remove data on purpose, these can be changed back and forth before dumping since they do not affect the intermediate representation internally.

Note

When no limit is applied, a Symfony\Component\VarDumper\Cloner\Data object is as accurate as the native [serialize](https://www.php.net/manual/en/function.serialize.php "serialize") function, and thus could be used for purposes beyond debugging.

Dumpers

A dumper is responsible for outputting a string representation of a PHP variable, using a Symfony\Component\VarDumper\Cloner\Data object as input. The destination and the formatting of this output vary with dumpers.

This component comes with an Symfony\Component\VarDumper\Dumper\HtmlDumper for HTML output and a Symfony\Component\VarDumper\Dumper\CliDumper for optionally colored command line output.

For example, if you want to dump some $variable, do:

  1. use Symfony\Component\VarDumper\Cloner\VarCloner;
  2. use Symfony\Component\VarDumper\Dumper\CliDumper;
  3. $cloner = new VarCloner();
  4. $dumper = new CliDumper();
  5. $dumper->dump($cloner->cloneVar($variable));

By using the first argument of the constructor, you can select the output stream where the dump will be written. By default, the CliDumper writes on php://stdout and the HtmlDumper on php://output. But any PHP stream (resource or URL) is acceptable.

Instead of a stream destination, you can also pass it a callable that will be called repeatedly for each line generated by a dumper. This callable can be configured using the first argument of a dumper’s constructor, but also using the [setOutput()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/VarDumper/Dumper/AbstractDumper.php "Symfony\Component\VarDumper\Dumper\AbstractDumper::setOutput()") method or the second argument of the [dump()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/VarDumper/Dumper/AbstractDumper.php "Symfony\Component\VarDumper\Dumper\AbstractDumper::dump()") method.

For example, to get a dump as a string in a variable, you can do:

  1. use Symfony\Component\VarDumper\Cloner\VarCloner;
  2. use Symfony\Component\VarDumper\Dumper\CliDumper;
  3. $cloner = new VarCloner();
  4. $dumper = new CliDumper();
  5. $output = '';
  6. $dumper->dump(
  7. $cloner->cloneVar($variable),
  8. function ($line, $depth) use (&$output) {
  9. // A negative depth means "end of dump"
  10. if ($depth >= 0) {
  11. // Adds a two spaces indentation to the line
  12. $output .= str_repeat(' ', $depth).$line."\n";
  13. }
  14. }
  15. );
  16. // $output is now populated with the dump representation of $variable

Another option for doing the same could be:

  1. use Symfony\Component\VarDumper\Cloner\VarCloner;
  2. use Symfony\Component\VarDumper\Dumper\CliDumper;
  3. $cloner = new VarCloner();
  4. $dumper = new CliDumper();
  5. $output = fopen('php://memory', 'r+b');
  6. $dumper->dump($cloner->cloneVar($variable), $output);
  7. $output = stream_get_contents($output, -1, 0);
  8. // $output is now populated with the dump representation of $variable

Tip

You can pass true to the second argument of the [dump()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/VarDumper/Dumper/AbstractDumper.php "Symfony\Component\VarDumper\Dumper\AbstractDumper::dump()") method to make it return the dump as a string:

  1. $output = $dumper->dump($cloner->cloneVar($variable), true);

Dumpers implement the Symfony\Component\VarDumper\Dumper\DataDumperInterface interface that specifies the [dump(Data $data)](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/VarDumper/Dumper/DataDumperInterface.php "Symfony\Component\VarDumper\Dumper\DataDumperInterface::dump()") method. They also typically implement the Symfony\Component\VarDumper\Cloner\DumperInterface that frees them from re-implementing the logic required to walk through a Symfony\Component\VarDumper\Cloner\Data object’s internal structure.

The Symfony\Component\VarDumper\Dumper\HtmlDumper uses a dark theme by default. Use the [setTheme()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/VarDumper/Dumper/HtmlDumper.php "Symfony\Component\VarDumper\Dumper\HtmlDumper::setTheme()") method to use a light theme:

  1. // ...
  2. $htmlDumper->setTheme('light');

The Symfony\Component\VarDumper\Dumper\HtmlDumper limits string length and nesting depth of the output to make it more readable. These options can be overridden by the third optional parameter of the [dump(Data $data)](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/VarDumper/Dumper/DataDumperInterface.php "Symfony\Component\VarDumper\Dumper\DataDumperInterface::dump()") method:

  1. use Symfony\Component\VarDumper\Dumper\HtmlDumper;
  2. $output = fopen('php://memory', 'r+b');
  3. $dumper = new HtmlDumper();
  4. $dumper->dump($var, $output, [
  5. // 1 and 160 are the default values for these options
  6. 'maxDepth' => 1,
  7. 'maxStringLength' => 160
  8. ]);

The output format of a dumper can be fine tuned by the two flags DUMP_STRING_LENGTH and DUMP_LIGHT_ARRAY which are passed as a bitmap in the third constructor argument. They can also be set via environment variables when using [assertDumpEquals($dump, $data, $filter, $message)](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/VarDumper/Test/VarDumperTestTrait.php "Symfony\Component\VarDumper\Test\VarDumperTestTrait::assertDumpEquals()") during unit testing.

The $filter argument of assertDumpEquals() can be used to pass a bit field of Caster::EXCLUDE_* constants and influences the expected output produced by the different casters.

If DUMP_STRING_LENGTH is set, then the length of a string is displayed next to its content:

  1. use Symfony\Component\VarDumper\Cloner\VarCloner;
  2. use Symfony\Component\VarDumper\Dumper\AbstractDumper;
  3. use Symfony\Component\VarDumper\Dumper\CliDumper;
  4. $varCloner = new VarCloner();
  5. $var = ['test'];
  6. $dumper = new CliDumper();
  7. echo $dumper->dump($varCloner->cloneVar($var), true);
  8. // array:1 [
  9. // 0 => "test"
  10. // ]
  11. $dumper = new CliDumper(null, null, AbstractDumper::DUMP_STRING_LENGTH);
  12. echo $dumper->dump($varCloner->cloneVar($var), true);
  13. // (added string length before the string)
  14. // array:1 [
  15. // 0 => (4) "test"
  16. // ]

If DUMP_LIGHT_ARRAY is set, then arrays are dumped in a shortened format similar to PHP’s short array notation:

  1. use Symfony\Component\VarDumper\Cloner\VarCloner;
  2. use Symfony\Component\VarDumper\Dumper\AbstractDumper;
  3. use Symfony\Component\VarDumper\Dumper\CliDumper;
  4. $varCloner = new VarCloner();
  5. $var = ['test'];
  6. $dumper = new CliDumper();
  7. echo $dumper->dump($varCloner->cloneVar($var), true);
  8. // array:1 [
  9. // 0 => "test"
  10. // ]
  11. $dumper = new CliDumper(null, null, AbstractDumper::DUMP_LIGHT_ARRAY);
  12. echo $dumper->dump($varCloner->cloneVar($var), true);
  13. // (no more array:1 prefix)
  14. // [
  15. // 0 => "test"
  16. // ]

If you would like to use both options, then you can combine them by using the logical OR operator |:

  1. use Symfony\Component\VarDumper\Cloner\VarCloner;
  2. use Symfony\Component\VarDumper\Dumper\AbstractDumper;
  3. use Symfony\Component\VarDumper\Dumper\CliDumper;
  4. $varCloner = new VarCloner();
  5. $var = ['test'];
  6. $dumper = new CliDumper(null, null, AbstractDumper::DUMP_STRING_LENGTH | AbstractDumper::DUMP_LIGHT_ARRAY);
  7. echo $dumper->dump($varCloner->cloneVar($var), true);
  8. // [
  9. // 0 => (4) "test"
  10. // ]

Casters

Objects and resources nested in a PHP variable are “cast” to arrays in the intermediate Symfony\Component\VarDumper\Cloner\Data representation. You can customize the array representation for each object/resource by hooking a Caster into this process. The component already includes many casters for base PHP classes and other common classes.

If you want to build your own Caster, you can register one before cloning a PHP variable. Casters are registered using either a Cloner’s constructor or its addCasters() method:

  1. use Symfony\Component\VarDumper\Cloner\VarCloner;
  2. $myCasters = [...];
  3. $cloner = new VarCloner($myCasters);
  4. // or
  5. $cloner->addCasters($myCasters);

The provided $myCasters argument is an array that maps a class, an interface or a resource type to a callable:

  1. $myCasters = [
  2. 'FooClass' => $myFooClassCallableCaster,
  3. ':bar resource' => $myBarResourceCallableCaster,
  4. ];

As you can notice, resource types are prefixed by a : to prevent colliding with a class name.

Because an object has one main class and potentially many parent classes or interfaces, many casters can be applied to one object. In this case, casters are called one after the other, starting from casters bound to the interfaces, the parents classes and then the main class. Several casters can also be registered for the same resource type/class/interface. They are called in registration order.

Casters are responsible for returning the properties of the object or resource being cloned in an array. They are callables that accept five arguments:

  • the object or resource being casted;
  • an array modeled for objects after PHP’s native (array) cast operator;
  • a Symfony\Component\VarDumper\Cloner\Stub object representing the main properties of the object (class, type, etc.);
  • true/false when the caster is called nested in a structure or not;
  • A bit field of Symfony\Component\VarDumper\Caster\Caster ::EXCLUDE_* constants.

Here is a simple caster not doing anything:

  1. use Symfony\Component\VarDumper\Cloner\Stub;
  2. function myCaster($object, $array, Stub $stub, $isNested, $filter)
  3. {
  4. // ... populate/alter $array to your needs
  5. return $array;
  6. }

For objects, the $array parameter comes pre-populated using PHP’s native (array) casting operator or with the return value of $object->__debugInfo() if the magic method exists. Then, the return value of one Caster is given as the array argument to the next Caster in the chain.

When casting with the (array) operator, PHP prefixes protected properties with a \0*\0 and private ones with the class owning the property. For example, \0Foobar\0 will be the prefix for all private properties of objects of type Foobar. Casters follow this convention and add two more prefixes: \0~\0 is used for virtual properties and \0+\0 for dynamic ones (runtime added properties not in the class declaration).

Note

Although you can, it is advised to not alter the state of an object while casting it in a Caster.

Tip

Before writing your own casters, you should check the existing ones.

Adding Semantics with Metadata

Since casters are hooked on specific classes or interfaces, they know about the objects they manipulate. By altering the $stub object (the third argument of any caster), one can transfer this knowledge to the resulting Data object, thus to dumpers. To help you do this (see the source code for how it works), the component comes with a set of wrappers for common additional semantics. You can use:

  • Symfony\Component\VarDumper\Caster\ConstStub to wrap a value that is best represented by a PHP constant;
  • Symfony\Component\VarDumper\Caster\ClassStub to wrap a PHP identifier (i.e. a class name, a method name, an interface, etc.);
  • Symfony\Component\VarDumper\Caster\CutStub to replace big noisy objects/strings/etc. by ellipses;
  • Symfony\Component\VarDumper\Caster\CutArrayStub to keep only some useful keys of an array;
  • Symfony\Component\VarDumper\Caster\ImgStub to wrap an image;
  • Symfony\Component\VarDumper\Caster\EnumStub to wrap a set of virtual values (i.e. values that do not exist as properties in the original PHP data structure, but are worth listing alongside with real ones);
  • Symfony\Component\VarDumper\Caster\LinkStub to wrap strings that can be turned into links by dumpers;
  • Symfony\Component\VarDumper\Caster\TraceStub and their
  • Symfony\Component\VarDumper\Caster\FrameStub and
  • Symfony\Component\VarDumper\Caster\ArgsStub relatives to wrap PHP traces (used by Symfony\Component\VarDumper\Caster\ExceptionCaster).

For example, if you know that your Product objects have a brochure property that holds a file name or a URL, you can wrap them in a LinkStub to tell HtmlDumper to make them clickable:

  1. use Symfony\Component\VarDumper\Caster\LinkStub;
  2. use Symfony\Component\VarDumper\Cloner\Stub;
  3. function ProductCaster(Product $object, $array, Stub $stub, $isNested, $filter = 0)
  4. {
  5. $array['brochure'] = new LinkStub($array['brochure']);
  6. return $array;
  7. }

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.