65 lines
1.4 KiB
PHP
65 lines
1.4 KiB
PHP
<?php
|
|
|
|
class Env
|
|
{
|
|
private static $loaded = false;
|
|
private static $values = [];
|
|
|
|
public static function load( $path = '.env' )
|
|
{
|
|
if ( self::$loaded )
|
|
return;
|
|
|
|
self::$loaded = true;
|
|
|
|
if ( !is_string( $path ) || $path === '' || !file_exists( $path ) )
|
|
return;
|
|
|
|
$lines = file( $path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES );
|
|
if ( !is_array( $lines ) )
|
|
return;
|
|
|
|
foreach ( $lines as $line )
|
|
{
|
|
$line = trim( $line );
|
|
if ( $line === '' || strpos( $line, '#' ) === 0 )
|
|
continue;
|
|
|
|
$parts = explode( '=', $line, 2 );
|
|
if ( count( $parts ) !== 2 )
|
|
continue;
|
|
|
|
$key = trim( $parts[0] );
|
|
$value = trim( $parts[1] );
|
|
if ( $key === '' )
|
|
continue;
|
|
|
|
if ( strlen( $value ) >= 2 )
|
|
{
|
|
$first = $value[0];
|
|
$last = $value[strlen( $value ) - 1];
|
|
if ( ( $first === '"' && $last === '"' ) || ( $first === "'" && $last === "'" ) )
|
|
$value = substr( $value, 1, -1 );
|
|
}
|
|
|
|
self::$values[ $key ] = $value;
|
|
$_ENV[ $key ] = $value;
|
|
putenv( $key . '=' . $value );
|
|
}
|
|
}
|
|
|
|
public static function get( $key, $default = null )
|
|
{
|
|
self::load();
|
|
|
|
$value = getenv( $key );
|
|
if ( $value !== false )
|
|
return $value;
|
|
|
|
if ( isset( self::$values[ $key ] ) )
|
|
return self::$values[ $key ];
|
|
|
|
return $default;
|
|
}
|
|
}
|