Skip to content

Commit af70b4e

Browse files
authored
chore(core): env detection improvements (#747)
1 parent ddda992 commit af70b4e

File tree

4 files changed

+29
-5
lines changed

4 files changed

+29
-5
lines changed

src/Tempest/Core/src/AppConfig.php

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,7 @@ public function __construct(
2121
// …,
2222
],
2323
) {
24-
$this->environment = $environment
25-
?? Environment::tryFrom(env('ENVIRONMENT', 'local'))
26-
?? Environment::LOCAL;
24+
$this->environment = $environment ?? Environment::fromEnv();
2725

2826
$this->baseUri = $baseUri ?? env('BASE_URI') ?? '';
2927
}

src/Tempest/Core/src/Environment.php

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44

55
namespace Tempest\Core;
66

7+
use function Tempest\env;
8+
79
enum Environment: string
810
{
911
case LOCAL = 'local';
@@ -42,4 +44,11 @@ public function isOther(): bool
4244
{
4345
return $this === self::OTHER;
4446
}
47+
48+
public static function fromEnv(): self
49+
{
50+
$value = env('ENVIRONMENT', 'production');
51+
52+
return self::tryFrom($value) ?? throw new InvalidEnvironment($value);
53+
}
4554
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Tempest\Core;
6+
7+
use Exception;
8+
use function Tempest\Support\arr;
9+
10+
final class InvalidEnvironment extends Exception
11+
{
12+
public function __construct(string $value)
13+
{
14+
$possibleValues = arr(Environment::cases())->map(fn (Environment $environment) => $environment->value)->implode(', ');
15+
16+
parent::__construct("Invalid environment value `{$value}`, possible values are {$possibleValues}.");
17+
}
18+
}

src/Tempest/Core/src/Kernel.php

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@
1212
use Tempest\Core\Kernel\LoadConfig;
1313
use Tempest\Core\Kernel\LoadDiscoveryClasses;
1414
use Tempest\Core\Kernel\LoadDiscoveryLocations;
15-
use function Tempest\env;
1615
use Tempest\EventBus\EventBus;
1716
use Tempest\Http\Exceptions\HttpProductionErrorHandler;
1817
use Whoops\Handler\PrettyPageHandler;
@@ -177,7 +176,7 @@ private function event(object $event): self
177176

178177
private function registerKernelErrorHandler(): self
179178
{
180-
$environment = Environment::tryFrom(env('ENVIRONMENT', 'production'));
179+
$environment = Environment::fromEnv();
181180

182181
if ($environment->isTesting()) {
183182
return $this;

0 commit comments

Comments
 (0)