├── .github ├── FUNDING.yml └── workflows │ └── main.yml ├── .styleci.yml ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE.md ├── README.md ├── composer.json ├── phpunit.xml ├── screenshot.png └── src ├── EnvironmentSetCommand.php └── EnvironmentSetCommandServiceProvider.php /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: imliam 2 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: run-tests 2 | 3 | on: 4 | - push 5 | - pull_request 6 | 7 | jobs: 8 | test: 9 | runs-on: ${{ matrix.os }} 10 | 11 | strategy: 12 | fail-fast: false 13 | matrix: 14 | os: [ubuntu-latest] 15 | php: [8.4, 8.3, 8.2] 16 | laravel: [^12.0, ^11.0] 17 | dependency-version: [prefer-lowest, prefer-stable] 18 | include: 19 | - laravel: ^11.0 20 | testbench: ^9.0 21 | - laravel: ^12.0 22 | testbench: ^10.0 23 | 24 | name: P${{ matrix.php }} - L${{ matrix.laravel }} - ${{ matrix.dependency-version }} - ${{ matrix.os }} 25 | 26 | steps: 27 | - name: Checkout code 28 | uses: actions/checkout@v4 29 | 30 | - name: Setup PHP 31 | uses: shivammathur/setup-php@v2 32 | with: 33 | php-version: ${{ matrix.php }} 34 | extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, sqlite, pdo_sqlite, bcmath, soap, intl, gd, exif, iconv, imagick 35 | coverage: none 36 | 37 | - name: Install dependencies 38 | run: | 39 | composer require "laravel/framework:${{ matrix.laravel }}" "orchestra/testbench:${{ matrix.testbench }}" --no-interaction --no-update 40 | composer update --${{ matrix.dependency-version }} --prefer-dist --no-interaction 41 | 42 | - name: Execute tests 43 | run: vendor/bin/phpunit 44 | -------------------------------------------------------------------------------- /.styleci.yml: -------------------------------------------------------------------------------- 1 | preset: laravel 2 | 3 | disabled: 4 | - single_class_element_per_statement 5 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) 3 | and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). 4 | 5 | ## [Unreleased] 6 | ### Added 7 | ### Changed 8 | ### Deprecated 9 | ### Removed 10 | ### Fixed 11 | ### Security 12 | 13 | ## [1.2.0] - 2020-09-13 14 | ### Added 15 | - Laravel 8 support 16 | 17 | 18 | ## [1.1.1] - 2020-05-27 19 | ### Fixed 20 | - Fixed working with nested key names (for example, APP_KEY and PUSHER_APP_KEY). 21 | 22 | ## [1.1.0] - 2020-05-23 23 | ### Added 24 | - Now you can set and update empty env-variables. 25 | - Now you can specify external .env-file as the third optional argument. 26 | - Now you can set the value with equals sign ("="). 27 | - Added a lot of unit-tests. 28 | - Added GitHub Actions integration. 29 | - Added GitHub Actions build status badge. 30 | - Added the command description. 31 | - Added support for using en external `.env` file when using "key=value" syntax. 32 | ### Changed 33 | - composer.json now includes needed laravel components. 34 | ### Fixed 35 | - Fixed compatibility with Laravel 6+. 36 | 37 | ## [1.0.0] - 2018-07-13 38 | ### Added 39 | - Initial release 40 | 41 | [1.1.1]: https://github.com/imliam/laravel-env-set-command/compare/1.1.0...1.1.1 42 | [1.1.0]: https://github.com/imliam/laravel-env-set-command/compare/1.0.0...1.1.0 43 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Contributions are **welcome** and will be fully **credited**. 4 | 5 | Please read and understand the contribution guide before creating an issue or pull request. 6 | 7 | ## Etiquette 8 | 9 | This project is open source, and as such, the maintainers give their free time to build and maintain the source code held within. They make the code freely available in the hope that it will be of use to other developers. It would be extremely unfair for them to suffer abuse or anger for their hard work. 10 | 11 | Please be considerate towards maintainers when raising issues or presenting pull requests. Let's show the world that developers are civilized and selfless people. 12 | 13 | It's the duty of the maintainer to ensure that all submissions to the project are of sufficient quality to benefit the project. Many developers have different skill sets, strengths, and weaknesses. Respect the maintainer's decision, and do not be upset or abusive if your submission is not used. 14 | 15 | ## Viability 16 | 17 | When requesting or submitting new features, first consider whether it might be useful to others. Open source projects are used by many developers, who may have entirely different needs to your own. Think about whether or not your feature is likely to be used by other users of the project. 18 | 19 | ## Procedure 20 | 21 | Before filing an issue: 22 | 23 | - Attempt to replicate the problem, to ensure that it wasn't a coincidental incident. 24 | - Check to make sure your feature suggestion isn't already present within the project. 25 | - Check the pull requests tab to ensure that the bug doesn't have a fix in progress. 26 | - Check the pull requests tab to ensure that the feature isn't already in progress. 27 | 28 | Before submitting a pull request: 29 | 30 | - Check the codebase to ensure that your feature doesn't already exist. 31 | - Check the pull requests to ensure that another person hasn't already submitted the feature or fix. 32 | 33 | ## Requirements 34 | 35 | - **[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](https://pear.php.net/package/PHP_CodeSniffer). 36 | 37 | - **Add tests!** - Your patch won't be accepted if it doesn't have tests. 38 | 39 | - **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date. 40 | 41 | - **Consider our release cycle** - We try to follow [SemVer v2.0.0](https://semver.org/). Randomly breaking public APIs is not an option. 42 | 43 | - **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. 44 | 45 | - **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](https://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting. 46 | 47 | **Happy coding**! 48 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) Liam Hammett 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Laravel `env:set` Command 2 | 3 | [![Latest Version on Packagist](https://img.shields.io/packagist/v/imliam/laravel-env-set-command.svg)](https://packagist.org/packages/imliam/laravel-env-set-command) 4 | [![Total Downloads](https://img.shields.io/packagist/dt/imliam/laravel-env-set-command.svg)](https://packagist.org/packages/imliam/laravel-env-set-command) 5 | [![License](https://img.shields.io/github/license/imliam/laravel-env-set-command.svg)](LICENSE.md) 6 | 7 | Set a .env file variable from the command line. 8 | 9 | ![Example command output](./screenshot.png) 10 | 11 | 12 | 13 | - [Laravel `env:set` Command](#laravel-setenv-command) 14 | - [Installation](#installation) 15 | - [Usage](#usage) 16 | - [Changelog](#changelog) 17 | - [Contributing](#contributing) 18 | - [Security](#security) 19 | - [Credits](#credits) 20 | - [License](#license) 21 | 22 | 23 | 24 | ## Installation 25 | 26 | You can install the package with [Composer](https://getcomposer.org/) using the following command: 27 | 28 | ```bash 29 | composer require imliam/laravel-env-set-command 30 | ``` 31 | 32 | ## Usage 33 | 34 | When running the `env:set` artisan command, you must provide both a key and value as two arguments. 35 | 36 | ```bash 37 | $ php artisan env:set app_name Example 38 | # Environment variable with key 'APP_NAME' has been changed from 'Laravel' to 'Example' 39 | ``` 40 | 41 | You can also set values with spaces by wrapping them in quotes. 42 | 43 | ```bash 44 | $ php artisan env:set app_name "Example App" 45 | # Environment variable with key 'APP_NAME' has been changed from 'Laravel' to '"Example App"' 46 | ``` 47 | 48 | The command will also create new environment variables if an existing one does not exist. 49 | 50 | ```bash 51 | $ php artisan env:set editor=vscode 52 | # A new environment variable with key 'EDITOR' has been set to 'vscode' 53 | ``` 54 | 55 | Instead of two arguments split by a space, you can also mimic the `.env` file format by supplying `KEY=VALUE`. 56 | 57 | ```bash 58 | $ php artisan env:set app_name=Example 59 | # Environment variable with key 'APP_NAME' has been changed from 'Laravel' to 'Example' 60 | ``` 61 | 62 | The command will do its best to stop any invalid inputs. 63 | 64 | ```bash 65 | $ php artisan env:set @pp_n@me Laravel 66 | # Invalid environment key @pp_n@me! Only use letters and underscores 67 | ``` 68 | 69 | You can specify the external `.env` file in the third optional argument. 70 | 71 | ```bash 72 | $ php artisan env:set APP_NAME TestApp /var/www/my_own_env.env 73 | # Environment variable with key 'APP_NAME' has been changed from 'Laravel' to 'TestApp' 74 | ``` 75 | 76 | Or in the second parameter if you use key=value syntax. 77 | ```bash 78 | $ php artisan env:set APP_NAME=TestApp /var/www/my_own_env.env 79 | # Environment variable with key 'APP_NAME' has been changed from 'Laravel' to 'TestApp' 80 | ``` 81 | 82 | ## Changelog 83 | 84 | Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently. 85 | 86 | ## Contributing 87 | 88 | Please see [CONTRIBUTING](CONTRIBUTING.md) for details. 89 | 90 | ### Security 91 | 92 | If you discover any security related issues, please email liam@liamhammett.com instead of using the issue tracker. 93 | 94 | ## Credits 95 | 96 | - [Liam Hammett](https://github.com/imliam) 97 | - [All Contributors](../../contributors) 98 | 99 | ## License 100 | 101 | The MIT License (MIT). Please see [License File](LICENSE.md) for more information. 102 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "imliam/laravel-env-set-command", 3 | "description": "Set a .env file variable from the command line", 4 | "keywords": [ 5 | "imliam", 6 | "laravel-env-set-command", 7 | "environment", 8 | "variables", 9 | "env", 10 | "artisan" 11 | ], 12 | "homepage": "https://github.com/imliam/laravel-env-set-command", 13 | "license": "MIT", 14 | "authors": [ 15 | { 16 | "name": "Liam Hammett", 17 | "email": "liam@liamhammett.com", 18 | "homepage": "https://liamhammett.com", 19 | "role": "Developer" 20 | } 21 | ], 22 | "require": { 23 | "php": "^8.0", 24 | "illuminate/support": "^11.0|^12.0", 25 | "illuminate/console": "^11.0|^12.0" 26 | }, 27 | "require-dev": { 28 | "orchestra/testbench": "^9.0|^10.0", 29 | "phpunit/phpunit": "^11.0", 30 | "roave/security-advisories": "dev-master" 31 | }, 32 | "autoload": { 33 | "psr-4": { 34 | "ImLiam\\EnvironmentSetCommand\\": "src" 35 | } 36 | }, 37 | "autoload-dev": { 38 | "psr-4": { 39 | "Tests\\": "tests/" 40 | } 41 | }, 42 | "config": { 43 | "sort-packages": true 44 | }, 45 | "extra": { 46 | "laravel": { 47 | "providers": [ 48 | "ImLiam\\EnvironmentSetCommand\\EnvironmentSetCommandServiceProvider" 49 | ] 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /phpunit.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 9 | ./tests/Unit 10 | 11 | 12 | 13 | 14 | ./app 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/imliam/laravel-env-set-command/079a4c2291540a92a82066b229869d57614459b1/screenshot.png -------------------------------------------------------------------------------- /src/EnvironmentSetCommand.php: -------------------------------------------------------------------------------- 1 | parseCommandArguments( 43 | $this->argument(self::ARGUMENT_KEY), 44 | $this->argument(self::ARGUMENT_VALUE), 45 | $this->argument(self::ARGUMENT_ENV_FILE) 46 | ); 47 | 48 | // Use system env file path if the argument env file path is not provided. 49 | $envFilePath = $envFilePath ?: App::environmentFilePath(); 50 | $this->info("The following environment file is used: '" . $envFilePath . "'"); 51 | } catch (InvalidArgumentException $e) { 52 | $this->error($e->getMessage()); 53 | return; 54 | } 55 | 56 | $content = file_get_contents($envFilePath); 57 | [$newEnvFileContent, $isNewVariableSet] = $this->setEnvVariable($content, $key, $value); 58 | 59 | if ($isNewVariableSet) { 60 | $this->info("A new environment variable with key '{$key}' has been set to '{$value}'"); 61 | } else { 62 | [$_, $oldValue] = explode('=', $this->readKeyValuePair($content, $key), 2); 63 | $this->info("Environment variable with key '{$key}' has been changed from '{$oldValue}' to '{$value}'"); 64 | } 65 | 66 | $this->writeFile($envFilePath, $newEnvFileContent); 67 | } 68 | 69 | /** 70 | * Set or update env-variable. 71 | * 72 | * @param string $envFileContent Content of the .env file. 73 | * @param string $key Name of the variable. 74 | * @param string $value Value of the variable. 75 | * 76 | * @return array [string newEnvFileContent, bool isNewVariableSet]. 77 | */ 78 | public function setEnvVariable(string $envFileContent, string $key, string $value): array 79 | { 80 | $oldPair = $this->readKeyValuePair($envFileContent, $key); 81 | 82 | // Wrap values that have a space or equals in quotes to escape them 83 | $trimmedValue = trim($value); 84 | if (!str_starts_with($trimmedValue, '"') && !str_ends_with($trimmedValue, '"') && preg_match('/\s/',$value) || strpos($value, '=') !== false) { 85 | $value = '"' . str_replace('"', '\"', $value) . '"'; 86 | } 87 | 88 | $newPair = $key . '=' . $value; 89 | 90 | // For existed key. 91 | if ($oldPair !== null) { 92 | $replaced = preg_replace('/^' . preg_quote($oldPair, '/') . '$/uimU', $newPair, $envFileContent); 93 | return [$replaced, false]; 94 | } 95 | 96 | // For a new key. 97 | return [$envFileContent . "\n" . $newPair . "\n", true]; 98 | } 99 | 100 | /** 101 | * Read the "key=value" string of a given key from an environment file. 102 | * This function returns original "key=value" string and doesn't modify it. 103 | * 104 | * @param string $envFileContent 105 | * @param string $key 106 | * 107 | * @return string|null Key=value string or null if the key is not exists. 108 | */ 109 | public function readKeyValuePair(string $envFileContent, string $key): ?string 110 | { 111 | // Match the given key at the beginning of a line 112 | if (preg_match("#^\s*{$key}\s*=\s*[^\r\n]*$#uimU", $envFileContent, $matches)) { 113 | return $matches[0]; 114 | } 115 | 116 | return null; 117 | } 118 | 119 | /** 120 | * Parse key, value and path to .env-file from command line arguments. 121 | * 122 | * @param string $_key 123 | * @param string|null $_value 124 | * @param string|null $_envFilePath 125 | * 126 | * @return string[] [string KEY, string value, ?string envFilePath]. 127 | */ 128 | public function parseCommandArguments(string $_key, ?string $_value, ?string $_envFilePath): array 129 | { 130 | $key = null; 131 | $value = null; 132 | $envFilePath = null; 133 | 134 | // Parse "key=value" key argument. 135 | if (preg_match('#^([^=]+)=(.*)$#umU', $_key, $matches)) { 136 | [1 => $key, 2 => $value] = $matches; 137 | 138 | // Use second argument as path to env file: 139 | if ($_value !== null) { 140 | $envFilePath = $_value; 141 | } 142 | } else { 143 | $key = $_key; 144 | $value = $_value; 145 | } 146 | 147 | // If the path to env file is not set, use third argument or return null (default system path). 148 | if ($envFilePath === null) { 149 | $envFilePath = $_envFilePath; 150 | } 151 | 152 | $this->assertKeyIsValid($key); 153 | 154 | // If the value contains spaces but not is not enclosed in quotes. 155 | if (preg_match('#^[^\'"].*\s+.*[^\'"]$#umU', $value)) { 156 | $value = '"' . $value . '"'; 157 | } 158 | 159 | return [strtoupper($key), $value, ($envFilePath === null ? null : realpath($envFilePath))]; 160 | } 161 | 162 | /** 163 | * Assert a given string is valid as an environment variable key. 164 | * 165 | * @param string $key 166 | * 167 | * @return bool Is key is valid. 168 | */ 169 | public function assertKeyIsValid(string $key): bool 170 | { 171 | if (Str::contains($key, '=')) { 172 | throw new InvalidArgumentException('Invalid environment key ' . $key 173 | . "! Environment key should not contain '='"); 174 | } 175 | 176 | if (!preg_match('/^[a-zA-Z_]+$/', $key)) { 177 | throw new InvalidArgumentException('Invalid environment key ' . $key 178 | . '! Only use letters and underscores'); 179 | } 180 | 181 | return true; 182 | } 183 | 184 | /** 185 | * Overwrite the contents of a file. 186 | * 187 | * @param string $path 188 | * @param string $contents 189 | * 190 | * @return boolean 191 | */ 192 | protected function writeFile(string $path, string $contents): bool 193 | { 194 | return (bool)file_put_contents($path, $contents, LOCK_EX); 195 | } 196 | } 197 | -------------------------------------------------------------------------------- /src/EnvironmentSetCommandServiceProvider.php: -------------------------------------------------------------------------------- 1 | app->bind('command.env:set', EnvironmentSetCommand::class); 23 | 24 | $this->commands([ 25 | 'command.env:set' 26 | ]); 27 | } 28 | } 29 | --------------------------------------------------------------------------------