Last active
August 4, 2017 12:24
-
-
Save jgrossi/531b63718cb14d11ed0dcd6489a7d080 to your computer and use it in GitHub Desktop.
PHP command to switch PHP versions using Homebrew
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How to use
~/phpver
for example~/.bash_profile
or something similar: