Skip to content

Instantly share code, notes, and snippets.

@NasirNobin
Last active March 17, 2022 19:40
Show Gist options
  • Select an option

  • Save NasirNobin/3e5992608df21389dded1ac1661e1c7c to your computer and use it in GitHub Desktop.

Select an option

Save NasirNobin/3e5992608df21389dded1ac1661e1c7c to your computer and use it in GitHub Desktop.
This script that will read .valetphprc from the project root and will switch to that PHP version automatically. Moved here: https://github.com/NasirNobin/zsh-valet
# homebrew-instant-php-version-swap.zsh
#
# @author: NasirNobin
# @url https://gist.github.com/NasirNobin/3e5992608df21389dded1ac1661e1c7c
# @url https://github.com/seanyeh/autosrc
VALETPHPRC=".valetphprc"
VALETPHPRC_IGNORE=0
valetphprc_find(){
local curpath="$1"
while [ "$curpath" != "/" ]; do
local temp_file="$curpath/$VALETPHPRC"
if [ -r "$temp_file" ]; then
valetphprc_file="$temp_file"
return 0
fi
curpath=$(dirname "$curpath")
done
return 1
}
valetphprc_run() {
if [ "$VALETPHPRC_IGNORE" -eq 1 ]; then
return
fi
local cur_pwd="$(pwd)"
# If same dir, exit
if [ "$OLDPWD" = "$cur_pwd" ]; then
return
fi
valetphprc_find "$OLDPWD" && local prev_valetphprc="$valetphprc_file"
valetphprc_find "$cur_pwd" && local cur_valetphprc="$valetphprc_file"
# If same valetphprc, return
if [ "$prev_valetphprc" = "$cur_valetphprc" ]; then
return
fi
# change php path for default .valetphprc
if [ -n "$prev_valetphprc" ] && [ -n $VALETPHPRC_DEFAULT_PHP ]; then
valetphprc_change_php $VALETPHPRC_DEFAULT_PHP
fi
# change php path for current .valetphprc
if [ -n "$cur_valetphprc" ]; then
valetphprc_change_php $(cat $cur_valetphprc)
fi
}
valetphprc_change_php () {
PHP_VERSION="${1:-$VALETPHPRC_DEFAULT_PHP}"
PHP_VERSION=$(echo $PHP_VERSION | gsed "s,php,," | gsed "s,@,,")
PHP_VERSION_BIN_PATH="/opt/homebrew/opt/php@$PHP_VERSION/bin"
if [ -d "$PHP_VERSION_BIN_PATH" ]; then
export PATH=$(echo $PATH | gsed "s,/opt/homebrew/opt/php@.\../bin,$PHP_VERSION_BIN_PATH,g")
if [[ "$PATH" != *"$PHP_VERSION"* ]]; then
export PATH="$PHP_VERSION_BIN_PATH:$PATH"
fi
echo "Using $(php -v | grep -m1 "PHP")"
fi
}
autoload -U add-zsh-hook
add-zsh-hook chpwd valetphprc_run
# Call on startup as well
valetphprc_find "$(pwd)" && valetphprc_change_php $(cat $valetphprc_file)
@NasirNobin
Copy link
Author

NasirNobin commented Mar 15, 2022

Here's a quick video demonstration
CleanShot.2022-03-15.at.13.32.49.mp4

Steps:

  1. Source valet-automatic-php-version-swap-on-cli.zsh to your .zshrc file
  2. Create a file named .valetphprc in your project directory with following project's PHP version. Example:
  1. You can define a default PHP version on your .zshrc. This will be used to reset PHP Binary when you exit a project directory.
  1. Now when you cd into your project directory. It should automatically swap to PHP 8.1 binary for that session.

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