有许多用于PHP的“编码工具标准”,但是我一直在尝试使用phpcbf和php-cs-fixer,但是它们给我的效果并不理想。
例如(缩进不良...非常糟糕的缩进):
<?php
// A example with a horrific indentation
$title = 'This is the title';
$rows = array(array('aaa', 'bbb', 'ccc'),
array('ddd', 'eee', 'fff'),
array('ggg', 'hhh', 'iii'));
function print_rows($rows) {
foreach ($rows as $row) {
?>
<tr>
<?php
foreach ($row as $cell) {
?>
<td><?=$cell?></td>
<?php
}
?>
</tr>
<?php
}
}
?>
<html>
<head>
<title>A example with a horrific indentation
</title>
</head>
<body>
<h1>
<?php
echo $title;?></h1>
<table border="1">
<?php print_rows($rows);?>
</table>
</body>
</html>
预期结果应该是(或接近):
<?php
// A example with a horrific indentation
$title = 'This is the title';
$rows = array(
array('aaa', 'bbb', 'ccc'),
array('ddd', 'eee', 'fff'),
array('ggg', 'hhh', 'iii'));
function print_rows($rows) {
foreach ($rows as $row) {
?>
<tr>
<?php
foreach ($row as $cell) {
?>
<td><?=$cell?></td>
<?php
}
?>
</tr>
<?php
}
}
?>
<html>
<head>
<title>A example with a horrific indentation</title>
</head>
<body>
<h1>
<?php
echo $title;
?>
</h1>
<table border="1">
<?php print_rows($rows);?>
</table>
</body>
</html>
但是使用php-cs-fixer的输出是:
$ php-cs-fixer fix example.php --rules=@PSR2
是:
<?php
// A example with a horrific indentation
$title = 'This is the title';
$rows = array(array('aaa', 'bbb', 'ccc'),
array('ddd', 'eee', 'fff'),
array('ggg', 'hhh', 'iii'));
function print_rows($rows)
{
foreach ($rows as $row) {
?>
<tr>
<?php
foreach ($row as $cell) {
?>
<td><?=$cell?></td>
<?php
} ?>
</tr>
<?php
}
}
?>
<html>
<head>
<title>A example with a horrific indentation
</title>
</head>
<body>
<h1>
<?php
echo $title;?></h1>
<table border="1">
<?php print_rows($rows);?>
</table>
</body>
</html>
并且使用phpcbf是:
<?php
// A example with a horrific indentation
$title = 'This is the title';
$rows = array(array('aaa', 'bbb', 'ccc'),
array('ddd', 'eee', 'fff'),
array('ggg', 'hhh', 'iii'));
function print_rows($rows)
{
foreach ($rows as $row) {
?>
<tr>
<?php
foreach ($row as $cell) {
?>
<td><?=$cell?></td>
<?php
}
?>
</tr>
<?php
}
}
?>
<html>
<head>
<title>A example with a horrific indentation
</title>
</head>
<body>
<h1>
<?php
echo $title;?></h1>
<table border="1">
<?php print_rows($rows);?>
</table>
</body>
</html>
这两个工具仅格式化/缩进PHP代码,但对于内联html则没有任何作用。