CliDumper example

protected function getDump(mixed $data, string|int $key = null, int $filter = 0): ?string
    {
        if (null === $flags = $this->varDumperConfig['flags']) {
            $flags = getenv('DUMP_LIGHT_ARRAY') ? CliDumper::DUMP_LIGHT_ARRAY : 0;
            $flags |= getenv('DUMP_STRING_LENGTH') ? CliDumper::DUMP_STRING_LENGTH : 0;
            $flags |= getenv('DUMP_COMMA_SEPARATOR') ? CliDumper::DUMP_COMMA_SEPARATOR : 0;
        }

        $cloner = new VarCloner();
        $cloner->addCasters($this->varDumperConfig['casters']);
        $cloner->setMaxItems(-1);
        $dumper = new CliDumper(null, null, $flags);
        $dumper->setColors(false);
        $data = $cloner->cloneVar($data$filter)->withRefHandles(false);
        if (null !== $key && null === $data = $data->seek($key)) {
            return null;
        }

        return rtrim($dumper->dump($data, true));
    }

    private function prepareExpectation(mixed $expected, int $filter): string
    {
        
$queries = [
            ['sql' => 'SELECT * FROM table1 WHERE field1 = ?1', 'params' => [$param], 'types' => $types, 'executionMS' => 1],
        ];
        $c = $this->createCollector($queries);
        $c->collect(new Request()new Response());
        $c = unserialize(serialize($c));

        $collectedQueries = $c->getQueries();

        $collectedParam = $collectedQueries['default'][0]['params'][0];
        if ($collectedParam instanceof Data) {
            $dumper = new CliDumper($out = fopen('php://memory', 'r+'));
            $dumper->setColors(false);
            $collectedParam->dump($dumper);
            $this->assertStringMatchesFormat($expectedprint_r(stream_get_contents($out, -1, 0), true));
        } elseif (\is_string($expected)) {
            $this->assertStringMatchesFormat($expected$collectedParam);
        } else {
            $this->assertEquals($expected$collectedParam);
        }

        $this->assertEquals($explainable$collectedQueries['default'][0]['explainable']);
        $this->assertSame($runnable$collectedQueries['default'][0]['runnable']);
    }
