Skip to content

Instantly share code, notes, and snippets.

@rieschl
Created March 6, 2022 14:00
Show Gist options
  • Save rieschl/471d4026e9cda34ad4742e3bdb1a9cbe to your computer and use it in GitHub Desktop.
Save rieschl/471d4026e9cda34ad4742e3bdb1a9cbe to your computer and use it in GitHub Desktop.
PHP version based on composer.json

Use correct PHP version based on composer.json

Installation

Copy both files to /usr/local/bin or ~/bin and make the php file executable.

Usage

The php script will read the contents of composer.json (if any) and delegate to the correct php version.

<?php
declare(strict_types=1);
const DEFAULT_PHP_VERSION = '7.4';
echo (static function () {
if (!file_exists('composer.json')) {
return DEFAULT_PHP_VERSION;
}
try {
$composer = json_decode(file_get_contents('composer.json'), true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $exception) {
return DEFAULT_PHP_VERSION;
}
$version = $composer['require']['php'] ?? null;
if ($version === null) {
return DEFAULT_PHP_VERSION;
}
$version = str_replace(['||', ' ', '^', '~', '*'], ['|', '', '', '', ''], $version);
$version = explode('|', $version);
$version = $version[0];
$length = strlen($version);
if ($length === 3) {
return $version;
}
if ($length > 3) {
return substr($version, 0, 3);
}
return DEFAULT_PHP_VERSION;
})();
#!/bin/bash
SCRIPT_PATH="$(realpath "$0")"
SCRIPT_DIR="$(dirname "$SCRIPT_PATH")"
PHPVERSION="$(php7.4 "$SCRIPT_DIR"/getphp.php)"
PHPCMD="php${PHPVERSION}";
eval ${PHPCMD} $@
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment