Browse Source

Add support for default value to InstanceConfigTrait::getConfig().

ADmad 8 years ago
parent
commit
47f2a3cff9
2 changed files with 29 additions and 2 deletions
  1. 11 2
      src/Core/InstanceConfigTrait.php
  2. 18 0
      tests/TestCase/Core/InstanceConfigTraitTest.php

+ 11 - 2
src/Core/InstanceConfigTrait.php

@@ -103,17 +103,26 @@ trait InstanceConfigTrait
      * $this->getConfig('some.nested.key');
      * ```
      *
+     * Reading with default value:
+     *
+     * ```
+     * $this->getConfig('some-key', 'default-value');
+     * ```
+     *
      * @param string|null $key The key to get or null for the whole config.
+     * @param mixed $default The return value when the key does not exist.
      * @return mixed Config value being read.
      */
-    public function getConfig($key = null)
+    public function getConfig($key = null, $default = null)
     {
         if (!$this->_configInitialized) {
             $this->_config = $this->_defaultConfig;
             $this->_configInitialized = true;
         }
 
-        return $this->_configRead($key);
+        $return = $this->_configRead($key);
+
+        return $return === null ? $default : $return;
     }
 
     /**

+ 18 - 0
tests/TestCase/Core/InstanceConfigTraitTest.php

@@ -151,6 +151,24 @@ class InstanceConfigTraitTest extends TestCase
     }
 
     /**
+     * testGetDefault
+     *
+     * @return void
+     */
+    public function testGetDefault()
+    {
+        $this->assertSame(
+            'default',
+            $this->object->getConfig('nonexistent', 'default')
+        );
+
+        $this->assertSame(
+            'my-default',
+            $this->object->getConfig('nested.nonexistent', 'my-default')
+        );
+    }
+
+    /**
      * testSetSimple
      *
      * @return void