Created
January 31, 2017 22:34
-
-
Save gthouret/f6e1aa0fd8c7009bf29d2244f4754d9f to your computer and use it in GitHub Desktop.
PHP Trait for validating a key=>value configuration array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Patterns; | |
trait ConfigurableTrait { | |
private $requiredConfigKeys; | |
private function validateConfiguration($config) | |
{ | |
if (empty($config)) | |
throw new \Exception("\$config parameter should be an array of configuration options"); | |
if (empty($this->requiredConfigKeys)) | |
throw new \Exception("\$this->requiredConfigKeys member should be an array of required configuration options"); | |
foreach ($this->requiredConfigKeys as $key) { | |
$this->configurationKeyExists($key, $config); | |
} | |
} | |
private function configurationKeyExists($configurationKey, $configurationArray) { | |
if (!array_key_exists($configurationKey, $configurationArray)) | |
throw new \Exception("Configuration key '$configurationKey' does not exist"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment