Skip to content

Instantly share code, notes, and snippets.

@gnutix
Last active February 25, 2022 16:12
Show Gist options
  • Save gnutix/e26cb1952368b53e148bc675cae1ce3d to your computer and use it in GitHub Desktop.
Save gnutix/e26cb1952368b53e148bc675cae1ce3d to your computer and use it in GitHub Desktop.
Example of a self-contained, minimalist Symfony Console application
#!/usr/bin/env php
<?php
declare(strict_types=1);
use Imagecow\Image;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Filesystem\Filesystem;
set_time_limit(0);
umask(0000);
/** @noinspection PhpIncludeInspection */
require (static function (): string {
$dir = \dirname(__DIR__);
while (!file_exists($dir . '/vendor/autoload.php')) {
$dir = \dirname($dir);
if ('/' === $dir) {
throw new \UnexpectedValueException('Can\'t find a parent folder containing Composer\'s autoloader');
}
}
return $dir . '/vendor/autoload.php';
})();
$command = new class('crop:balanced') extends Command
{
protected function configure(): void
{
$this
->addArgument('sourceImagePath', InputArgument::REQUIRED, 'Absolute path to the input image')
->addArgument('imagePath', InputArgument::REQUIRED, 'Absolute path to the output image')
->addArgument('width', InputArgument::REQUIRED, 'Width for the crop')
->addArgument('height', InputArgument::REQUIRED, 'Height for the crop');
}
protected function execute(InputInterface $input, OutputInterface $output): void
{
$imagePath = $input->getArgument('imagePath');
// Here we create the directory for the destination image, otherwise Imagick will crash
$directory = \dirname($imagePath);
if (!file_exists($directory)) {
(new Filesystem())->mkdir($directory);
/** @noinspection NotOptimalIfConditionsInspection */
if (!file_exists($directory)) {
throw new \RuntimeException(sprintf('Could not create folder "%s" for Imagick.', $directory));
}
}
Image::fromFile($input->getArgument('sourceImagePath'))
->crop($input->getArgument('width'), $input->getArgument('height'), Image::CROP_BALANCED)
->save($imagePath);
}
};
$application = (new Application())
->add($command)
->getApplication()
->setDefaultCommand($command->getName(), true)
->run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment