naugrim/laravel-strict-config-helper

确保您的配置返回正确的类型

1.1.0 2024-04-03 06:20 UTC

This package is auto-updated.

Last update: 2024-09-03 07:09:21 UTC


README

此包主要与 PHPStan 一起使用。

Laravel 的助手函数 config($key, $default) 返回 mixed 类型。在更高的 PHPStan 级别,您不能在 mixed 类型上执行某些操作。

示例

https://phpstan.org/r/39022f87-cbae-4e7b-bb44-8a4a655d2f00

<?php 

$value = config('foo');

if (strpos($value, 'bar')) {
  // do something	
}

这将产生以下错误

使用此包,您可以这样做

https://phpstan.org/r/0c0e3e10-2dbd-418b-966d-2930016d803d

$value = config_string('foo');

if (strpos($value, 'bar')) {
  // do something	
}

没有返回错误,因为 $value 保证是一个字符串。

如果配置中的值类型不正确,将抛出一个 RuntimeException

注意: 此包中的辅助函数不能返回 NULL。因此,如果您的配置中没有设置值并且您没有提供 $default 值,将抛出异常。

安装

composer require naugrim/laravel-strict-config-helper

可用函数

config_string(string $key, ?string $default = null): string
config_int(string $key, ?int $default = null): int
config_float(string $key, ?float $default = null): float
config_numeric(string $key, int | float | null $default = null): int | float
config_bool(string $key, ?bool $default = null): bool

IDE 配置键自动补全

如果您正在使用 PHPStorm 的出色 Laravel 插件,您可以在项目中创建一个名为 ide.json 的文件,并包含以下内容以实现配置键的自动补全

{
  "$schema": "https://laravel-ide.com/schema/laravel-ide-v2.json",
  "completions": [
    {
      "complete": "configKey",
      "condition": [
        {
          "functionNames": ["config_bool", "config_float", "config_int", "config_numeric", "config_string"],
          "parameters": [1]
        }
      ]
    }
  ]
}