protected function getDump(mixed $data, string|int $key = null, int $filter = 0): ?string
    {
        if (null === $flags = $this->varDumperConfig['flags']) {
            $flags = getenv('DUMP_LIGHT_ARRAY') ? CliDumper::DUMP_LIGHT_ARRAY : 0;
            $flags |= getenv('DUMP_STRING_LENGTH') ? CliDumper::DUMP_STRING_LENGTH : 0;
            $flags |= getenv('DUMP_COMMA_SEPARATOR') ? CliDumper::DUMP_COMMA_SEPARATOR : 0;
        }

        $cloner = new VarCloner();
        $cloner->addCasters($this->varDumperConfig['casters']);
        $cloner->setMaxItems(-1);
        $dumper = new CliDumper(null, null, $flags);
        $dumper->setColors(false);
        $data = $cloner->cloneVar($data$filter)->withRefHandles(false);
        if (null !== $key && null === $data = $data->seek($key)) {
            return null;
        }

        return rtrim($dumper->dump($data, true));
    }

    private function prepareExpectation(mixed $expected, int $filter): string
    {
        
class ServerDumpCommand extends Command
{
    private DumpServer $server;

    /** @var DumpDescriptorInterface[] */
    private array $descriptors;

    public function __construct(DumpServer $server, array $descriptors = [])
    {
        $this->server = $server;
        $this->descriptors = $descriptors + [
            'cli' => new CliDescriptor(new CliDumper()),
            'html' => new HtmlDescriptor(new HtmlDumper()),
        ];

        parent::__construct();
    }

    protected function configure(): void
    {
        $this
            ->addOption('format', null, InputOption::VALUE_REQUIRED, sprintf('The output format (%s)', implode(', ', $this->getAvailableFormats())), 'cli')
            ->setHelp(<<<'EOF'
$this->cloner->addCasters([
                '*' => $this->castObject(...),
            ]);

            $this->outputBuffer = fopen('php://memory', 'r+');
            if ($this->options['multiline']) {
                $output = $this->outputBuffer;
            } else {
                $output = $this->echoLine(...);
            }

            $this->dumper = new CliDumper($output, null, CliDumper::DUMP_LIGHT_ARRAY | CliDumper::DUMP_COMMA_SEPARATOR);
        }
    }

    public function formatBatch(array $records): mixed
    {
        foreach ($records as $key => $record) {
            $records[$key] = $this->format($record);
        }

        return $records;
    }

    
date_default_timezone_set(self::$timezone);
        putenv('TERMINAL_EMULATOR'.(self::$prevTerminalEmulator ? '='.self::$prevTerminalEmulator : ''));
    }

    /** * @dataProvider provideContext */
    public function testDescribe(array $context, string $expectedOutput, bool $decorated = false)
    {
        $output = new BufferedOutput();
        $output->setDecorated($decorated);
        $descriptor = new CliDescriptor(new CliDumper(fn ($s) => $s));

        $descriptor->describe($outputnew Data([[123]])$context + ['timestamp' => 1544804268.3668], 1);

        $this->assertStringMatchesFormat(trim($expectedOutput)str_replace(\PHP_EOL, "\n", trim($output->fetch())));
    }

    public static function provideContext()
    {
        yield 'source' => [
            [
                'source' => [
                    
private ?ClonerInterface $cloner;
    private \Closure $handler;

    public function __construct(OutputInterface $output, CliDumper $dumper = null, ClonerInterface $cloner = null)
    {
        $this->output = $output;
        $this->dumper = $dumper;
        $this->cloner = $cloner;

        if (class_exists(CliDumper::class)) {
            $this->handler = function D$var): string {
                $dumper = $this->dumper ??= new CliDumper(null, null, CliDumper::DUMP_LIGHT_ARRAY | CliDumper::DUMP_COMMA_SEPARATOR);
                $dumper->setColors($this->output->isDecorated());

                return rtrim($dumper->dump(($this->cloner ??= new VarCloner())->cloneVar($var)->withRefHandles(false), true));
            };
        } else {
            $this->handler = fn ($var): string => match (true) {
                null === $var => 'null',
                true === $var => 'true',
                false === $var => 'false',
                \is_string($var) => '"'.$var.'"',
                default => rtrim(print_r($var, true)),
            };
ob_start();
        $return = dump($var1, second: $var2, third: $var3);
        ob_end_clean();

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

    protected function setupVarDumper()
    {
        $cloner = new VarCloner();
        $dumper = new CliDumper('php://output');
        VarDumper::setHandler(function D$var) use ($cloner$dumper) {
            $dumper->dump($cloner->cloneVar($var));
        });
    }
}
use Symfony\Component\VarDumper\Dumper\CliDumper;
use Symfony\Component\VarDumper\Dumper\ContextProvider\SourceContextProvider;
use Symfony\Component\VarDumper\Dumper\ContextualizedDumper;

/** * @author Kévin Thérage <therage.kevin@gmail.com> */
class ContextualizedDumperTest extends TestCase
{
    public function testContextualizedCliDumper()
    {
        $wrappedDumper = new CliDumper('php://output');
        $wrappedDumper->setColors(true);

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

        ob_start();
        $dumper->dump($data);
        $out = ob_get_clean();

        
/** * @author Nicolas Grekas <p@tchwork.com> */
class CliDumperTest extends TestCase
{
    use VarDumperTestTrait;

    public function testGet()
    {
        require __DIR__.'/../Fixtures/dumb-var.php';

        $dumper = new CliDumper('php://output');
        $dumper->setColors(false);
        $cloner = new VarCloner();
        $cloner->addCasters([
            ':stream' => function D$res$a) {
                unset($a['uri']$a['wrapper_data']);

                return $a;
            },
            'Symfony\Component\VarDumper\Tests\Fixture\DumbFoo' => function D$foo$a) {
                $a['foo'] = new CutStub($a['foo']);

                

class TestVarDumper {

  /** * A CLI handler for \Symfony\Component\VarDumper\VarDumper. */
  public static function cliHandler($var) {
    $cloner = new VarCloner();
    $dumper = new CliDumper();
    fwrite(STDOUT, "\n");
    $dumper->setColors(TRUE);
    $dumper->dump(
      $cloner->cloneVar($var),
      function D$line$depth$indent_pad) {
        // A negative depth means "end of dump".         if ($depth >= 0) {
          // Adds a two spaces indentation to the line.           fwrite(STDOUT, str_repeat($indent_pad$depth) . $line . "\n");
        }
      }
    );
        if (!$this->requestStack
            || !$response->headers->has('X-Debug-Token')
            || $response->isRedirection()
            || ($response->headers->has('Content-Type') && !str_contains($response->headers->get('Content-Type') ?? '', 'html'))
            || 'html' !== $request->getRequestFormat()
            || false === strripos($response->getContent(), '</body>')
        ) {
            if ($response->headers->has('Content-Type') && str_contains($response->headers->get('Content-Type') ?? '', 'html')) {
                $dumper = new HtmlDumper('php://output', $this->charset);
                $dumper->setDisplayOptions(['fileLinkFormat' => $this->fileLinkFormat]);
            } else {
                $dumper = new CliDumper('php://output', $this->charset);
                if (method_exists($dumper, 'setDisplayOptions')) {
                    $dumper->setDisplayOptions(['fileLinkFormat' => $this->fileLinkFormat]);
                }
            }

            foreach ($this->data as $dump) {
                $this->doDump($dumper$dump['data']$dump['name']$dump['file']$dump['line']$dump['label'] ?? '');
            }
        }
    }

    
private ?ClonerInterface $cloner;
    private \Closure $handler;

    public function __construct(OutputInterface $output, CliDumper $dumper = null, ClonerInterface $cloner = null)
    {
        $this->output = $output;
        $this->dumper = $dumper;
        $this->cloner = $cloner;

        if (class_exists(CliDumper::class)) {
            $this->handler = function D$var): string {
                $dumper = $this->dumper ??= new CliDumper(null, null, CliDumper::DUMP_LIGHT_ARRAY | CliDumper::DUMP_COMMA_SEPARATOR);
                $dumper->setColors($this->output->isDecorated());

                return rtrim($dumper->dump(($this->cloner ??= new VarCloner())->cloneVar($var)->withRefHandles(false), true));
            };
        } else {
            $this->handler = fn ($var): string => match (true) {
                null === $var => 'null',
                true === $var => 'true',
                false === $var => 'false',
                \is_string($var) => '"'.$var.'"',
                default => rtrim(print_r($var, true)),
            };
$line = __LINE__ - 1;

        ob_start();
        $collector->__destruct();
        $output = preg_replace("/\033\[[^m]*m/", '', ob_get_clean());
        $this->assertSame("DumpDataCollectorTest.php on line {$line}:\n456\n", $output);
    }

    public function testFlushNothingWhenDataDumperIsProvided()
    {
        $data = new Data([[456]]);
        $dumper = new CliDumper('php://output');
        $collector = new DumpDataCollector(null, null, null, null, $dumper);

        ob_start();
        $collector->dump($data);
        $line = __LINE__ - 1;
        $output = preg_replace("/\033\[[^m]*m/", '', ob_get_clean());

        $this->assertSame("DumpDataCollectorTest.php on line {$line}:\n456\n", $output);

        ob_start();
        $collector->__destruct();
        
private static function register(): void
    {
        $cloner = new VarCloner();
        $cloner->addCasters(ReflectionCaster::UNSET_CLOSURE_FILE_INFO);

        $format = $_SERVER['VAR_DUMPER_FORMAT'] ?? null;
        switch (true) {
            case 'html' === $format:
                $dumper = new HtmlDumper();
                break;
            case 'cli' === $format:
                $dumper = new CliDumper();
                break;
            case 'server' === $format:
            case $format && 'tcp' === parse_url($format, \PHP_URL_SCHEME):
                $host = 'server' === $format ? $_SERVER['VAR_DUMPER_SERVER'] ?? '127.0.0.1:9912' : $format;
                $dumper = \in_array(\PHP_SAPI, ['cli', 'phpdbg'], true) ? new CliDumper() : new HtmlDumper();
                $dumper = new ServerDumper($host$dumper, self::getDefaultContextProviders());
                break;
            default:
                $dumper = \in_array(\PHP_SAPI, ['cli', 'phpdbg'], true) ? new CliDumper() : new HtmlDumper();
        }

        
Home | Imprint | This part of the site doesn't use cookies.