├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE.md ├── README.md ├── composer.json └── src └── Environment.php /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All Notable changes to `yii2-environment` will be documented in this file. 4 | 5 | ## 1.3.0 - 2016-06-01 6 | 7 | ### Fixed 8 | - Travis + Scrutinizer 9 | 10 | ### Added 11 | - Tests 12 | 13 | ## 1.2.0 - 2015-06-26 14 | 15 | ### Fixed 16 | - Updated dependencies 17 | - Travis 18 | 19 | ## 1.1.1 - 2015-04-09 20 | 21 | ### Fixed 22 | - Bug #2: Use late static bindings with merge 23 | 24 | ## 1.1.0 - 2015-04-08 25 | 26 | ### Added 27 | - Code refactor 28 | - Added to Travis and Scrutinizer 29 | 30 | ### Fixed 31 | - Bug #1: Added merge method for easier ArrayHelper override 32 | 33 | ## 1.0.1 - 2014-10-27 34 | 35 | ### Added 36 | - Examples 37 | 38 | ## 1.0.0 - 2014-10-27 39 | 40 | - Initial release 41 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Contributions are **welcome** and will be fully **credited**. 4 | 5 | We accept contributions via Pull Requests on [Github](https://github.com/janisto/yii2-environment). 6 | 7 | 8 | ## Pull Requests 9 | 10 | - **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](http://pear.php.net/package/PHP_CodeSniffer). 11 | 12 | - **Add tests!** - Your patch won't be accepted if it doesn't have tests. 13 | 14 | - **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date. 15 | 16 | - **Consider our release cycle** - We try to follow [SemVer v2.0.0](http://semver.org/). Randomly breaking public APIs is not an option. 17 | 18 | - **Create feature branches** - Don't ask us to pull from your master branch. 19 | 20 | - **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. 21 | 22 | - **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please squash them before submitting. 23 | 24 | 25 | ## Running Tests 26 | 27 | ``` bash 28 | $ phpunit 29 | ``` 30 | 31 | 32 | **Happy coding**! 33 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | This is free and unencumbered software released into the public domain. 2 | 3 | Anyone is free to copy, modify, publish, use, compile, sell, or 4 | distribute this software, either in source code form or as a compiled 5 | binary, for any purpose, commercial or non-commercial, and by any 6 | means. 7 | 8 | In jurisdictions that recognize copyright laws, the author or authors 9 | of this software dedicate any and all copyright interest in the 10 | software to the public domain. We make this dedication for the benefit 11 | of the public at large and to the detriment of our heirs and 12 | successors. We intend this dedication to be an overt act of 13 | relinquishment in perpetuity of all present and future rights to this 14 | software under copyright law. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 17 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 18 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 19 | IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR 20 | OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 21 | ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 22 | OTHER DEALINGS IN THE SOFTWARE. 23 | 24 | For more information, please refer to 25 | 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Yii 2 Environment 2 | 3 | Environment class for Yii 2, used to set configuration for console and web apps depending on the server environment. 4 | 5 | [![Software License](https://img.shields.io/badge/license-Unlicense-blue.svg?style=flat-square)](LICENSE.md) 6 | [![Build Status](https://img.shields.io/travis/janisto/yii2-environment/master.svg?style=flat-square)](https://travis-ci.org/janisto/yii2-environment) 7 | [![Code Quality](https://img.shields.io/scrutinizer/g/janisto/yii2-environment.svg?style=flat-square)](https://scrutinizer-ci.com/g/janisto/yii2-environment) 8 | [![Code Coverage](https://img.shields.io/scrutinizer/coverage/g/janisto/yii2-environment.svg?style=flat-square)](https://scrutinizer-ci.com/g/janisto/yii2-environment) 9 | [![Packagist Version](https://img.shields.io/packagist/v/janisto/yii2-environment.svg?style=flat-square)](https://packagist.org/packages/janisto/yii2-environment) 10 | [![Total Downloads](https://img.shields.io/packagist/dt/janisto/yii2-environment.svg?style=flat-square)](https://packagist.org/packages/janisto/yii2-environment) 11 | 12 | ## Installation 13 | 14 | If you do not have [Composer](http://getcomposer.org/), you may install it by following the instructions 15 | at [getcomposer.org](http://getcomposer.org/doc/00-intro.md#installation-nix). 16 | 17 | You can then install this package using the following command: 18 | 19 | ```php 20 | php composer.phar require "janisto/yii2-environment" "*" 21 | ``` 22 | or add 23 | 24 | ```json 25 | "janisto/yii2-environment": "*" 26 | ``` 27 | 28 | to the require section of your application's `composer.json` file. 29 | 30 | ## Usage 31 | 32 | ### web index.php 33 | 34 | ```php 35 | setup(); 40 | (new yii\web\Application($env->web))->run(); 41 | ``` 42 | 43 | or if you have multiple configuration locations 44 | 45 | ```php 46 | setup(); 54 | (new yii\web\Application($env->web))->run(); 55 | ``` 56 | 57 | ### console yii 58 | 59 | ```php 60 | #!/usr/bin/env php 61 | setup(); 71 | $exitCode = (new yii\console\Application($env->console))->run(); 72 | exit($exitCode); 73 | ``` 74 | 75 | Use yii 76 | 77 | ``` 78 | export YII_ENV='dev' && ./yii 79 | ``` 80 | 81 | ## Documentation 82 | 83 | See `examples/`. 84 | 85 | ## Contributing 86 | 87 | Please see [CONTRIBUTING](CONTRIBUTING.md) for details. 88 | 89 | ## Credits 90 | 91 | - [Jani Mikkonen](https://github.com/janisto) 92 | - [All Contributors](../../contributors) 93 | 94 | ## License 95 | 96 | Public domain. Please see [License File](LICENSE.md) for more information. 97 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "janisto/yii2-environment", 3 | "description": "Environment class for Yii 2, used to set configuration for console and web apps depending on the server environment.", 4 | "keywords": ["yii2", "environment", "configuration", "extension"], 5 | "homepage": "https://github.com/janisto/yii2-environment", 6 | "type": "yii2-extension", 7 | "license": "public domain", 8 | "authors": [ 9 | { 10 | "name": "Jani Mikkonen", 11 | "email": "janisto@php.net" 12 | } 13 | ], 14 | "support": { 15 | "issues": "https://github.com/janisto/yii2-environment/issues?state=open", 16 | "source": "https://github.com/janisto/yii2-environment" 17 | }, 18 | "require": { 19 | "php": ">=5.4.0", 20 | "yiisoft/yii2": "*" 21 | }, 22 | "require-dev": { 23 | "phpunit/phpunit": "~4.5", 24 | "scrutinizer/ocular": "~1.1" 25 | }, 26 | "autoload": { 27 | "psr-4": { 28 | "janisto\\environment\\": "src" 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/Environment.php: -------------------------------------------------------------------------------- 1 | 9 | * @license public domain (http://unlicense.org) 10 | * @link https://github.com/janisto/yii2-environment 11 | */ 12 | class Environment 13 | { 14 | /** 15 | * Environment variable. Use Apache SetEnv or export in shell. 16 | * 17 | * @var string environment variable name 18 | */ 19 | protected $envName = 'YII_ENV'; 20 | /** 21 | * @var array list of valid modes 22 | */ 23 | protected $validModes = [ 24 | 'dev', 25 | 'test', 26 | 'stage', 27 | 'prod', 28 | ]; 29 | /** 30 | * @var array configuration directory(s) 31 | */ 32 | protected $configDir = []; 33 | /** 34 | * @var string selected environment mode 35 | */ 36 | protected $mode; 37 | /** 38 | * @var string path to Yii.php 39 | */ 40 | public $yiiPath; 41 | /** 42 | * @var boolean debug mode or not 43 | */ 44 | public $yiiDebug; 45 | /** 46 | * @var string defines in which environment the application is running 47 | */ 48 | public $yiiEnv; 49 | /** 50 | * @var array register path aliases 51 | */ 52 | public $aliases = []; 53 | /** 54 | * @var array merge class map used by the Yii autoloading mechanism 55 | */ 56 | public $classMap = []; 57 | /** 58 | * @var array web application configuration array 59 | */ 60 | public $web = []; 61 | /** 62 | * @var array console application configuration array 63 | */ 64 | public $console = []; 65 | 66 | /** 67 | * Constructor. Initializes the Environment class. 68 | * 69 | * @param string|array $configDir configuration directory(s) 70 | * @param string $mode override automatically set environment mode 71 | * @throws \Exception 72 | */ 73 | public function __construct($configDir, $mode = null) 74 | { 75 | $this->setConfigDir($configDir); 76 | $this->setMode($mode); 77 | $this->setEnvironment(); 78 | } 79 | 80 | /** 81 | * Set configuration directory(s) where the config files are stored. 82 | * 83 | * @param string|array $configDir configuration directory(s) 84 | * @throws \Exception 85 | */ 86 | protected function setConfigDir($configDir) 87 | { 88 | $this->configDir = []; 89 | foreach ((array) $configDir as $k => $v) { 90 | $dir = rtrim($v, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; 91 | if (!is_dir($dir)) { 92 | throw new \Exception('Invalid configuration directory "' . $dir . '".'); 93 | } 94 | $this->configDir[$k] = $dir; 95 | } 96 | } 97 | 98 | /** 99 | * Set environment mode. 100 | * 101 | * @param string|null $mode environment mode 102 | * @throws \Exception 103 | */ 104 | protected function setMode($mode) 105 | { 106 | if ($mode === null) { 107 | // Return mode based on environment variable. 108 | $mode = getenv($this->envName); 109 | if ($mode === false) { 110 | // Defaults to production. 111 | $mode = 'prod'; 112 | } 113 | } 114 | 115 | // Check if mode is valid. 116 | $mode = strtolower($mode); 117 | if (!in_array($mode, $this->validModes, true)) { 118 | throw new \Exception('Invalid environment mode supplied or selected: ' . $mode); 119 | } 120 | 121 | $this->mode = $mode; 122 | } 123 | 124 | /** 125 | * Load and merge configuration files into one array. 126 | * 127 | * @return array $config array to be processed by setEnvironment 128 | * @throws \Exception 129 | */ 130 | protected function getConfig() 131 | { 132 | $configMerged = []; 133 | foreach ($this->configDir as $configDir) { 134 | // Merge main config. 135 | $fileMainConfig = $configDir . 'main.php'; 136 | if (!file_exists($fileMainConfig)) { 137 | throw new \Exception('Cannot find main config file "' . $fileMainConfig . '".'); 138 | } 139 | $configMain = require($fileMainConfig); 140 | if (is_array($configMain)) { 141 | $configMerged = static::merge($configMerged, $configMain); 142 | } 143 | 144 | // Merge mode specific config. 145 | $fileSpecificConfig = $configDir . 'mode_' . $this->mode . '.php'; 146 | if (!file_exists($fileSpecificConfig)) { 147 | throw new \Exception('Cannot find mode specific config file "' . $fileSpecificConfig . '".'); 148 | } 149 | $configSpecific = require($fileSpecificConfig); 150 | if (is_array($configSpecific)) { 151 | $configMerged = static::merge($configMerged, $configSpecific); 152 | } 153 | 154 | // If one exists, merge local config. 155 | $fileLocalConfig = $configDir . 'local.php'; 156 | if (file_exists($fileLocalConfig)) { 157 | $configLocal = require($fileLocalConfig); 158 | if (is_array($configLocal)) { 159 | $configMerged = static::merge($configMerged, $configLocal); 160 | } 161 | } 162 | } 163 | 164 | return $configMerged; 165 | } 166 | 167 | /** 168 | * Sets the environment and configuration for the selected mode. 169 | * 170 | * @throws \Exception 171 | */ 172 | protected function setEnvironment() 173 | { 174 | $config = $this->getConfig(); 175 | if (!is_readable($config['yiiPath'])) { 176 | throw new \Exception('Invalid Yii framework path "' . $config['yiiPath'] . '".'); 177 | } 178 | 179 | // Set attributes. 180 | $this->yiiPath = $config['yiiPath']; 181 | $this->yiiDebug = isset($config['yiiDebug']) ? $config['yiiDebug'] : false; 182 | $this->yiiEnv = isset($config['yiiEnv']) ? $config['yiiEnv'] : $this->mode; 183 | $this->web = isset($config['web']) ? $config['web'] : []; 184 | $this->web['params']['environment'] = $this->mode; 185 | $this->console = isset($config['console']) ? $config['console'] : []; 186 | $this->console['params']['environment'] = $this->mode; 187 | $this->aliases = isset($config['aliases']) ? $config['aliases'] : []; 188 | $this->classMap = isset($config['classMap']) ? $config['classMap'] : []; 189 | } 190 | 191 | /** 192 | * Merges two arrays into one recursively. 193 | * 194 | * @param array $a array to be merged to 195 | * @param array $b array to be merged from. 196 | * @return array the merged array (the original arrays are not changed.) 197 | */ 198 | protected static function merge($a, $b) 199 | { 200 | return \yii\helpers\ArrayHelper::merge($a, $b); 201 | } 202 | 203 | /** 204 | * Defines Yii constants, includes base Yii class, sets aliases and merges class map. 205 | */ 206 | public function setup() 207 | { 208 | /** 209 | * This constant defines whether the application should be in debug mode or not. 210 | */ 211 | defined('YII_DEBUG') or define('YII_DEBUG', $this->yiiDebug); 212 | /** 213 | * This constant defines in which environment the application is running. 214 | * The value could be 'prod' (production), 'stage' (staging), 'test' (testing) or 'dev' (development). 215 | */ 216 | defined('YII_ENV') or define('YII_ENV', $this->yiiEnv); 217 | /** 218 | * Whether the the application is running in staging environment. 219 | */ 220 | defined('YII_ENV_STAGE') or define('YII_ENV_STAGE', YII_ENV === 'stage'); 221 | 222 | // Include Yii. 223 | require($this->yiiPath); 224 | 225 | // Set aliases. 226 | foreach ($this->aliases as $alias => $path) { 227 | \Yii::setAlias($alias, $path); 228 | } 229 | 230 | // Merge class map. 231 | if (!empty($this->classMap)) { 232 | \Yii::$classMap = static::merge(\Yii::$classMap, $this->classMap); 233 | } 234 | } 235 | 236 | /** 237 | * Show current Environment class values. 238 | */ 239 | public function showDebug() 240 | { 241 | print '
' 243 | . '
'
244 |             . htmlspecialchars(print_r($this, true)) . '
'; 245 | } 246 | } 247 | --------------------------------------------------------------------------------