[英]Psalm: How to handle dedicated view files?
My set-up comprises a lib
folder with classes and a view
folder with PHP files, that produce output.我的设置包括一个带有类的
lib
文件夹和一个带有 PHP 文件的view
文件夹,这些文件产生 output。 The views are imported inside a View
class similar to this:视图导入到
View
class 中,类似于:
class View {
public function render(string $basename, Array $params) : string {
extract($params, EXTR_PREFIX_INVALID, 'v');
ob_start();
include sprintf('%s/views/%s.php', dirname(__DIR__), $basename);
$out = ob_get_contents();
ob_end_clean();
return $out;
}
}
I have basically two problems with Psalm in this situation:在这种情况下,我基本上对 Psalm 有两个问题:
For View::render
it reports a UnresolvableInclude
.对于
View::render
它报告一个UnresolvableInclude
。 I can even type the $basename
with something like我什至可以用类似的东西输入
$basename
@param "view1"|"view2"|"about" $basename
without effect.没有效果。 The unresolvable include remains.
无法解决的包含仍然存在。
The extract()
puts the content of $params
in the local scope, where the view files are included. extract()
将$params
的内容放在包含视图文件的本地 scope 中。 This allows me to have这让我有
<?=escape($foo)?>
“tags” in my view files with $params === ['foo' => 'bar']
.我的视图文件中的“标签”带有
$params === ['foo' => 'bar']
。 However, Psalm doesn't catch up on this and reports a lot of UndefinedGlobalVariable
problems.然而,Psalm 并没有赶上这一点,并报告了很多
UndefinedGlobalVariable
问题。
My question: How can I tell psalm about the view files and the variables?我的问题:如何告诉 psalm 有关视图文件和变量的信息? Or alternatively, how can I re-structure this code so that psalm can test it for me?
或者,我如何重新构建此代码以便 psalm 可以为我测试它?
There's a demo TemlateChecker plugin in Psalm's repo that seems to do something similar: it looks at the docblock in the view file for the tag like @variablesfrom ClassName::method
and makes them available in the template file.在 Psalm 的 repo 中有一个演示TemlateChecker 插件,它似乎做了类似的事情:它在视图文件中的 docblock 中查找
@variablesfrom ClassName::method
之类的标签,并使它们在模板文件中可用。 Or just properties on $this
variable from that method, not sure.或者只是该方法中
$this
变量的属性,不确定。 It's also mentioned in Psalm docs: Checking non-PHP files . Psalm 文档中也提到了这一点:检查非 PHP 文件。
Alternatively, you could wrap your template into a minimal method/function as technically view is just a function that takes a bunch of variables and returns a string: https://psalm.dev/r/66898ee87f或者,您可以将模板包装到最小的方法/函数中,因为从技术上讲,它只是一个 function ,它接受一堆变量并返回一个字符串: https://psalm.dev/r/66898ee87f
<?php class HomePageView { // view starts here
/** @param list<string> $sections */
public function render(
string $title,
array $sections
): string { ob_start();
?>
<html>
<head>
<title><?=$title?></title>
</head>
<body>
<?php foreach ($sections as $section): ?>
<section><?=$section?></section>
<?php endforeach; ?>
</body>
</html>
<?php return ob_get_contents(); }} // view ends here ?>
This way any tool that analyzes code (including Psalm, but not limited to) would be able to understand it.这样任何分析代码的工具(包括 Psalm,但不限于)都能够理解它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.