Skip to content

yaml dumper with objects and magic method __debugInfo #49570

Closed as not planned
Closed as not planned
@hrvoj3e

Description

@hrvoj3e

Description

Yaml dumper should support dumping objects via magic method __debugInfo() like native PHP var_dump.

This could be another flag so it would be only opt-in.

What do you think?

Example

My code

$flags = Yaml::DUMP_NULL_AS_TILDE;
$flags |= Yaml::DUMP_OBJECT_AS_MAP;
$data = Yaml::dump($input, 5, 2, $flags);

Before:

ifHas:
  - parent-2
found:
  2: ~  # too bad to see only tilde (NULL value) when dump exists
tplData:
  - 'NN-MU 003/2009'

After:

ifHas:
  - parent-2
found:
  2: { type: ~, fi: ~, ri: 2575574, plain: 'NN-MU 003/2009' }
tplData:
  - 'NN-MU 003/2009'

My code patch was in lib/vendor/symfony/yaml/Inline.php on line 147 in method Inline::dump() in switch/case case \is_object($value):.

if (Yaml::DUMP_OBJECT_AS_MAP & $flags && ($value instanceof \stdClass || $value instanceof \ArrayObject)) {
    $output = [];

    foreach ($value as $key => $val) {
        $output[] = sprintf('%s: %s', self::dump($key, $flags), self::dump($val, $flags));
    }

    return sprintf('{ %s }', implode(', ', $output));
}
// ----> my patch to support __debugInfo()
elseif (Yaml::DUMP_OBJECT_AS_MAP & $flags && method_exists($value, '__debugInfo')) {
    $value = call_user_func([$value, '__debugInfo']);

    return self::dumpArray($value, $flags);
}

My class implements method __debugInfo() and prepares data to expose.

    public function __debugInfo()
    {
        $data = [
            'type' => $this->type,
            'fi' => $this->fi,
        ];
        if ($this->ri) {
            $data['ri'] = $this->ri;
        }

        return $data;
    }

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions