diff --git a/config/environment.php b/config/environment.php index 8a30037c5..bbc43952a 100644 --- a/config/environment.php +++ b/config/environment.php @@ -3,4 +3,7 @@ /*----------------------------------------------------*/ // Define environment type /*----------------------------------------------------*/ -return ''; +return [ + 'local' => 'INSERT-HOSTNAME', + 'production' => 'INSERT-HOSTNAME' +]; diff --git a/library/Thms/Config/Environment.php b/library/Thms/Config/Environment.php index 48ed3bbf7..186b923b2 100644 --- a/library/Thms/Config/Environment.php +++ b/library/Thms/Config/Environment.php @@ -44,9 +44,23 @@ public function which($hostname = '') // by comparing the given hostnames from an array. if (is_array($this->locations) && !empty($this->locations)) { foreach ($this->locations as $location => $host) { - $host = is_array($host) ? $host : [$host]; - if (in_array($hostname, $host)) { - return $location; + + /* + * Test against an array of hosts. + */ + if (is_array($host)) { + if (in_array($hostname, $host)) { + return $location; + } + } else { + /* + * Test against a string/regular expression. + */ + $pattern = ($host !== '/') ? str_replace('*', '(.*)', $host).'\z' : '^/$'; + + if ((bool) preg_match('/'.$pattern.'/', $hostname)) { + return $location; + } } } } @@ -54,6 +68,8 @@ public function which($hostname = '') // If not using array, a single string is provided to define the // environment. if (is_string($this->locations)) { + + // Default string. return $this->locations; } diff --git a/tests/config/EnvironmentTest.php b/tests/config/EnvironmentTest.php index e5996b61d..b2e101b26 100644 --- a/tests/config/EnvironmentTest.php +++ b/tests/config/EnvironmentTest.php @@ -61,4 +61,26 @@ public function testWhichEnvironmentWithString() $env = new \Thms\Config\Environment($locations); $this->assertEquals('local', $env->which()); } + + public function testWhichEnvironmentWithRegEx() + { + $locations = [ + 'local' => '*.themosis.dev', + 'production' => '*.aws.elastic456278s9d.com', + 'staging' => 'xyz\..+\.net', + 'custom' => 'my-hostname', + ]; + + $env = new Thms\Config\Environment($locations); + + $this->assertEquals('local', $env->which('server001.themosis.dev')); + $this->assertEquals('local', $env->which('abcserver3578sdd67.themosis.dev')); + + $this->assertEquals('production', $env->which('us2-467.aws.elastic456278s9d.com')); + + $this->assertEquals('staging', $env->which('xyz.some-name.net')); + $this->assertEquals('staging', $env->which('xyz.another_name215658.net')); + + $this->assertEquals('custom', $env->which('my-hostname')); + } }