Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Environment Laravel Package

sebastian/environment

sebastian/environment helps PHP libraries handle runtime-specific execution paths by detecting and describing the current environment (PHP version, features, etc.). Useful for writing portable code that adapts to different runtimes and configurations.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require --dev sebastian/environment
    

    Add as a dev dependency to avoid bloating production.

  2. First Use Case: Detect PHP version in a Laravel service or command:

    use SebastianBergmann\Environment\Runtime;
    
    $runtime = new Runtime();
    if ($runtime->isPhpVersion('8.1')) {
        // Enable PHP 8.1+ features
    }
    
  3. Key Classes:

    • Runtime: Core class for PHP/HHVM detection (e.g., isHhvm(), getPhpVersion()).
    • Environment: Detects OS, paths, and runtime capabilities (e.g., detect(), getOsFamily()).
    • Host: OS/host-specific checks (e.g., isLinux(), isWindows()).
  4. Where to Look First:


Implementation Patterns

Core Workflows

1. Runtime-Specific Feature Flags

Use Runtime to enable/disable features conditionally:

// In a Laravel service provider
if (app(Runtime::class)->isHhvm()) {
    $this->app->register(HhvmOptimizationServiceProvider::class);
}

2. CI/CD Enforcement

Fail builds or skip tests on unsupported runtimes:

// In a GitHub Action or PHPUnit bootstrap
if (!app(Runtime::class)->isPhpVersion('8.1')) {
    throw new \RuntimeException('PHP 8.1+ required');
}

3. Dynamic Configuration

Load environment-aware settings in config/app.php:

'php_version' => app(Runtime::class)->getPhpVersion(),
'opcache_enabled' => app(Runtime::class)->isOpcacheActive(),

4. Test Isolation

Skip or mark tests based on runtime:

// In a PHPUnit test case
public function testXdebugCoverage() {
    if (!app(Runtime::class)->canCollectCodeCoverage()) {
        $this->markTestSkipped('Xdebug not available');
    }
    // ...
}

5. Artisan Commands

Add runtime checks to CLI tools:

// In a custom Artisan command
protected function handle() {
    if (app(Runtime::class)->isWindows()) {
        $this->info('Windows-specific cleanup');
    }
}

6. Legacy HHVM Support

Gradually deprecate HHVM with warnings:

// In a middleware or service
if (app(Runtime::class)->isHhvm()) {
    Log::warning('HHVM detected; consider migrating to PHP');
}

Integration Tips

Laravel Service Container

Bind the Runtime class globally for dependency injection:

// In AppServiceProvider::boot()
$this->app->singleton(Runtime::class, fn() => new \SebastianBergmann\Environment\Runtime());

Facade Wrapper

Create a Laravel facade for team consistency:

// app/Facades/Environment.php
namespace App\Facades;

use Illuminate\Support\Facades\Facade;
use SebastianBergmann\Environment\Runtime;

class Environment extends Facade {
    protected static function getFacadeAccessor() {
        return Runtime::class;
    }

    // Add static methods for common checks
    public static function isPhp80(): bool {
        return static::getFacadeRoot()->isPhpVersion('8.0');
    }
}

Usage:

if (Environment::isPhp80()) { ... }

Dynamic Config Loading

Load runtime-specific config in AppServiceProvider:

public function boot() {
    $runtime = app(Runtime::class);
    config([
        'app.supported_php_versions' => $runtime->getSupportedPhpVersions(),
        'app.enable_opcache' => $runtime->isOpcacheActive(),
    ]);
}

PHPUnit Integration

Skip tests on unsupported runtimes:

// In a test trait or base test case
abstract class RuntimeAwareTestCase extends TestCase {
    protected function skipIfUnsupported(): void {
        if (!app(Runtime::class)->isPhpVersion('8.0')) {
            $this->markTestSkipped('PHP 8.0+ required');
        }
    }
}

Environment-Aware Logging

Log runtime details for debugging:

Log::debug('Runtime', [
    'php_version' => app(Runtime::class)->getPhpVersion(),
    'hhvm' => app(Runtime::class)->isHhvm(),
    'opcache' => app(Runtime::class)->isOpcacheActive(),
]);

Gotchas and Tips

Pitfalls

1. Deprecated Methods

  • Avoid Runtime::getBinary() and Runtime::getRawBinary() (deprecated in v8.0.0).
  • Use escapeshellarg(PHP_BINARY) or PHP_BINARY directly instead.

2. PHP Version Support

  • The package drops support for PHP 8.2+ in v9.0.0. Ensure your Laravel app’s PHP version aligns with the package version.
  • Check release notes for breaking changes.

3. HHVM-Specific Quirks

  • HHVM may return unexpected values for Runtime::getCurrentSettings(). Test thoroughly in HHVM environments.
  • Use Runtime::isHhvm() to guard HHVM-specific logic.

4. Non-TTY Warnings

  • Older versions (<9.0.0) may emit warnings in non-TTY environments. Update to the latest version if this is an issue.

5. Extension Detection

  • Runtime::hasExtension() may not detect all extensions correctly in some environments. Verify with extension_loaded() as a fallback:
    if (app(Runtime::class)->hasExtension('intl') || extension_loaded('intl')) { ... }
    

6. Path Handling

  • Environment::getPath() may return unexpected paths on Windows or custom PHP installations. Validate paths before use:
    $phpPath = app(Runtime::class)->getBinary();
    if (!file_exists($phpPath)) {
        throw new \RuntimeException("PHP binary not found at {$phpPath}");
    }
    

Debugging Tips

1. Inspect Runtime Details

Dump runtime info for debugging:

dd(app(Runtime::class)->getCurrentSettings());

2. Check for Deprecated Methods

Use static analysis (e.g., PHPStan) to catch deprecated method usage:

vendor/bin/phpstan analyse --level 7

3. Validate HHVM Detection

Test HHVM-specific logic in a HHVM environment:

if (app(Runtime::class)->isHhvm()) {
    dd('HHVM detected:', app(Runtime::class)->getHhvmVersion());
}

4. Handle Non-TTY Environments

Suppress warnings in CI/CD pipelines by updating the package or wrapping checks:

try {
    $runtime = new Runtime();
} catch (\SebastianBergmann\Environment\Exception $e) {
    Log::error('Environment detection failed', ['error' => $e->getMessage()]);
}

Extension Points

1. Custom Runtime Checks

Extend the Runtime class for project-specific checks:

class CustomRuntime extends \SebastianBergmann\Environment\Runtime {
    public function isLaravelSupported(): bool {
        return $this->isPhpVersion('8.0') && !$this->isHhvm();
    }
}

2. Override Environment Detection

Replace the default Environment detector for custom logic:

$environment = new \SebastianBergmann\Environment\Environment(
    new CustomDetector()
);

3. Add Custom Settings

Extend Runtime::getCurrentSettings() to include project-specific configs:

$settings = app(Runtime::class)->getCurrentSettings();
$settings['app.custom_setting'] = 'value';

4. Integrate with Laravel Events

Trigger events based on runtime detection:

// In AppServiceProvider::boot()
if (app(Runtime::class)->isPhpVersion('8.1')) {
    event(new Php81Detected);
}

5. **Custom Facade

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
ecotone/kafka
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata