Skip to content

Commit

Permalink
Fix #44. Allow pattern in environment detection.
Browse files Browse the repository at this point in the history
  • Loading branch information
jlambe committed Nov 13, 2016
1 parent c21a665 commit cc9d9b8
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 4 deletions.
5 changes: 4 additions & 1 deletion config/environment.php
Expand Up @@ -3,4 +3,7 @@
/*----------------------------------------------------*/
// Define environment type
/*----------------------------------------------------*/
return '';
return [
'local' => 'INSERT-HOSTNAME',
'production' => 'INSERT-HOSTNAME'
];
22 changes: 19 additions & 3 deletions library/Thms/Config/Environment.php
Expand Up @@ -44,16 +44,32 @@ 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;
}
}
}
}

// If not using array, a single string is provided to define the
// environment.
if (is_string($this->locations)) {

// Default string.
return $this->locations;
}

Expand Down
22 changes: 22 additions & 0 deletions tests/config/EnvironmentTest.php
Expand Up @@ -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'));
}
}

0 comments on commit cc9d9b8

Please sign in to comment.