Skip to content

Instantly share code, notes, and snippets.

@gthouret
Created January 31, 2017 22:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gthouret/f6e1aa0fd8c7009bf29d2244f4754d9f to your computer and use it in GitHub Desktop.
Save gthouret/f6e1aa0fd8c7009bf29d2244f4754d9f to your computer and use it in GitHub Desktop.
PHP Trait for validating a key=>value configuration array
<?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