Debug Formatter Helper
DebugFormatterHelper 提供了在运行外部程序(例如进程或 HTTP 请求)时输出调试信息的功能。例如,如果您使用它来输出运行 figlet symfony
的结果,它可能会输出如下内容:

使用 debug_formatter
格式化器包含在默认的助手集中,您可以通过调用 getHelper() 来获取它。
1
$debugFormatter = $this->getHelper('debug_formatter');
格式化器接受字符串并返回格式化后的字符串,然后您可以将其输出到控制台(甚至记录信息或执行其他任何操作)。
此助手的所有方法都将标识符作为第一个参数。这是每个程序的唯一值。这样,助手可以同时调试多个程序的信息。当使用 Process 组件 时,您可能想要使用 spl_object_hash。
提示
此信息通常过于冗长,默认情况下不显示。您可以使用 verbosity levels 仅在调试模式下 (-vvv
) 显示它。
启动程序
一旦您启动程序,您可以使用 start() 来显示程序已启动的信息
1 2 3 4 5 6 7 8 9
// ...
$process = new Process(...);
$output->writeln($debugFormatter->start(
spl_object_hash($process),
'Some process description'
));
$process->run();
这将输出
1
RUN Some process description
您可以使用第三个参数调整前缀
1 2 3 4 5 6 7
$output->writeln($debugFormatter->start(
spl_object_hash($process),
'Some process description',
'STARTED'
));
// will output:
// STARTED Some process description
输出进度信息
有些程序在运行时会给出输出。可以使用 progress() 显示此信息
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
use Symfony\Component\Process\Process;
// ...
$process = new Process(...);
$process->run(function (string $type, string $buffer) use ($output, $debugFormatter, $process): void {
$output->writeln(
$debugFormatter->progress(
spl_object_hash($process),
$buffer,
Process::ERR === $type
)
);
});
// ...
如果成功,这将输出
1
OUT The output of the process
如果失败,则会输出
1
ERR The output of the process
第三个参数是一个布尔值,它告诉函数输出是否是错误输出。当 true
时,输出被认为是错误输出。
第四个和第五个参数允许您分别覆盖正常输出和错误输出的前缀。
停止程序
当程序停止时,您可以使用 stop() 来通知用户
1 2 3 4 5 6 7 8
// ...
$output->writeln(
$debugFormatter->stop(
spl_object_hash($process),
'Some command description',
$process->isSuccessful()
)
);
这将输出
1
RES Some command description
如果失败,这将以红色显示,如果成功,则以绿色显示。
使用多个程序
如前所述,您也可以使用助手同时显示更多程序。有关不同程序的信息将以不同的颜色显示,以清楚地表明哪个输出属于哪个命令。
这项工作,包括代码示例,根据 Creative Commons BY-SA 3.0 许可获得许可。