8000 [VarDumper] Add support for options in `dump()`/`dd()` by alexandre-daubois · Pull Request #48667 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

[VarDumper] Add support for options in dump()/dd() #48667

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: 7.4
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 18 additions & 12 deletions src/Symfony/Bundle/DebugBundle/Resources/config/services.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
use Symfony\Component\VarDumper\Command\Descriptor\HtmlDescriptor;
use Symfony\Component\VarDumper\Command\ServerDumpCommand;
use Symfony\Component\VarDumper\Dumper\CliDumper;
use Symfony\Component\VarDumper\Dumper\ContextProvider\BacktraceContextProvider;
use Symfony\Component\VarDumper\Dumper\ContextProvider\CliContextProvider;
use Symfony\Component\VarDumper\Dumper\ContextProvider\RequestContextProvider;
use Symfony\Component\VarDumper\Dumper\ContextProvider\SourceContextProvider;
Expand All @@ -35,6 +36,21 @@
->set('env(VAR_DUMPER_SERVER)', '127.0.0.1:9912')
;

$contextProviders = [
'source' => inline_service(SourceContextProvider::class)->args([
param('kernel.charset'),
param('kernel.project_dir'),
service('debug.file_link_formatter')->nullOnInvalid(),
]),
];

if (class_exists(BacktraceContextProvider::class)) {
$contextProviders['backtrace'] = inline_service(BacktraceContextProvider::class)->args([
0,
service('var_dump.cloner')->nullOnInvalid(),
]);
}

$container->services()

->set('twig.extension.dump', DumpExtension::class)
Expand Down Expand Up @@ -81,13 +97,7 @@
->decorate('var_dumper.cli_dumper')
->args([
service('var_dumper.contextualized_cli_dumper.inner'),
[
'source' => inline_service(SourceContextProvider::class)->args([
param('kernel.charset'),
param('kernel.project_dir'),
service('debug.file_link_formatter')->nullOnInvalid(),
]),
],
$contextProviders,
])

