My use case is to show Yaml in <pre>
and that is it. VarDumper is to verbose.
I think maybe we should not focus on my use case but on the fact that object (except stdClass and ArrayObject) are represented in Yaml as NULL and there is a simple solution to this inconvenience.
Using __debugInfo()
is optional to use so when combined with new potential flag Yaml::DUMP_OBJECT_DEBUGINFO
(or something like that) this would not change the current logic.
What are the arguments to not implement this? Hope your team will consider this or put on internal discussion at least.
Hm... But that is the purpose of __debugInfo()
. To expose only needed data for debug/dump. Just an alternative to serializing whole objects which can be huge (e.g. some collection Dto could expose only count and some stats about collection).
OK, maybe this is a usage edge case but it would be useful in my day-to-day. That is way I propose it to be only opt-in.
I patched my local dev version and it works fine. Dumps/logs make more sense now. I used var_export() before but the array syntax is to verbose to read/display - yaml is more concise.
Yaml dumper should support dumping objects via magic method __debugInfo()
like native PHP var_dump
.
This method is called by var_dump() when dumping an object to get the properties that should be shown. If the method isn't defined on an object, then all public, protected and private properties will be shown.
This could be another flag so it would be only opt-in.
What do you think?
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'
May 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 && (is_object($value) && 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;
}