Commit 7fb9ab12 authored by Anton Smirnov's avatar Anton Smirnov

Add converter commands

parent 808fc5eb
<?php
namespace SandFox\ComposerYaml\Commands;
use SandFox\ComposerYaml\Helpers\JsonHelper;
use SandFox\ComposerYaml\Helpers\YamlHelper;
class CreateCommand extends RecodeCommand
{
protected function configure()
{
$this->setName('yaml:create');
$this->setDescription('Create composer.yml from composer.json');
parent::configure();
}
protected function recode($value)
{
return YamlHelper::encode(JsonHelper::decode($value));
}
protected function defaultInputFilename()
{
return 'composer.json';
}
protected function defaultOutputFilename()
{
return 'composer.yml';
}
}
<?php
namespace SandFox\ComposerYaml\Commands;
use SandFox\ComposerYaml\Helpers\JsonHelper;
use SandFox\ComposerYaml\Helpers\YamlHelper;
class DumpCommand extends RecodeCommand
{
protected function configure()
{
$this->setName('yaml:dump');
$this->setDescription('Create composer.json from composer.yml');
parent::configure();
}
protected function recode($value)
{
return JsonHelper::encode(YamlHelper::decode($value));
}
protected function defaultInputFilename()
{
// discovery
foreach (['composer.yml', 'composer.yaml'] as $file) {
if (file_exists($file)) {
return $file;
}
}
// fall back
return 'composer.yml';
}
protected function defaultOutputFilename()
{
return 'composer.json';
}
}
<?php
namespace SandFox\ComposerYaml\Commands;
use Composer\Command\BaseCommand;
use RuntimeException;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
abstract class RecodeCommand extends BaseCommand
{
protected function configure()
{
$this->addOption('input', 'i', InputOption::VALUE_REQUIRED, 'Override input file name');
$this->addOption('output', 'o', InputOption::VALUE_REQUIRED, 'Override output file name');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$inputFile = $input->getOption('input') ?: $this->defaultInputFilename();
$outputFile = $input->getOption('output') ?: $this->defaultOutputFilename();
if (!file_exists($inputFile)) {
throw new RuntimeException('Input file does not exist');
}
$data = file_get_contents($inputFile);
if ($data === false) {
throw new RuntimeException(sprintf('Unable to read input file "%s"', $inputFile));
}
$recoded = $this->recode($data);
$result = file_put_contents($outputFile, $recoded);
if ($result === false) {
throw new RuntimeException(sprintf('Unable to write to output file "%s"', $outputFile));
}
}
abstract protected function defaultInputFilename();
abstract protected function defaultOutputFilename();
abstract protected function recode($value);
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment