selfphp/env-schema

Validate .env environment variables in PHP using a declarative schema.

Installs: 1

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Watchers: 0

Forks: 0

Open Issues: 0

pkg:composer/selfphp/env-schema

v1.0.0 2025-05-28 08:59 UTC

This package is auto-updated.

Last update: 2025-11-28 10:15:40 UTC


README

env-schema is a lightweight PHP library for validating .env files using a declarative schema.

โœ… Features

  • Validate environment variables at runtime
  • Supports types: string, int, bool, float
  • Optional fields with default
  • Required fields with required
  • Allowed values (allowed) and regex (pattern) checks
  • Fully tested (PHPUnit 12)
  • No dependencies

๐Ÿ“ฆ Installation

composer require selfphp/env-schema

๐Ÿงช Usage

.env

APP_ENV=production
DEBUG=true
PORT=8080
APP_SECRET=abcd1234efgh5678ijkl9012mnop3456

schema.php

use Selfphp\EnvSchema\EnvSchema;

$schema = [
    'APP_ENV' => [
        'type' => 'string',
        'default' => 'production',
        'allowed' => ['dev', 'test', 'production'],
    ],
    'DEBUG' => [
        'type' => 'bool',
        'default' => false,
    ],
    'PORT' => [
        'type' => 'int',
        'required' => true,
    ],
    'APP_SECRET' => [
        'type' => 'string',
        'pattern' => '/^[A-Za-z0-9]{32}$/',
        'required' => true,
    ],
];

$validatedEnv = EnvSchema::validate($schema, __DIR__ . '/.env');

echo $validatedEnv['PORT']; // 8080

๐Ÿ“ Example Files

  • .env โ€“ runtime environment
  • .env.example โ€“ template for others
  • .gitignore โ€“ excludes secrets

๐Ÿ“„ License

MIT License ยฉ2025 SELFPHP - Damir Enseleit

๐Ÿ–ฅ๏ธ Run CLI Example

You can quickly test your .env file and schema using the provided example script:

php examples/validate-env.php

This script:

  • Loads a predefined schema
  • Parses your .env file
  • Outputs all validated values or detailed error messages

Example Output

โœ… .env file is valid.
APP_ENV = 'production'
DEBUG = true
PORT = 8080
APP_SECRET = 'abcd1234efgh5678ijkl9012mnop3456'

If validation fails, you'll see helpful errors like:

โŒ Validation error: Missing required variable: PORT

โ„น๏ธ Make sure to install dependencies first via composer install.