tiny-blocks / environment-variable
Provides a type-safe environment variable reader for PHP, with strict integer and boolean conversion.
Package info
github.com/tiny-blocks/environment-variable
pkg:composer/tiny-blocks/environment-variable
Requires
- php: ^8.5
Requires (Dev)
- ergebnis/composer-normalize: ^2.51
- infection/infection: ^0.32
- phpstan/phpstan: ^2.1
- phpunit/phpunit: ^13.1
- squizlabs/php_codesniffer: ^4.0
README
Overview
Provides a type-safe environment variable reader for PHP, wrapping raw values behind a typed accessor with explicit string, integer, and boolean conversion methods. Supports defaults for missing variables and distinguishes between absent and empty states. Built to surface configuration errors at read time rather than propagate silent coercions through the system.
Installation
composer require tiny-blocks/environment-variable
How to use
Creating an environment variable
To create and work with environment variables, use the from method to get an instance of the environment variable.
use TinyBlocks\EnvironmentVariable\EnvironmentVariable; EnvironmentVariable::from(name: 'MY_VAR');
To retrieve an environment variable with the option of providing a default value in case the variable does not exist,
use the fromOrDefault method.
If the environment variable is not found, the method returns an instance carrying the provided default value instead of throwing an exception.
use TinyBlocks\EnvironmentVariable\EnvironmentVariable; EnvironmentVariable::fromOrDefault(name: 'MY_VAR', defaultValueIfNotFound: 'default_value');
Conversions
Once you have an instance of the environment variable, you can convert its value into various types.
Convert to string
To convert the environment variable to a string.
use TinyBlocks\EnvironmentVariable\EnvironmentVariable; $environmentVariable = EnvironmentVariable::from(name: 'MY_VAR'); $environmentVariable->toString();
Convert to integer
To convert the environment variable to an integer.
use TinyBlocks\EnvironmentVariable\EnvironmentVariable; $environmentVariable = EnvironmentVariable::from(name: 'MY_VAR'); $environmentVariable->toInteger();
Convert to boolean
To convert the environment variable to a boolean.
use TinyBlocks\EnvironmentVariable\EnvironmentVariable; $environmentVariable = EnvironmentVariable::from(name: 'MY_VAR'); $environmentVariable->toBoolean();
Check if the environment variable has a value
Checks if the environment variable has a value. Values like false, 0, and -1 are valid and non-empty.
use TinyBlocks\EnvironmentVariable\EnvironmentVariable; $environmentVariable = EnvironmentVariable::from(name: 'MY_VAR'); $environmentVariable->hasValue();
License
Environment variable is licensed under MIT.
Contributing
Please follow the contributing guidelines to contribute to the project.