Skip to content

Instantly share code, notes, and snippets.

@jgrossi
Last active August 4, 2017 12:24
Show Gist options
  • Save jgrossi/531b63718cb14d11ed0dcd6489a7d080 to your computer and use it in GitHub Desktop.
Save jgrossi/531b63718cb14d11ed0dcd6489a7d080 to your computer and use it in GitHub Desktop.
PHP command to switch PHP versions using Homebrew
#!/usr/bin/php
<?php
if (!isset($argv[1])) {
echo_error("Please, tell me what PHP version you want!");
exit;
}
$to_version = $argv[1];
$to_version = (int)str_replace('.', '', $to_version);
@exec('php -v', $output);
if (!isset($output[0])) {
echo_error("It seems you don't have PHP installed");
exit;
}
preg_match('/PHP (\d+\.\d+)/', $output[0], $matches);
$from_version = str_replace('.', '', $matches[1]);
check_php_install($to_version, $from_version);
stop_php_services();
start_php($to_version);
echo_success("Done!");
system("php -v");
function echo_error($string) {
echo "\033[31m$string\033[0m\n";
}
function echo_info($string) {
echo "\033[36m$string\033[0m\n";
}
function echo_warning($string) {
echo "\033[33m$string\033[1m\n";
}
function echo_success($string) {
echo "\033[32m$string\033[0m\n";
}
function check_php_install($to_version, $from_version) {
@exec("brew list | grep php$to_version", $output);
if (count($output) === 0) {
echo_warning("Package php$to_version not found.");
stop_php_services();
echo_info("Installing php$to_version...");
@exec("brew install php$to_version");
}
}
function stop_php_services() {
@exec("brew services list | grep php", $output);
$pattern = "/^php(\d+)\s+([a-z]+)/";
foreach ($output as $line) {
preg_match($pattern, $line, $matches);
if (isset($matches[2])) {
if ($matches[2] === 'started') {
stop_php($matches[1]);
}
}
}
}
function start_php($version) {
echo_info("Starting php$version...");
@exec("brew services start php$version"); // TODO check if it's not started yet
@exec("brew link php$version"); // TODO check if it's not linked yet
}
function stop_php($version) {
echo_info("Stopping php$version...");
@exec("brew unlink php$version"); // TODO check if it's linked first
@exec("brew services stop php$version"); // TODO check if it's started
}
@jgrossi
Copy link
Author

jgrossi commented Feb 1, 2017

How to use

  1. Copy this file to ~/phpver for example
  2. Add an alias to your ~/.bash_profile or something similar:
alias phpver='php ~/phpver'
  1. Reload your bash file
source ~/.bash_profile
  1. Run the command to switch to PHP 5.6, for example. If it's not installed it'll be:
phpver 5.6

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment