Skip to content

Instantly share code, notes, and snippets.

@dnahrebecki
Created February 17, 2022 09:44
Show Gist options
  • Save dnahrebecki/b2a237fec52b6a6f533514caec578be2 to your computer and use it in GitHub Desktop.
Save dnahrebecki/b2a237fec52b6a6f533514caec578be2 to your computer and use it in GitHub Desktop.
Command for switching PHP versions [tested in Ubuntu only]
<?php
namespace App\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Webmozart\Assert\Assert;
class SwitchPhpCommand extends Command
{
/** @var string */
protected static $defaultName = 'devtools:php:switch';
/**
* {@inheritdoc}
*/
protected function configure()
{
$this
->setDefinition($this->createDefinition())
->setDescription('Switch php version.')
->addUsage('7.3')
->addUsage('7.1');
}
/**
* {@inheritdoc}
*/
public function getNativeDefinition()
{
return $this->createDefinition();
}
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$io = new SymfonyStyle($input, $output);
$io->newLine();
$phpVersion = $input->getArgument('version');
$restartServices = $input->getOption('restart');
$phpBin = sprintf('/usr/bin/php%s', $phpVersion);
if (!file_exists($phpBin)) {
$io->error(sprintf('PHP binary (%s) not found', $phpBin));
return;
}
shell_exec(sprintf('sudo ln -sfn %s /etc/alternatives/php', $phpBin));
if ($restartServices === true) {
$command = sprintf('sudo service nginx restart && sudo service php%s-fpm restart', $phpVersion);
$io->text(sprintf('Restarting services: <info>%s</info>', $command));
shell_exec($command);
}
$phpVersionOutput = shell_exec('php -v');
preg_match('/PHP (\d.\d.\d{1,2})/', $phpVersionOutput, $matches);
Assert::isArray($matches);
Assert::notEmpty($matches);
Assert::keyExists($matches, 1);
Assert::startsWith(
$matches[1],
$phpVersion,
sprintf('PHP version not changed. Expected: %s, current: %s', $phpVersion, $matches[1])
);
$io->success(sprintf('PHP version successfully changed: %s', $matches[1]));
}
/**
* {@inheritdoc}
*/
private function createDefinition()
{
return new InputDefinition([
new InputArgument('version', InputArgument::REQUIRED, 'PHP version.'),
new InputOption('restart', null, InputOption::VALUE_REQUIRED, 'Restart nginx and php-fpm', true),
]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment