简体   繁体   English

与 request->get() 一起提供的 Psalm 可能为空值

[英]Psalm possibly null value provided with request->get()

I have the following code:我有以下代码:

$request->headers->get('Accept-Language', 'en');

I provide a default value but Psalm thinks it's potentially null since ->get() declares that return a nullable string:我提供了一个默认值,但 Psalm 认为它可能为空,因为->get()声明返回一个可为空的字符串:

// vendor/symfony/http-foundation/HeaderBag.php
/**
 * Returns a header value by name.
 *
 * @return string|null The first header value or default value
 */
public function get(string $key, string $default = null) { /* */ }

How can I fix this so psalm knows it's not null?我该如何解决这个问题,以便 psalm 知道它不为空?

Since you cannot control the annotation in the upstream library, you'll have to provide the missing information to Psalm in your own code.由于您无法控制上游库中的注释,因此您必须在自己的代码中向 Psalm 提供缺少的信息。

A couple of ways to go about it:有几种方法可以解决这个问题:

Cast to string, so Psalm has no doubt what type get() is getting you:转换为字符串,因此 Psalm 毫无疑问get()正在为您提供什么类型:

$a = (string) $request->headers->get('Accept-Language', 'en');

Yup, the cast is redundant, but it's clear and concise.是的,演员阵容是多余的,但它清晰简洁。 I usually do this just for economy.我通常这样做只是为了经济。

You could explicitly declare that the variable that result of this get() call is a string:您可以明确声明此get()调用结果的变量是一个字符串:

/** @var string $acceptLanguage **/
$acceptLanguage = $request->headers->get('Accept-Language', 'en');

Finally, you can simply suppress the PossiblyNullArgument wherever you need it:最后,您可以在任何需要的地方简单地抑制PossiblyNullArgument

/** @psalm-suppress PossiblyNullArgument */
iWantAString($request->headers->get('Accept-Language', 'en'));

See all these working here .这里查看所有这些工作。

You can also combine some of the above with your own wrapper method to deal with getting values from the request, making sure you always return string.您还可以将上面的一些与您自己的包装器方法结合起来处理从请求中获取值,确保您始终返回字符串。 If you do that, you should probably throw an exception if the parameter is not found.如果你这样做,如果没有找到参数,你可能应该throw一个异常。

In addition to @yivi's answer that shows you how you can override type inference or suppress the error, you can also explain the type to Psalm by providing correct docblock using conditional types either directly in the source code (if you have control over that) or in a stub file .除了@ yivi的回答将告诉您如何可以覆盖类型推断或抑制的错误,你也可以通过提供一种使用正确的docblock解释型诗篇条件类型的源代码可以直接(如果你有超过对照)或在存根文件中

/**
 * Returns a header value by name.
 *
 * @psalm-return ($default is null ? (string|null) : string)
 */
public function get(string $key, string $default = null) { /* */ }

https://psalm.dev/r/41b8471847 https://psalm.dev/r/41b8471847

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM