根据官方文档,有一种方法可以为自定义YAML标记提供回调:
mixed yaml_parse ( string $input [, int $pos = 0 [, int &$ndocs [, array $callbacks ]]] )
Run Code Online (Sandbox Code Playgroud)
回调
YAML节点的内容处理程序.YAML标记的关联数组=>回调映射.
但是,即使在扩展源中,似乎也没有关于该主题的其他文档!
我创建了这个脚本作为测试:
<?php
$yaml =<<<YAML
---
prop: !custom val
YAML;
print_r(yaml_parse($yaml,0,$n,array(
YAML_STR_TAG => function () {
echo "YAML_STR_TAG\n";
$args = func_get_args();
print_r($args);
return 'x';
},
'!custom' => function () {
echo "!custom\n";
$args = func_get_args();
print_r($args);
return 'y';
}
)));
Run Code Online (Sandbox Code Playgroud)
我得到了这个输出:
$ php yaml.php
YAML_STR_TAG
Array
(
[0] => prop
[1] => tag:yaml.org,2002:str
[2] => 1
)
!custom
Array
(
[0] => val
[1] => !custom
[2] => 1
)
Array
(
[x] => y
)
Run Code Online (Sandbox Code Playgroud)
从那以后我可以说几件事:
YAML_*_SCALAR_STYLE常量.任何人都可以确认此功能的预期行为吗?
经过大量研究和测试,我找到了一些答案。
正如在扩展的单元测试中发现的那样,每个回调都采用三个参数:
$data - 已解析的标记数据$tag - 标签名称,根据官方 YAML 标签规范进行扩展:
!custom!custom如果没有定义标签前缀则扩展为!custom扩展为prefixcustom,其中prefix是由文档元数据 定义的%TAG ! prefix。请注意,没有前导感叹号!!preset扩展为解析器定义的内部类型。查看YAML_*_TAG常数!<verbatim-tag> expands to 逐字标记`。请注意,没有前导感叹号。$style- 使用的标量样式。查看YAML_*_SCALAR_STYLE常数回调应该返回一个混合值供解析器发出。