philiprehberger/env-validator 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

philiprehberger/env-validator

Composer 安装命令:

composer require philiprehberger/env-validator

包简介

Validate required environment variables with type checking and defaults

README 文档

README

Tests Latest Version on Packagist Last updated

Validate required environment variables with type checking and defaults.

Requirements

  • PHP 8.2+

Installation

composer require philiprehberger/env-validator

Usage

Required Variables

Check that environment variables are present:

use PhilipRehberger\EnvValidator\EnvValidator;

$result = EnvValidator::required(['APP_KEY', 'DATABASE_URL', 'REDIS_HOST'])
    ->validate();

if (!$result->passed) {
    echo 'Missing: ' . implode(', ', $result->missing);
}

Schema with Type Rules

Define variables with type validation in a single call:

$result = EnvValidator::schema([
    'APP_PORT' => 'int',
    'APP_DEBUG' => 'bool',
    'APP_URL' => 'url',
    'ADMIN_EMAIL' => 'email',
])->validate();

Default Values

Provide fallback values for variables that may not be set:

$result = EnvValidator::required(['APP_PORT', 'APP_ENV'])
    ->defaults([
        'APP_PORT' => '8080',
        'APP_ENV' => 'production',
    ])
    ->validate();

Optional Variables

Optional variables generate warnings but do not cause validation failure:

$result = EnvValidator::required(['DATABASE_URL'])
    ->optional(['CACHE_DRIVER', 'QUEUE_CONNECTION'])
    ->validate();

// $result->warnings contains notices about unset optional vars

Type Validation

Add type rules to individual variables:

$result = EnvValidator::required(['API_PORT', 'API_URL'])
    ->type('API_PORT', 'int')
    ->type('API_URL', 'url')
    ->validate();

Validate or Fail

Throw an exception if validation fails:

use PhilipRehberger\EnvValidator\Exceptions\EnvValidationException;

try {
    EnvValidator::required(['APP_KEY', 'DATABASE_URL'])
        ->validateOrFail();
} catch (EnvValidationException $e) {
    echo $e->getMessage();
    // Access the full result
    $result = $e->result;
}

IP Validation

Validate IP addresses with specific version constraints:

$result = EnvValidator::required(['SERVER_IP', 'GATEWAY_V4', 'GATEWAY_V6'])
    ->type('SERVER_IP', 'ip')
    ->type('GATEWAY_V4', 'ipv4')
    ->type('GATEWAY_V6', 'ipv6')
    ->validate();

Custom Validation Rules

Define your own validation logic with a callable:

$result = EnvValidator::required(['APP_SECRET'])
    ->custom('APP_SECRET', fn (string $value) => strlen($value) >= 32, 'Secret must be at least 32 characters.')
    ->validate();

Enum Validation

Validate that a value matches one of a backed enum's cases:

enum Environment: string
{
    case Production = 'production';
    case Staging = 'staging';
    case Development = 'development';
}

$result = EnvValidator::required(['APP_ENV'])
    ->enum('APP_ENV', Environment::class)
    ->validate();

Dependency Rules

Make variables conditionally required based on other variables:

// DB_HOST is only required when DB_DRIVER is set
$result = EnvValidator::required(['DB_DRIVER', 'DB_HOST'])
    ->dependsOn('DB_HOST', 'DB_DRIVER')
    ->validate();

// REDIS_HOST is required when CACHE_DRIVER equals "redis"
$result = EnvValidator::required(['CACHE_DRIVER', 'REDIS_HOST'])
    ->requiredIf('REDIS_HOST', 'CACHE_DRIVER', 'redis')
    ->validate();

// APP_SECRET is required unless APP_ENV equals "local"
$result = EnvValidator::required(['APP_ENV', 'APP_SECRET'])
    ->requiredUnless('APP_SECRET', 'APP_ENV', 'local')
    ->validate();

.env File Parsing

Validate a .env file without loading it into the environment:

$result = EnvValidator::fromFile('/path/to/.env')
    ->type('APP_PORT', 'int')
    ->type('APP_URL', 'url')
    ->validate();

The parser handles comments, quoted values, multiline values, export prefix, and ${VAR} interpolation.

Environment Profiles

Register named validation profiles for different environments:

// Register profiles
EnvValidator::profile('web', [
    'APP_URL' => 'url',
    'APP_PORT' => 'int',
    'APP_DEBUG' => 'bool',
]);

EnvValidator::profile('worker', [
    'QUEUE_CONNECTION' => 'string',
    'REDIS_HOST' => 'string',
]);

// Validate against a profile
$result = EnvValidator::validateProfile('web');

Supported Types

Type Description
string Always passes (any string value)
int, integer Numeric digits, optionally prefixed with -
float, number Any numeric value (uses is_numeric)
bool, boolean true, false, 1, 0, yes, no (case-insensitive)
url Valid URL (uses FILTER_VALIDATE_URL)
email Valid email (uses FILTER_VALIDATE_EMAIL)
ip Valid IP address (uses FILTER_VALIDATE_IP)
ipv4 Valid IPv4 address
ipv6 Valid IPv6 address
json Valid JSON string

API

EnvValidator

Method Description
required(array $vars): PendingValidation Define required environment variables
schema(array $rules): PendingValidation Define variables with type rules
fromFile(string $path): PendingFileValidation Validate a .env file without loading it
profile(string $name, array $schema): void Register a named validation profile
validateProfile(string $name): ValidationResult Validate against a named profile

PendingValidation

Method Description
optional(array $vars): self Add optional variables (warnings only)
defaults(array $defaults): self Set default values for missing variables
type(string $var, string $type): self Add a type rule for a variable
custom(string $var, callable $validator, string $message = ''): self Add a custom validation rule
enum(string $var, string $enumClass): self Validate against a backed enum
dependsOn(string $var, string $dependency): self Require variable only when dependency is set
requiredIf(string $var, string $conditionVar, mixed $value): self Require variable when condition equals value
requiredUnless(string $var, string $conditionVar, mixed $value): self Require variable unless condition equals value
validate(): ValidationResult Run validation and return result
validateOrFail(): void Run validation, throw on failure

ValidationResult

Property Type Description
passed bool Whether validation passed
missing array<string> List of missing required variables
invalid array<string, string> Map of variable names to error messages
warnings array<string> List of warning messages
toArray() array Convert result to array

Development

composer install
vendor/bin/phpunit
vendor/bin/pint --test
vendor/bin/phpstan analyse

Support

If you find this project useful:

Star the repo

🐛 Report issues

💡 Suggest features

❤️ Sponsor development

🌐 All Open Source Projects

💻 GitHub Profile

🔗 LinkedIn Profile

License

MIT

philiprehberger/env-validator 适用场景与选型建议

philiprehberger/env-validator 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 58 次下载、GitHub Stars 达 1, 最近一次更新时间为 2026 年 03 月 13 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「validator」 「validation」 「environment」 「env」 「dotenv」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 philiprehberger/env-validator 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 philiprehberger/env-validator 我们能提供哪些服务?
定制开发 / 二次开发

基于 philiprehberger/env-validator 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 58
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 1
  • 点击次数: 33
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 1
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2026-03-13