Created
November 12, 2015 10:29
-
-
Save sam-higton/3c028303d4b6d5478988 to your computer and use it in GitHub Desktop.
A trait to handle user setting arrays in your classes
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 | |
class SettingTest { | |
use \MyProject\Behaviours\Settings; | |
public function __construct (array $settings = array()) { | |
$this->loadSettings($settings); | |
} | |
} | |
$settingTest = new SettingTest( | |
array ( | |
"schemaPath" => "schema.xml", | |
"api" => array ( | |
"basePath" => "api" | |
), | |
"admin" => array ( | |
"basPath" => "admin" | |
), | |
"auth" => array ( | |
"method" => "simple", | |
"model" => "user", | |
"username_field" => "name", | |
"password_field" => "password" | |
) | |
) | |
); | |
$settingTest->applySetting("auth:validation:username","email"); | |
echo "Authentication method: " . $settingTest->setting("auth:method"); | |
echo "username validation: " . $settingTest->setting("auth:validation:username")); |
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 MyProject\Behaviours; | |
trait Settings { | |
protected $settings; | |
public function loadSettings (array $settingsArray = array()) { | |
$this->settings = $settingsArray; | |
} | |
public function setting ($settingName) { | |
$settingRoute = explode(':',$settingName); | |
$setting = $this->settings; | |
foreach($settingRoute as $routePart) { | |
if(isset($setting[$routePart])) { | |
$setting = $setting[$routePart]; | |
} else { | |
return NULL; | |
} | |
} | |
return $setting; | |
} | |
public function applySetting($settingName, $settingValue) { | |
$settingRoute = explode(':',$settingName); | |
$this->apply($settingRoute,$this->settings, $settingValue); | |
} | |
public function fetchAllSettings () { | |
return $this->settings; | |
} | |
private function apply($route,&$setting, $value) { | |
if(count($route) > 1) { | |
$routePart = array_shift($route); | |
if(!isset($setting[$routePart])) { | |
$setting[$routePart] = array (); | |
} | |
$this->apply($route, $setting[$routePart], $value); | |
} else { | |
$setting[$route[0]] = $value; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment