Browse Source

Merge pull request #11752 from cakephp/3.next-configure-consume-or-fail

Add consumeOrFail().
Mark Story 8 years ago
parent
commit
d5c11dfcc3
2 changed files with 47 additions and 0 deletions
  1. 22 0
      src/Core/Configure.php
  2. 25 0
      tests/TestCase/Core/ConfigureTest.php

+ 22 - 0
src/Core/Configure.php

@@ -189,6 +189,28 @@ class Configure
     }
 
     /**
+     * Used to consume information stored in Configure. It's not
+     * possible to store `null` values in Configure.
+     *
+     * Acts as a wrapper around Configure::consume() and Configure::check().
+     * The configure key/value pair consumed via this method is expected to exist.
+     * In case it does not an exception will be thrown.
+     *
+     * @param string $var Variable to consume. Use '.' to access array elements.
+     * @return mixed Value stored in configure.
+     * @throws \RuntimeException if the requested configuration is not set.
+     * @since 3.6.0
+     */
+    public static function consumeOrFail($var)
+    {
+        if (static::check($var) === false) {
+            throw new RuntimeException(sprintf('Expected configuration key "%s" not found.', $var));
+        }
+
+        return static::consume($var);
+    }
+
+    /**
      * Used to read and delete a variable from Configure.
      *
      * This is primarily used during bootstrapping to move configuration data

+ 25 - 0
tests/TestCase/Core/ConfigureTest.php

@@ -592,4 +592,29 @@ class ConfigureTest extends TestCase
         $result = Configure::consume(null);
         $this->assertNull($result);
     }
+
+    /**
+     * testConsumeOrFail method
+     *
+     * @return void
+     */
+    public function testConsumeOrFail()
+    {
+        $expected = 'ok';
+        Configure::write('This.Key.Exists', $expected);
+        $result = Configure::consumeOrFail('This.Key.Exists');
+        $this->assertEquals($expected, $result);
+    }
+
+    /**
+     * testConsumeOrFail method
+     *
+     * @return void
+     */
+    public function testConsumeOrFailThrowingException()
+    {
+        $this->expectException(\RuntimeException::class);
+        $this->expectExceptionMessage('Expected configuration key "This.Key.Does.Not.exist" not found');
+        Configure::consumeOrFail('This.Key.Does.Not.exist');
+    }
 }