Skip to content

Commit

Permalink
Add ENV storage
Browse files Browse the repository at this point in the history
  • Loading branch information
pierredup committed May 5, 2023
1 parent 20f42d2 commit 7ba749a
Show file tree
Hide file tree
Showing 2 changed files with 102 additions and 0 deletions.
33 changes: 33 additions & 0 deletions src/Storage/EnvStorage.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

declare(strict_types=1);

/*
* This file is part of the Toggler package.
*
* (c) SolidWorx <open-source@solidworx.co>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace SolidWorx\Toggler\Storage;

class EnvStorage implements StorageInterface
{
/**
* {@inheritdoc}
*/
public function get(string $key)
{
return $_ENV[$key] ?? $_SERVER[$key] ?? getenv($key) ?? null;
}

/**
* @return array<string, mixed>
*/
public function all(): array
{
return array_merge($_ENV, $_SERVER, getenv());
}
}
69 changes: 69 additions & 0 deletions tests/Storage/EnvStorageTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
<?php

declare(strict_types=1);

/*
* This file is part of the Toggler package.
*
* (c) SolidWorx <open-source@solidworx.co>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace SolidWorx\Toggler\Tests\Storage;

use PHPUnit\Framework\TestCase;
use SolidWorx\Toggler\Storage\EnvStorage;

class EnvStorageTest extends TestCase
{
public function testGet(): void
{
$storage = new EnvStorage();

self::assertFalse($storage->get('baz'));

$_ENV['baz'] = 'foo';

self::assertSame('foo', $storage->get('baz'));

unset($_ENV['baz']);

$_SERVER['baz'] = 'bar';

self::assertSame('bar', $storage->get('baz'));

unset($_SERVER['baz']);

putenv('baz=baz');

self::assertSame('baz', $storage->get('baz'));

putenv('baz');

self::assertFalse($storage->get('baz'));

self::assertSame($_SERVER, $storage->all());

$_ENV['foo'] = 'bar';

self::assertSame(['foo' => 'bar'] + $_SERVER, $storage->all());

$_SERVER['bar'] = 'baz';

self::assertSame(['foo' => 'bar'] + $_SERVER, $storage->all());

putenv('baz=baz');

self::assertSame(['foo' => 'bar'] + $_SERVER + ['baz' => 'baz'], $storage->all());

putenv('baz');

self::assertSame(['foo' => 'bar'] + $_SERVER + ['bar' => 'baz'], $storage->all());

unset($_ENV['foo'], $_SERVER['bar']);

self::assertSame($_SERVER, $storage->all());
}
}

0 comments on commit 7ba749a

Please sign in to comment.