Skip to content

Instantly share code, notes, and snippets.

@tored
Last active April 30, 2020 11:03
Show Gist options
  • Save tored/b500eb7c10fbabbe2043126e51caf2f7 to your computer and use it in GitHub Desktop.
Save tored/b500eb7c10fbabbe2043126e51caf2f7 to your computer and use it in GitHub Desktop.
Auto-download composer dependencies for php script
#!/usr/bin/env php
<?php
declare(strict_types=1);
const PHPS = 'phps';
const COMMENT = '#';
const BANG = '!';
if (empty($argv[1])) {
throw new RuntimeException("Missing php file");
}
$file = realpath($argv[1]);
if ($file === false) {
throw new RuntimeException("No such file {$argv[1]}");
}
function scanner(string $file): Generator
{
$fp = fopen($file, 'rb');
$found = false;
do {
$line = fgets($fp);
if ($line === false) {
break;
}
if ($line[0] === COMMENT && $line[1] !== BANG) {
$found = true;
yield $line;
} else if ($found === true) {
break;
}
} while (true);
fclose($fp);
}
function parser(Generator $scanner): Generator
{
foreach ($scanner as $line) {
$result = explode(PHPS, $line, 2);
if (isset($result[1])) {
yield trim($result[1]);
}
}
}
$scanner = scanner($file);
$parser = parser($scanner);
$dirname = md5($file);
$dir = sys_get_temp_dir() . '/' . PHPS . "/{$dirname}";
$dependencies = [];
$composer_json = "{$dir}/composer.json";
if (is_file($composer_json)) {
$json = file_get_contents($composer_json);
$data = json_decode($json);
if (isset($data->require)) {
foreach ($parser as $instruction) {
if (empty($data->require->{$instruction})) {
$dependencies[] = $instruction;
}
}
} else {
$dependencies = iterator_to_array($parser);
}
} else {
if (!is_dir($dir)) {
mkdir($dir, 0755, true);
}
$dependencies = iterator_to_array($parser);
if (empty($dependencies)) {
file_put_contents($composer_json, '{}');
system("composer dumpautoload -d {$dir}");
}
}
if (count($dependencies)) {
$packages = implode(' ', $dependencies);
system("composer require -d {$dir} {$packages}");
}
$autoloader = "{$dir}/vendor/autoload.php";
array_splice($argv, 0, 2);
$args = implode(' ', $argv);
system(PHP_BINARY . " -d auto_prepend_file={$autoloader} -f {$file} {$args}");
<?php
declare(strict_types=1);
# phps ramsey/uuid
# phps hashids/hashids
use Ramsey\Uuid\Uuid;
use Hashids\Hashids;
$uuid = Uuid::uuid4()->toString();
$hashids = new Hashids($uuid);
$id = $hashids->encode(1, 2, 3);
$numbers = $hashids->decode($id);
echo implode(' ', $numbers), PHP_EOL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment