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

Runtime environment helper for PHP projects. Detects PHP/HHVM runtime specifics so you can choose safe execution paths, handle version and platform differences, and write portable code with minimal conditionals—useful in libraries and test tooling.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package (dev dependency for CLI tools):
    composer require --dev sebastian/environment
    
  2. First use case: Replace manual TTY checks in an Artisan command:
    use SebastianBergmann\Environment\Host;
    
    class MyCommand extends Command {
        protected function configure() {
            $this->getOutput()->setDecorated(Host::supportsColor());
        }
    }
    
  3. Key classes to explore:
    • Host: For terminal/color detection (supportsColor(), getEnvironmentVariable()).
    • Runtime: For PHP runtime checks (isCli(), canCollectCodeCoverage(), isOpcacheActive()).

Where to Look First

  • Host Class: Core for CLI output (colors, TTY).
  • Runtime Class: PHP environment checks (Xdebug, opcache, SAPI).
  • Changelog: Note FORCE_COLOR (v9.2.0) and PHP 8.3+ support.

Implementation Patterns

Core Workflows

1. Terminal Output Standardization

  • Pattern: Use Host::supportsColor() in all CLI tools (Artisan, Pest, custom scripts).
    if (Host::supportsColor()) {
        $this->info('<fg=green>Success!</>');
    }
    
  • CI/CD Integration: Force colors in workflows:
    # GitHub Actions
    env:
      FORCE_COLOR: "1"
    
  • Docker/Laravel Sail: Override TTY detection:
    if (Host::getEnvironmentVariable('FORCE_COLOR') === '0') {
        putenv('FORCE_COLOR=1'); // Force colors in containers
    }
    

2. Runtime-Specific Logic

  • Pattern: Use Runtime for conditional execution paths.
    if (Runtime::isCli()) {
        // CLI-only logic (e.g., Artisan commands)
    }
    
    if (Runtime::canCollectCodeCoverage()) {
        // Enable Xdebug coverage
    }
    
  • Opcache Detection:
    if (Runtime::isOpcacheActive()) {
        $this->warn('Opcache is enabled. Clear it for testing.');
    }
    

3. Environment Variable Handling

  • Pattern: Read custom env vars (e.g., APP_DEBUG, FORCE_COLOR).
    $debugMode = Host::getEnvironmentVariable('APP_DEBUG') === 'true';
    $forceColor = Host::getEnvironmentVariable('FORCE_COLOR') === '1';
    

4. Laravel-Specific Integrations

  • Artisan Commands:
    use Illuminate\Support\Command;
    use SebastianBergmann\Environment\Host;
    
    class DeployCommand extends Command {
        protected function configure() {
            $this->getOutput()->setDecorated(Host::supportsColor());
        }
    }
    
  • PestPHP Tests:
    beforeAll(function () {
        if (!Host::supportsColor()) {
            putenv('FORCE_COLOR=1'); // Ensure CI has colors
        }
    });
    

Integration Tips

  • Symfony Console Compatibility: Works seamlessly with Laravel’s Illuminate\Support\Console (backed by Symfony).
  • Legacy Code: Use Runtime::isCli() instead of PHP_SAPI === 'cli' for broader SAPI support (e.g., PHP-CGI).
  • Performance: Methods like Host::supportsColor() are lazy-loaded—no runtime overhead in non-CLI contexts.
  • Testing: Mock Host/Runtime in unit tests:
    $host = $this->createMock(Host::class);
    $host->method('supportsColor')->willReturn(true);
    

Gotchas and Tips

Pitfalls

  1. PHP Version Mismatch:

    • Error: Class 'SebastianBergmann\Environment\Host' not found if using PHP <8.2.
    • Fix: Use ^8.0 for PHP 8.2–8.3 (no FORCE_COLOR support).
    • Laravel Compatibility:
      • Laravel 10+ (PHP 8.3+): Use ^9.2.
      • Laravel 9.x (PHP 8.2): Use ^8.0.
  2. Deprecated Methods:

    • Error: Runtime::getBinary() or getRawBinary() triggers deprecation warnings.
    • Fix: Replace with escapeshellarg(PHP_BINARY) or PHP_BINARY.
  3. TTY Detection in Docker:

    • Issue: Host::supportsColor() may return false in non-interactive Docker containers.
    • Fix: Set FORCE_COLOR=1 in your Dockerfile or CI:
      ENV FORCE_COLOR=1
      
  4. Xdebug Coverage Edge Cases:

    • Issue: Runtime::canCollectCodeCoverage() may return false even when Xdebug is enabled (e.g., in CI).
    • Fix: Explicitly check extension_loaded('xdebug') if needed.
  5. Windows CMD Quirks:

    • Issue: Color support may behave differently in Windows CMD vs. PowerShell.
    • Fix: Use Host::supportsColor() (handles Windows-specific logic internally).

Debugging Tips

  • Verify FORCE_COLOR:
    echo Host::getEnvironmentVariable('FORCE_COLOR'); // Check current value
    
  • Inspect Runtime:
    var_dump([
        'isCli' => Runtime::isCli(),
        'supportsColor' => Host::supportsColor(),
        'opcacheActive' => Runtime::isOpcacheActive(),
    ]);
    
  • CI/CD Debugging: Add this to your workflow to force colors:
    env:
      FORCE_COLOR: "1"
      APP_DEBUG: "true"
    

Extension Points

  1. Custom Environment Variables: Extend Host to read project-specific vars:
    $customVar = Host::getEnvironmentVariable('MY_CUSTOM_VAR', 'default');
    
  2. Override TTY Detection: Subclass Host for custom logic:
    class CustomHost extends Host {
        public function supportsColor(): bool {
            return parent::supportsColor() || $this->isCustomCondition();
        }
    }
    
  3. Add Runtime Checks: Extend Runtime for project-specific needs:
    Runtime::registerCustomCheck('my_check', fn() => someLogic());
    
  4. Laravel Service Provider: Bind the package to the container for dependency injection:
    $this->app->singleton(Host::class, fn() => new Host());
    

Configuration Quirks

  • FORCE_COLOR Priority: The package respects FORCE_COLOR over TTY detection. Set it in CI to enforce colors:
    FORCE_COLOR=1 php artisan test
    
  • NO_COLOR Support: While not natively supported, you can manually check:
    if (Host::getEnvironmentVariable('NO_COLOR') === '1') {
        putenv('FORCE_COLOR=0');
    }
    
  • Case Sensitivity: Environment variables are case-insensitive (e.g., FORCE_COLOR = force_color). Use Host::getEnvironmentVariable() for consistency.

Performance Notes

  • Lazy Loading: All methods are stateless and cache results internally. No performance impact in non-CLI contexts.
  • Memory: Minimal overhead (~50KB footprint). Safe for dev dependencies.
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport