PHP code example of dev-kraken / env-validator

1. Go to this page and download the library: Download dev-kraken/env-validator library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

dev-kraken / env-validator example snippets


use EnvValidator\Facades\EnvValidator;

// Validate with default Laravel rules
EnvValidator::validate();

// Use preset for different scenarios
EnvValidator::useProductionRules()->validate();
EnvValidator::useMinimalRules()->validate();
EnvValidator::useApiRules()->validate();

use EnvValidator\EnvValidator;

// Simple validation with string rules
$rules = [
    'APP_ENV' => 'string',
    'DB_PASSWORD' => 'd:\n";
    foreach ($result as $field => $errors) {
        foreach ($errors as $error) {
            echo "  • $error\n";
        }
    }
    exit(1);
}

echo "✅ Environment validation passed!\n";

use EnvValidator\EnvValidator;
use EnvValidator\Collections\StringRules\{InRule, BooleanRule};
use EnvValidator\Collections\NetworkRules\UrlRule;

$validator = new EnvValidator();
$validator->setRules([
    'APP_ENV' => ['Rules());

if ($result !== true) {
    // Handle validation errors
    foreach ($result as $field => $errors) {
        foreach ($errors as $error) {
            echo "Error: $error\n";
        }
    }
    exit(1);
}

echo "✅ Environment validation passed!\n";

// All these formats work for 'ing',                       // String format
    'DB_PASSWORD' => ['dalone validation
$result = EnvValidator::validateStandalone($_ENV, $rules);

if ($result !== true) {
    // Handle validation errors
    foreach ($result as $field => $errors) {
        echo "Error in $field: " . implode(', ', $errors) . "\n";
    }
}

// Laravel application
$validator = (new EnvValidator())->usePreset('laravel');

// Microservice
$validator = (new EnvValidator())->usePreset('microservice');

// Production deployment
$validator = (new EnvValidator())->useProductionRules();

// Custom combination
$validator = (new EnvValidator())
    ->useMinimalRules()
    ->addRule('CUSTOM_API_KEY', ['

use EnvValidator\Collections\StringRules\{InRule, BooleanRule};
use EnvValidator\Collections\NetworkRules\UrlRule;

$rules = [
    'APP_ENV' => ['

use EnvValidator\Core\AbstractRule;

class CustomRule extends AbstractRule
{
    public function passes($attribute, $value): bool
    {
        return str_starts_with($value, 'custom_');
    }

    public function message(): string
    {
        return 'The :attribute must start with "custom_".';
    }
}

// Usage
$validator->addRule('CUSTOM_FIELD', [new CustomRule()]);

// Development environment
if (app()->environment('local', 'development')) {
    $validator->useMinimalRules();
} else {
    // Production environment
    $validator->useProductionRules();
}

$rules = [
    'DB_HOST' => ['nless:DB_CONNECTION,sqlite', new PortRule()],
    'REDIS_HOST' => ['

use EnvValidator\Services\EnvExampleSyncService;
use EnvValidator\Facades\EnvSync;

// Using the facade
$report = EnvSync::getSyncReport();
if ($report['status'] !== 'synced') {
    // Handle out-of-sync files
    $result = EnvSync::syncToExample(['generate_values' => true]);
}

// Using the service directly
$syncService = new EnvExampleSyncService();
$report = $syncService->getSyncReport();

// Check specific conditions
if ($syncService->envFileExists() && !$syncService->exampleFileExists()) {
    // Create .env.example from .env
    $syncService->syncToExample(['generate_values' => true]);
}

// Get validation rule suggestions for new keys
$comparison = $syncService->compareFiles();
$suggestedRules = $syncService->suggestValidationRules(
    $comparison['missing_in_example']
);

use EnvValidator\Services\EnvExampleSyncService;

// IMPORTANT: Always provide explicit paths in standalone PHP
$syncService = new EnvExampleSyncService(
    __DIR__ . '/.env',           // Path to your .env file
    __DIR__ . '/.env.example'    // Path to your .env.example file
);

// Check synchronization status
$report = $syncService->getSyncReport();
if ($report['status'] !== 'synced') {
    echo "⚠️  Environment files are out of sync!\n";

    // Show what's missing
    foreach ($report['missing_in_example'] as $category => $keys) {
        echo "Missing {$category} keys: " . implode(', ', array_keys($keys)) . "\n";
    }

    // Auto-sync files
    $result = $syncService->syncToExample([
        'add_missing' => true,
        'remove_extra' => true,
        'generate_values' => true
    ]);

    if ($result['success']) {
        echo "✅ Files synchronized successfully!\n";
    }
}

// Integration with validation
$rules = [
    'APP_ENV' => '

// Current directory
$syncService = new EnvExampleSyncService(
    getcwd() . '/.env',
    getcwd() . '/.env.example'
);

// Config directory
$syncService = new EnvExampleSyncService(
    getcwd() . '/config/.env',
    getcwd() . '/config/.env.example'
);

// Absolute paths
$syncService = new EnvExampleSyncService(
    '/var/www/app/.env',
    '/var/www/app/.env.example'
);

// Custom file names
$syncService = new EnvExampleSyncService(
    getcwd() . '/environment.conf',
    getcwd() . '/environment.example.conf'
);

#!/usr/bin/env php

// deployment.php
ervice;
use EnvValidator\EnvValidator;

echo "🚀 Deployment: Environment Check\n";

// 1. Check environment sync
$syncService = new EnvExampleSyncService(__DIR__ . '/.env', __DIR__ . '/.env.example');
$report = $syncService->getSyncReport();

if ($report['status'] !== 'synced') {
    echo "❌ ERROR: Environment files are out of sync!\n";
    echo "Missing keys: " . count($report['missing_in_example'] ?? []) . "\n";
    echo "Extra keys: " . count($report['extra_in_example'] ?? []) . "\n";
    exit(1);
}

// 2. Validate environment
$rules = [
    'APP_ENV' => '

// config/env-validator.php
return [
    'validate_on_boot' => ['APP_KEY', 'APP_ENV'], // Validate on app boot
    'rules' => [
        'CUSTOM_VAR' => ['

use EnvValidator\Facades\EnvValidator;

// Method chaining
EnvValidator::useProductionRules()
    ->addRule('API_KEY', ['

// E-commerce application
$validator = (new EnvValidator())
    ->usePreset('laravel')
    ->addRules([
        'STRIPE_KEY' => ['
// Microservice with health checks
$validator = (new EnvValidator())
    ->usePreset('microservice')
    ->addRules([
        'HEALTH_CHECK_ENDPOINT' => ['resets::minimal(),
    default => DefaultRulePresets::laravel(),
};
bash
php artisan vendor:publish --provider="EnvValidator\EnvValidatorServiceProvider" --tag="config"
bash
# In your CI/CD pipeline
php artisan env:sync --check
if [ $? -ne 0 ]; then
    echo "❌ Environment files are out of sync!"
    echo "Run 'php artisan env:sync' to fix."
    exit 1
fi
bash
# Run comprehensive examples
php examples/comprehensive_examples.php

# Explore (Laravel)
php examples/env_sync_examples.php

# Standalone PHP environment sync demos
php examples/standalone_env_sync_examples.php

# See preset system in action
php examples/preset_examples.php