Skip to content

Instantly share code, notes, and snippets.

@cryptiklemur
Last active December 18, 2015 08:20
Show Gist options
  • Save cryptiklemur/5753723 to your computer and use it in GitHub Desktop.
Save cryptiklemur/5753723 to your computer and use it in GitHub Desktop.
<?php
/**
* Copyright 2013 Aaron Scherer
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @copyright Aaron Scherer 2013
* @license Apache License, Version 2.0
*/
use Symfony\Component\Console\Input\ArgvInput;
/**
* Environment Class
*
* @author Aaron Scherer <[email protected]
*/
class Environment
{
/**
* @var string[]
*/
static public $allowedEnvironments = array(
'dev',
'test',
'staging',
'prod'
);
/**
* @var ArgvInput
*/
public $input = null;
/**
* @var string
*/
private $environment = false;
/**
* @var Boolean
*/
private $debug = false;
/**
* Sets the $environment and $debug values. Checks for $_GET[ 'SYM_ENV' ],
* Then checks for the Apache SYM_ENV
*
* @param ArgvInput $input
*/
public function __construct(ArgvInput $input = null)
{
$cfgEnv = get_cfg_var('symfony.environment');
if ($cfgEnv !== false && !isset($_SERVER['SYM_ENV'])) {
$_SERVER['SYM_ENV'] = $cfgEnv;
}
if (null !== $input) {
$this->input = $input;
}
$this->environment = $this->findEnvironment();
$this->checkEnvironment();
$this->debug = $this->findDebug();
}
/**
* @return string
*/
private function findEnvironment()
{
if (null !== $this->input) {
$env = $this->input->getParameterOption(array('--env', '-e'));
if (!empty($env)) {
return $env;
}
}
if (isset($_SERVER['SYM_ENV'])) {
return $_SERVER['SYM_ENV'];
}
return 'dev';
}
/**
* @return Boolean
* @throws \Exception
*/
private function checkEnvironment()
{
if (!in_array($this->environment, self::$allowedEnvironments)) {
throw new \Exception(sprintf(
"`%s` is not a valid environment. Expected: %s",
$this->environment,
implode(', ', self::$allowedEnvironments)
));
}
return true;
}
/**
* @return Boolean
*/
private function findDebug()
{
if (null !== $this->input && !$this->input->hasParameterOption(array('--no-debug', ''))) {
return true;
}
if (in_array($this->environment, ['dev', 'test'])) {
return true;
}
return false;
}
/**
* @return Boolean
*/
public function getDebug()
{
return $this->debug;
}
/**
* @return string
*/
public function getEnvironment()
{
return $this->environment;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment