Skip to content

Instantly share code, notes, and snippets.

@KABBOUCHI
Forked from simonhamp/RemoteArtisan.php
Created December 21, 2017 18:53
Show Gist options
  • Save KABBOUCHI/93e287a2050c7f4c43ad737541c3ecb7 to your computer and use it in GitHub Desktop.
Save KABBOUCHI/93e287a2050c7f4c43ad737541c3ecb7 to your computer and use it in GitHub Desktop.
RemoteArtisan: A way to call another Laravel/Lumen application's artisan command from the context of the current application.
<?php
namespace App;
use Dotenv\Dotenv;
use Symfony\Component\Process\Process;
class RemoteArtisan
{
/**
* Implements an interface similar to Artisan::call.
*
* @param string $path The full path to the remote application's root
* @param string $command The Artisan command to run, e.g. 'vendor:publish'
* @param array $parameters The parameters to pass to the artisan command
* @param string $php The path to the PHP executable
* @return mixed
* @throws \Exception
*/
public static function call($path, $command, $parameters = [], $php = null)
{
// Prepare parameters for appending
$options = '';
foreach ($parameters as $name => $value) {
$value = '"'.$value.'"';
if (is_int($name)) {
$options .= " $value";
} else {
$value = ($value ?: "=$value");
$options .= " {$name}{$value}";
}
}
// Swap out the full path to the current PHP executable binary
if (! $php) {
$php = PHP_BINDIR . '/php';
}
// Load .env for the target app
$env = new Dotenv($path);
$env->overload();
// Append the artisan command to the path
$artisan = str_finish($path, '/').'artisan';
// Build up the final command
$command = "{$php} {$artisan} {$command}{$options}";
// Run the command in its environment
$process = new Process($command, $path);
$process->run();
// Restore original environment
$env = new Dotenv(base_path());
$env->overload();
// If there was no response
if (! $process->isSuccessful()) {
throw new \Exception("Command failed with exit code {$process->getExitCode()}.", $process->getExitCode());
}
return $process->getOutput();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment