#!/usr/bin/env php
<?php
// Set working dir
chdir(dirname(__DIR__));
if (is_console()) {
array_shift($argv);
$file = $argv[0];
if (file_exists($file)) {
// Read shebang
$fopen = fopen($file, 'rb');
$shebang = fgets($fopen);
fclose($fopen);
// Detect runner
$runner = 'sh'; // Default bash
if (strpos($shebang, 'bash') !== false) {
$runner = 'sh';
}
if (strpos($shebang, 'php') !== false) {
$runner = "php -d disable_functions=''";
}
if (strpos($shebang, 'node') !== false) {
$runner = 'npm';
}
if(command_exists($runner)) {
$command = $runner . ' ' . implode(' ', $argv);
// Print command for debug
echo '> ' . $command . PHP_EOL;
// Execute command with verbose
passthru($command);
} else {
echo "[ERROR] > You need to install `$runner` on your environment for run this script!";
}
}
}
/**
* Is console.
*
* @return bool
*/
function is_console()
{
return defined('STDIN') ||
php_sapi_name() === 'cli' ||
(empty($_SERVER['REMOTE_ADDR']) && !isset($_SERVER['HTTP_USER_AGENT']) && count($_SERVER['argv']) > 0);
}
/**
* Determines if a command exists on the current environment
*
* @param string $command The command to check
* @return bool True if the command has been found ; otherwise, false.
*/
function command_exists($command)
{
$whereIsCommand = (PHP_OS === 'WINNT') ? 'where' : 'which';
$process = proc_open(
"$whereIsCommand $command",
array(
0 => ["pipe", "r"], //STDIN
1 => ["pipe", "w"], //STDOUT
2 => ["pipe", "w"], //STDERR
),
$pipes
);
if ($process !== false) {
$stdout = stream_get_contents($pipes[1]);
$stderr = stream_get_contents($pipes[2]);
fclose($pipes[1]);
fclose($pipes[2]);
proc_close($process);
return $stdout != '';
}
return false;
}
|