permafrost-dev / code-snippets
轻松在PHP中使用代码片段
Requires
- php: ^7.3|^8.0
Requires (Dev)
README
轻松从任何类型的源代码文件中创建和操作代码片段。
该包所基于的原始代码是从 spatie/backtrace
包借用的。
安装
您可以通过composer安装此包
composer require permafrost-dev/code-snippets
用法
注意:虽然这里的示例引用了php文件,但在创建 CodeSnippet
时可以使用任何文件类型。
创建片段
使用 surroundingLine($num)
方法选择“目标”行,它将作为片段的中间行返回
use Permafrost\CodeSnippets\CodeSnippet; $snippet = (new CodeSnippet()) ->surroundingLine(4) ->snippetLineCount(6) ->fromFile('/path/to/a/file.php');
使用 surroundingLines($first, $last)
方法选择一系列“目标”行,这些行将作为片段的中间行返回
$snippet = (new CodeSnippet()) ->surroundingLines(4, 7) ->snippetLineCount(6) ->fromFile('/path/to/a/file.php');
使用 linesBefore()
和 linesAfter()
方法指定要显示在“目标”行之前和之后的上下文行数
// the "target" line isn't displayed in the middle, but as the second line $snippet = (new CodeSnippet()) ->surroundingLine(4) ->linesBefore(1) ->linesAfter(3) ->fromFile('/path/to/a/file.php');
获取片段内容
getLines()
方法返回一个 SnippetLine
实例数组。结果数组的键是行号。
SnippetLine
实例可以转换为字符串以显示值。当与 SnippetLine
实例一起工作时,请使用 isSelected()
来确定是否使用 CodeSnippet
实例上的 surroundingLine()
或 surroundingLines()
方法选择了该行。
要获取 SnippetLine
的值,请使用 value()
方法或将对象转换为字符串。
$snippet = (new CodeSnippet()) ->surroundingLine(4) ->snippetLineCount(5) ->fromFile('/path/to/a/file.php'); foreach($snippet->getLines() as $lineNum => $line) { $prefix = $line->isSelected() ? ' * ' : ' '; echo $prefix . $line->lineNumber() . ' - ' . $line->value() . PHP_EOL; }
片段行数
要确定片段中的行数,请使用 getSnippetLineCount()
方法
$snippet = (new CodeSnippet()) ->surroundingLines(4, 7) ->linesBefore(3) ->linesAfter(3) ->fromFile('/path/to/a/file.php'); echo "Snippet line count: " . $snippet->getSnippetLineCount() . PHP_EOL;
您也可以使用 count()
在 getLines()
方法的输出上
$snippet = (new CodeSnippet()) ->surroundingLines(4, 7) ->linesBefore(3) ->linesAfter(3) ->fromFile('/path/to/a/file.php'); echo "Snippet line count: " . count($snippet->getLines()) . PHP_EOL;
要返回包含片段行号的数组,请使用 getLineNumbers()
print_r($snippet->getLineNumbers());
将片段作为字符串返回
使用 toString()
方法或将片段直接转换为字符串以将片段内容作为字符串返回
$snippet = (new CodeSnippet()) ->surroundingLines(4, 7) ->linesBefore(3) ->linesAfter(3) ->fromFile('/path/to/a/file.php'); echo "Snippet: \n" . $snippet->toString() . PHP_EOL;
测试
./vendor/bin/phpunit
变更日志
有关最近更改的更多信息,请参阅 CHANGELOG
贡献
有关详细信息,请参阅 CONTRIBUTING
安全漏洞
请查看我们关于如何报告安全漏洞的安全策略 我们的安全策略
致谢
许可
MIT许可(MIT)。有关更多信息,请参阅 许可文件