Skip to content

Instantly share code, notes, and snippets.

@paulshryock
Last active December 21, 2023 12:50
Show Gist options
  • Save paulshryock/f5d1fe8ff1240e8bd8a56a1971781adf to your computer and use it in GitHub Desktop.
Save paulshryock/f5d1fe8ff1240e8bd8a56a1971781adf to your computer and use it in GitHub Desktop.
Paul's PHP Version Manager
#!/usr/bin/env bash
##
# Paul's PHP version manager. Runs on Homebrew.
#
# @param {string} $version PHP version to switch to or install.
# @return {void}
#
# @see https://github.com/shivammathur/homebrew-php
##
function ppvm() {
if [[ $(which brew) == 'brew not found' ]]; then
echo -n '[ppvm] Homebrew is not installed. Would you like to install it? [y/n]: '
read SHOULD_INSTALL
if [[ $SHOULD_INSTALL == y ]] then;
echo '[ppvm] Installing Homebrew...'
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
else
echo '[ppvm] PPVM requires Homebrew: https://brew.sh/'
return 1
fi
fi
local -r EARLIEST_VERSION=5.6
local -r LATEST_VERSION=8.4
local -r CURRENT_VERSION=$(php --version | egrep -o "\d*\.\d*" | head -n 1) >& /dev/null
local -r VERSION=${${1:-$CURRENT_VERSION}:-$LATEST_VERSION}
local -r IS_INSTALLED=$(brew ls --versions "php@$VERSION")
if [[ $VERSION < $EARLIEST_VERSION ]]; then
echo "[ppvm] unsuppored PHP version ($VERSION)"
return 1
fi
if [[ ! $VERSION =~ '[0-9]+\.[0-9]+' ]]; then
echo "[ppvm] invalid PHP version ($VERSION)"
return 1
fi
if [[ $CURRENT_VERSION == $VERSION ]]; then
php --version
return 0
fi
echo "[ppvm] unlinking PHP $CURRENT_VERSION... "
brew unlink "php@$CURRENT_VERSION" > /dev/null
brew unlink "shivammathur/php/php@$CURRENT_VERSION" > /dev/null
if [[ $IS_INSTALLED ]]; then
echo "[ppvm] upgrading PHP $VERSION... "
brew upgrade "shivammathur/php/php@$VERSION" > /dev/null
else
echo "[ppvm] installing PHP $VERSION... "
brew tap shivammathur/php > /dev/null
brew install "shivammathur/php/php@$VERSION" > /dev/null
fi
echo "[ppvm] switching to PHP $VERSION... "
brew link --force --overwrite "shivammathur/php/php@$VERSION" > /dev/null
echo "[ppvm] updating path..."
export PATH="$(echo $PATH | sed -E 's/\/usr\/local\/opt\/php(@[0-9]+\.[0-9]+)?\/s?bin:?//g'):/usr/local/opt/php@$VERSION/bin:/usr/local/opt/php@$VERSION/sbin"
php --version
}
function ppvm_cleanup() {
rm -rf $(brew --cellar)/php
rm -f ~/Library/LaunchAgents/homebrew.mxcl.php*
rm -f /Library/LaunchAgents/homebrew.mxcl.php*
rm -f /Library/LaunchDaemons/homebrew.mxcl.php*
brew untap homebrew/php
brew untap exolnet/deprecated
brew cleanup
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment