diff --git a/src/Illuminate/Config/Repository.php b/src/Illuminate/Config/Repository.php index 08801213a0f3..60eba2a5c574 100644 --- a/src/Illuminate/Config/Repository.php +++ b/src/Illuminate/Config/Repository.php @@ -8,6 +8,7 @@ use Illuminate\Support\Collection; use Illuminate\Support\Traits\Macroable; use InvalidArgumentException; +use RuntimeException; class Repository implements ArrayAccess, ConfigContract { @@ -57,6 +58,19 @@ public function get($key, $default = null) return Arr::get($this->items, $key, $default); } + /** + * Get the specified configuration value. + * + * @param string $key + * @return mixed + * + * @throws \RuntimeException + */ + public function getOrFail(string $key) + { + return $this->get($key) ?? throw new RuntimeException("Configuration value for key [$key] is not set."); + } + /** * Get many configuration values. * diff --git a/src/Illuminate/Foundation/helpers.php b/src/Illuminate/Foundation/helpers.php index 2580b987cb6c..006694720035 100644 --- a/src/Illuminate/Foundation/helpers.php +++ b/src/Illuminate/Foundation/helpers.php @@ -316,6 +316,19 @@ function config($key = null, $default = null) } } +if (! function_exists('config_or_fail')) { + /** + * Get the specified configuration value. + * + * @param string $key + * @return mixed + */ + function config_or_fail(string $key) + { + return app('config')->getOrFail($key); + } +} + if (! function_exists('config_path')) { /** * Get the configuration path. diff --git a/tests/Config/RepositoryTest.php b/tests/Config/RepositoryTest.php index cf59e78b0c49..32d1db7c80ce 100644 --- a/tests/Config/RepositoryTest.php +++ b/tests/Config/RepositoryTest.php @@ -6,6 +6,7 @@ use Illuminate\Support\Collection; use InvalidArgumentException; use PHPUnit\Framework\TestCase; +use RuntimeException; class RepositoryTest extends TestCase { @@ -151,6 +152,19 @@ public function testGetWithDefault() $this->assertSame('default', $this->repository->get('not-exist', 'default')); } + public function testGetOrFailGets() + { + $this->assertSame('bar', $this->repository->getOrFail('foo')); + } + + public function testGetOrFailFails() + { + $this->expectException(RuntimeException::class); + $this->expectExceptionMessageMatches('#^Configuration value for key \[not-exist\] is not set.#'); + + $this->repository->getOrFail('not-exist'); + } + public function testSet() { $this->repository->set('key', 'value');