永不说最终.. 哈.. 最后.. 或者...
发布: (2026年4月23日 GMT+8 22:21)
1 分钟阅读
原文: Dev.to
Source: Dev.to
原始代码
$class_names = wrap($data)
->tryProp('page_config')
->bind(function (Lst $x) {
return $x->filter(function ($y) {
return $y['_type'] === 'header';
})
->tryHead();
})
->bind(function ($x) {
return $x->tryProp('header_attrs');
})
->bind(function ($x) {
return $x->filter(function ($y) {
return $y['_type'] === 'class';
})
->tryHead();
})
->bind(function ($x) {
return $x->tryProp('class');
})
->getOrElse('');
重复的模式
->tryProp('page_config')
->bind(function (Lst $x) {
return $x->filter(function ($y) {
return $y['_type'] === 'header';
})
->tryHead();
})
使用 propEquals 重构
->bind(fn (Lst $x)
=> $x->filter(propEquals('_type', 'header'))
->tryHead())
最终重构版本
$class_names = wrap($data)
->tryProp('page_config')
->bind(fn (Lst $x) => $x->filter(propEquals('_type', 'header'))->tryHead())
->bind(fn (Kvm $x) => $x->tryProp('header_attrs'))
->bind(fn (Lst $x) => $x->filter(propEquals('_type', 'class'))->tryHead())
->bind(fn (Kvm $x) => $x->tryProp('class'))
->getOrElse('');