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 developers detect runtime details (PHP vs HHVM, OS, architecture, 32/64-bit, debugging extensions) to choose runtime-specific execution paths. Commonly used by testing tools to adapt behavior to the environment.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require --dev sebastian/environment
    

    (Use --dev if only needed for testing/validation.)

  2. First Use Case: Detect the runtime environment in a Laravel service or Artisan command:

    use SebastianBergmann\Environment\Runtime;
    
    if (Runtime::isHhvm()) {
        // HHVM-specific logic (e.g., legacy compatibility)
        Log::warning('HHVM detected; enabling polyfills.');
    }
    
    if (Runtime::isPhp74()) {
        // PHP 7.4+ features (e.g., typed properties)
        $this->enableTypedProperties();
    }
    
  3. Where to Look First:

    • Core Classes: Runtime, Environment, OperatingSystem, PhpVersion.
    • Key Methods:
      • Runtime::isHhvm() / Runtime::isPhp()
      • Runtime::getPhpVersion()
      • Runtime::getCurrentSettings() (for php.ini overrides)
      • OperatingSystem::isLinux() / OperatingSystem::isWindows()
    • Laravel Integration: Register as a singleton in a service provider (see Implementation Patterns).

Implementation Patterns

Usage Patterns

1. Runtime-Aware Feature Flags

Dynamically enable/disable features based on PHP/HHVM:

// app/Providers/AppServiceProvider.php
public function register()
{
    if (Runtime::isHhvm()) {
        $this->app->register(HhvmPolyfillServiceProvider::class);
    }
}

2. CI/CD Environment Validation

Fail builds on unsupported PHP versions in phpunit.xml or GitHub Actions:

<!-- phpunit.xml -->
<php>
    <env name="MIN_PHP_VERSION" value="8.0.0"/>
    <ini name="error_reporting" value="-1"/>
    <phpunit bootloader="vendor/autotest/phpunit/bootstrap.php">
        <listeners>
            <listener class="SebastianBergmann\Environment\PhpVersionListener"/>
        </listeners>
    </phpunit>

3. Conditional Test Execution

Skip HHVM-specific tests on PHP-only CI:

// tests/Feature/HhvmTest.php
public function setUp(): void
{
    if (!Runtime::isHhvm()) {
        $this->markTestSkipped('HHVM required for this test.');
    }
}

4. Dynamic Configuration

Load environment-specific configs:

// config/app.php
'php_version' => Runtime::getPhpVersion(),
'is_hhvm' => Runtime::isHhvm(),

5. Artisan Commands

Add runtime checks to commands:

// app/Console/Commands/CheckEnvironment.php
protected function handle()
{
    if (Runtime::isPhp74() && !Runtime::isPhp80()) {
        $this->error('PHP 7.4 is deprecated; upgrade to 8.0+.');
        exit(1);
    }
}

Workflows

Workflow 1: Laravel Service Container Integration

  1. Register the Package:
    // app/Providers/EnvironmentServiceProvider.php
    public function register()
    {
        $this->app->singleton(Runtime::class, function () {
            return new \SebastianBergmann\Environment\Runtime();
        });
    }
    
  2. Use in Controllers/Services:
    use Illuminate\Support\Facades\App;
    
    if (App::make(Runtime::class)->isPhp80()) {
        // Enable PHP 8.0+ features
    }
    

Workflow 2: Facade for Laravel Consistency

  1. Create a Facade:
    // 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;
        }
    
        public static function isPhp81()
        {
            return static::getFacadeRoot()->isPhp('8.1');
        }
    }
    
  2. Use in Blade/Templates:
    @if(App\Facades\Environment::isPhp81())
        <p>PHP 8.1 features enabled.</p>
    @endif
    

Workflow 3: Testing Environment-Specific Logic

  1. Mock Runtime in Tests:
    // tests/TestCase.php
    protected function getEnvironmentStub()
    {
        return $this->mock(Runtime::class, function ($mock) {
            $mock->shouldReceive('isHhvm')->andReturn(true);
        });
    }
    
  2. Test Conditional Logic:
    public function testHhvmFeatureFlag()
    {
        $this->getEnvironmentStub();
        $this->assertTrue(app()->hasHhvmFeatures());
    }
    

Integration Tips

  1. Avoid Overuse:

    • Prefer Laravel’s app()->environment() for high-level checks (e.g., local, production).
    • Use sebastian/environment for low-level runtime details (e.g., PHP version, HHVM, OS).
  2. Combine with Laravel Helpers:

    if (app()->environment('local') && Runtime::isPhp74()) {
        // Local dev + PHP 7.4: enable debug tools
    }
    
  3. Leverage Runtime::getCurrentSettings():

    • Useful for dynamic php.ini overrides in tests or CLI tools:
      $settings = Runtime::getCurrentSettings();
      if ($settings['opcache.enable'] !== '1') {
          $this->error('OPcache is disabled.');
      }
      
  4. OS-Specific Logic:

    • Detect Linux/Windows for path handling or binary execution:
      if (OperatingSystem::isLinux()) {
          $binaryPath = '/usr/bin/php';
      }
      
  5. Deprecation Strategy:

    • Log warnings for unsupported runtimes:
      if (Runtime::isHhvm()) {
          Log::warning('HHVM is deprecated; upgrade to PHP.');
      }
      

Gotchas and Tips

Pitfalls

  1. HHVM is Deprecated:

    • Avoid writing new HHVM-specific logic. Use this package to detect and warn users still on HHVM.
    • Example:
      if (Runtime::isHhvm()) {
          throw new \RuntimeException('HHVM is no longer supported. Use PHP 8.0+.');
      }
      
  2. False Positives in Runtime::isPhp():

    • Returns false for HHVM, even if HHVM emulates PHP. Use Runtime::isHhvm() for explicit checks.
  3. Runtime::getCurrentSettings() Quirks:

    • Empty-string values: May break php -d round-trip (fixed in v9.3.2+).
    • Non-standard extensions: Some php.ini settings (e.g., xdebug.mode) may not be detected.
    • Workaround: Manually merge with $_SERVER or ini_get_all() if needed.
  4. PHP Version Detection Edge Cases:

    • Runtime::isPhp('8.0') includes PHP 8.0.x but not 8.1+.
    • Use Runtime::getPhpVersion() for precise comparisons:
      $version = Runtime::getPhpVersion();
      if (version_compare($version, '8.1.0') >= 0) {
          // PHP 8.1+
      }
      
  5. TTY/Non-TTY Warnings:

    • Some methods (e.g., Console::hasColorSupport()) may trigger warnings in non-TTY environments (fixed in v9.0.1+).
    • Suppress with:
      @Runtime::hasColorSupport();
      
  6. Deprecated Methods:

    • Avoid Runtime::getBinary() (use escapeshellarg(PHP_BINARY)).
    • Avoid Runtime::getRawBinary() (use PHP_BINARY constant).

Debugging Tips

  1. Inspect Runtime Settings:

    dd(Runtime::getCurrentSettings());
    
    • Useful for diagnosing php.ini or environment mismatches.
  2. Check PHP Version:

    dd(Runtime::getPhpVersion(), PHP_VERSION);
    
    • Compare with php -v output to verify detection.
  3. OS Detection:

    dd(OperatingSystem::getName());
    
    • Debug path/permission issues (e.g., /usr/bin/php vs. C:\php\php.exe).
  4. **HHVM vs.

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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope