Skip to content

Commit

Permalink
Initial Releaes
Browse files Browse the repository at this point in the history
  • Loading branch information
sabroan committed May 15, 2023
1 parent 8e5f972 commit 8ffedf5
Show file tree
Hide file tree
Showing 3 changed files with 94 additions and 0 deletions.
22 changes: 22 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Dotenv
A simple and tiny PHP `.env` loader.
## Installation
```
composer require env/dotenv
```
## Usage
The .env file should have a valid [.ini](https://wikipedia.org/wiki/INI_file) syntaxis, supported by [parse_ini_file](https://www.php.net/manual/en/function.parse-ini-file.php).
### Load
Parse .env and inject it into `$_ENV` variable:
```php
$env = new \Env\Dotenv(
path: '.env',
overwrite: false, // by default: true
);
```
The second argument determine if existing `$_ENV` keys should be overwritten.
### Parse
Additionaly, if you dont wan't to inject data into `$_ENV`, you can retrieve parsed data by:
```php
$env = \Env\Dotenv::load('.env');
```
16 changes: 16 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"name": "env/dotenv",
"type": "library",
"description": "A simple, tiny and lightweight PHP .env loader",
"keywords": ["environment", "env", "dotenv"],
"license": "MIT",
"minimum-stability": "stable",
"require": {
"php": "^8"
},
"autoload" : {
"psr-4": {
"Env\\": "./src"
}
}
}
56 changes: 56 additions & 0 deletions src/Dotenv.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<?php

declare(strict_types=1);

namespace Env;

use \ErrorException;
use \ValueError;

use function \realpath;
use function \parse_ini_file;

use const \INI_SCANNER_TYPED;

final class Dotenv
{
/**
* @param string $path path to .env file.
* @param bool $overwrite overwrite existing `$_ENV` keys?
*/
public function __construct(
string $path,
bool $overwrite = true
) {
$env = static::load($path);
$_ENV = ($overwrite)
? $env + $_ENV
: $_ENV + $env;
}

/**
* Parse and retrieve content from .env file.
*
* @param string $path path to .env file.
* @return array associative array of .env keys and values.
* @throws ValueError .env was not found at provided path.
* @throws ErrorException corrupted .env, unable to parse.
* @see https://www.php.net/manual/en/function.parse-ini-file.php
*/
public static function load(string $path): array
{
$path = realpath($path);
if ($path === false) {
throw new ValueError("File $path not found");
}
$env = parse_ini_file(
filename: $path,
process_sections: false,
scanner_mode: INI_SCANNER_TYPED
);
if ($env === false) {
throw new ErrorException("Unable to parse $path");
}
return $env;
}
}

0 comments on commit 8ffedf5

Please sign in to comment.