->set('var_dumper.html_dumper', HtmlDumper::class)
Expand All @@ -104,11 +114,7 @@
->args([
'', // server host
[
'source' => inline_service(SourceContextProvider::class)->args([
param('kernel.charset'),
param('kernel.project_dir'),
service('debug.file_link_formatter')->nullOnInvalid(),
]),
...$contextProviders,
'request' => inline_service(RequestContextProvider::class)->args([service('request_stack')]),
'cli' => inline_service(CliContextProvider::class),
],
Expand Down
1 change: 1 addition & 0 deletions src/Symfony/Component/VarDumper/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ CHANGELOG
---

* Add support for `FORCE_COLOR` environment variable
* Add support of options when using `dd()` and `dump()`

7.1
---
Expand Down
16 changes: 16 additions & 0 deletions src/Symfony/Component/VarDumper/Cloner/Data.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
namespace Symfony\Component\VarDumper\Cloner;

use Symfony\Component\VarDumper\Caster\Caster;
use Symfony\Component\VarDumper\Dumper\ContextProvider\BacktraceContextProvider;
use Symfony\Component\VarDumper\Dumper\ContextProvider\SourceContextProvider;

/**
Expand Down Expand Up @@ -270,12 +271,17 @@ public function dump(DumperInterface $dumper): void
$cursor->hashType = -1;
$cursor->attr = $this->context[SourceContextProvider::class] ?? [];
$label = $this->context['label'] ?? '';
$options = $this->context['options'] ?? [];

if ($cursor->attr || '' !== $label) {
$dumper->dumpScalar($cursor, 'label', $label);
}
$cursor->hashType = 0;
$this->dumpItem($dumper, $cursor, $refs, $this->data[$this->position][$this->key]);

if (false !== ($options['_trace'] ?? false) && $cursor->attr = $this->context[BacktraceContextProvider::class] ?? []) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

comparisons to boolean... you missed testing this is === true :P

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually, _trace can be either a bool or a integer. false disables the trace. If it's an integer, we limit the trace size. Also, the limit is disabled if _trace is <= 0. That's why we can't use === true here 😄 But maybe limiting the stack trace isn't that useful and we may only accept a boolean for _trace?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ah, makes sense then, let's keep as is :)

$this->dumpDebugBacktrace($dumper, $cursor);
}
}

/**
Expand Down Expand Up @@ -426,4 +432,14 @@ private function getStub(mixed $item): mixed

return $stub;
}

private function dumpDebugBacktrace(DumperInterface $dumper, Cursor $cursor): void
{
$backtrace = $cursor->attr['backtrace'];

$dumper->dumpScalar($cursor, 'default', '');
$dumper->dumpScalar($cursor, 'default', '**DEBUG BACKTRACE**');

$backtrace->dump($dumper);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\VarDumper\Dumper\ContextProvider;

use Symfony\Component\VarDumper\Caster\TraceStub;
use Symfony\Component\VarDumper\Cloner\ClonerInterface;
use Symfony\Component\VarDumper\Cloner\VarCloner;

/**
* Provides the debug stacktrace of the VarDumper call.
*
* @author Alexandre Daubois <alex.daubois@gmail.com>
*/
final class BacktraceContextProvider implements ContextProviderInterface
{
private const BACKTRACE_CONTEXT_PROVIDER_DEPTH = 4;

public function __construct(
private readonly bool|int $limit,
private ?ClonerInterface $cloner,
) {
$this->cloner ??= new VarCloner();
}

public function getContext(): ?array
{
if (false === $this->limit) {
return [];
}

$context = [];
$traces = debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS);

for ($i = self::BACKTRACE_CONTEXT_PROVIDER_DEPTH; $i < \count($traces); ++$i) {
$context[] = $traces[$i];

if ($this->limit === \count($context)) {
break;
}
}

$stub = new TraceStub($context);

return ['backtrace' => $this->cloner->cloneVar($stub->value)];
}
}
41 changes: 33 additions & 8 deletions src/Symfony/Component/VarDumper/Resources/functions/dump.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,18 +19,33 @@
*/
function dump(mixed ...$vars): mixed
{
if (!$vars) {
VarDumper::dump(new ScalarStub('🐛'));
$options = array_filter(
$vars,
static fn (mixed $key): bool => \in_array($key, VarDumper::AVAILABLE_OPTIONS, true),
\ARRAY_FILTER_USE_KEY
);

return null;
}
$trace = $options['_trace'] ?? null;
unset($options['_trace']);

if (array_key_exists(0, $vars) && 1 === count($vars)) {
VarDumper::dump($vars[0]);
VarDumper::dump($vars[0], null, $options);
$k = 0;
} else {
$vars = array_filter($vars, static fn (int|string $key) => !str_starts_with($key, '_'), \ARRAY_FILTER_USE_KEY);

if (!$vars) {
VarDumper::dump(new ScalarStub('🐛'), null, $options);

return null;
}

foreach ($vars as $k => $v) {
VarDumper::dump($v, is_int($k) ? 1 + $k : $k);
if (array_key_last($vars) === $k) {
$options['_trace'] = $trace;
}

VarDumper::dump($v, is_int($k) ? 1 + $k : $k, $options);
}
}

Expand All @@ -55,11 +70,21 @@ function dd(mixed ...$vars): never
exit(1);
}

$options = array_filter(
$vars,
static fn (mixed $key): bool => \in_array($key, VarDumper::AVAILABLE_OPTIONS, true),
\ARRAY_FILTER_USE_KEY
);

if (array_key_exists(0, $vars) && 1 === count($vars)) {
VarDumper::dump($vars[0]);
VarDumper::dump($vars[0], null, $options);
} else {
foreach ($vars as $k => $v) {
VarDumper::dump($v, is_int($k) ? 1 + $k : $k);
if (str_starts_with($k, '_')) {
continue;
}

VarDumper::dump($v, is_int($k) ? 1 + $k : $k, $options);
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\VarDumper\Tests\Dumper\ContextProvider;

use PHPUnit\Framework\TestCase;
use Symfony\Component\VarDumper\Cloner\VarCloner;
use Symfony\Component\VarDumper\Dumper\ContextProvider\BacktraceContextProvider;

class BacktraceContextProviderTest extends TestCase
{
public function testFalseBacktraceLimit()
{
$provider = new BacktraceContextProvider(false, new VarCloner());
$this->assertArrayNotHasKey('backtrace', $provider->getContext());
}

public function testPositiveBacktraceLimit()
{
$provider = new BacktraceContextProvider(2, new VarCloner());
$this->assertCount(2, $provider->getContext()['backtrace']);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,16 @@
namespace Symfony\Component\VarDumper\Tests\Dumper;

use PHPUnit\Framework\TestCase;
use Symfony\Component\ErrorHandler\ErrorRenderer\FileLinkFormatter;
use Symfony\Component\VarDumper\Cloner\VarCloner;
use Symfony\Component\VarDumper\Dumper\CliDumper;
use Symfony\Component\VarDumper\Dumper\ContextProvider\BacktraceContextProvider;
use Symfony\Component\VarDumper\Dumper\ContextProvider\SourceContextProvider;
use Symfony\Component\VarDumper\Dumper\ContextualizedDumper;

/**
* @author Kévin Thérage <therage.kevin@gmail.com>
* @author Alexandre Daubois <alex.daubois@gmail.com>
*/
class ContextualizedDumperTest extends TestCase
{
Expand All @@ -28,8 +31,8 @@ public function testContextualizedCliDumper()
$wrappedDumper->setColors(true);

$var = 'example';
$href = \sprintf('file://%s#L%s', __FILE__, 37);
$dumper = new ContextualizedDumper($wrappedDumper, [new SourceContextProvider()]);
$href = \sprintf('file://%s#L%s', __FILE__, 40);
$dumper = new ContextualizedDumper($wrappedDumper, [new SourceContextProvider(fileLinkFormatter: new FileLinkFormatter())]);
$cloner = new VarCloner();
$data = $cloner->cloneVar($var);

Expand All @@ -40,4 +43,22 @@ public function testContextualizedCliDumper()
$this->assertStringContainsString("\e]8;;{$href}\e\\^\e]", $out);
$this->assertStringContainsString("m{$var}\e[", $out);
}

public function testEnablingBacktraceDisplaysIt()
{
$wrappedDumper = new CliDumper('php://output');
$cloner = new VarCloner();

$dumper = new ContextualizedDumper($wrappedDumper, [new SourceContextProvider(), new BacktraceContextProvider(0, $cloner)]);

ob_start();
$dumper->dump(
$cloner->cloneVar(123)->withContext([
'options' => ['_trace' => true],
])
);
$result = ob_get_clean();

$this->assertStringContainsString('**DEBUG BACKTRACE**', $result);
}
}
14 changes: 14 additions & 0 deletions src/Symfony/Component/VarDumper/Tests/Dumper/FunctionsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,20 @@ public function testDumpReturnsAllNamedArgsInArray()
$this->assertSame([$var1, 'second' => $var2, 'third' => $var3], $return);
}

public function testDumpReturnsAllNamedArgsExceptSpecialOptionOnes()
{
$this->setupVarDumper();

$var1 = 'a';
$var2 = 'b';

ob_start();
$return = dump($var1, named: $var2, _trace: true, _flags: 0);
ob_end_clean();

$this->assertSame([$var1, 'named' => $var2], $return);
}

protected function setupVarDumper()
{
$cloner = new VarCloner();
Expand Down
Loading
Loading
0