drupal-module-generator/src/Command/GenerateDrupal7Command.php

113 lines
2.8 KiB
PHP
Raw Normal View History

<?php
namespace Opdavies\DrupalModuleGenerator\Command;
use Opdavies\DrupalModuleGenerator\Exception\CannotCreateModuleException;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
2020-02-09 13:32:21 +00:00
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Finder\SplFileInfo;
2020-02-09 14:27:12 +00:00
use Tightenco\Collect\Support\Collection;
class GenerateDrupal7Command extends Command
{
2020-02-09 13:32:21 +00:00
/** @var Filesystem */
private $filesystem;
/** @var Finder */
private $finder;
/** @var SymfonyStyle $io */
private $io;
private $moduleName;
2020-02-09 13:32:21 +00:00
public function __construct(Finder $finder, string $name = null)
{
parent::__construct($name);
$this->finder = $finder;
}
/**
* {@inheritdoc}
*/
protected static $defaultName = 'generate-drupal-7-module';
/**
* {@inheritDoc}
*/
protected function configure()
{
$this
->setDescription('Generate a new Drupal 7 module.')
->addArgument('module-name', InputArgument::REQUIRED, 'The name of the module to create');
}
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
2020-02-09 13:32:21 +00:00
$this->io = new SymfonyStyle($input, $output);
2020-02-09 13:32:21 +00:00
$this->moduleName = $input->getArgument('module-name');
2020-02-09 13:32:21 +00:00
$this
->ensureDirectoryDoesNotExist()
->createModuleDirectory()
->createFiles();
2020-02-09 12:24:28 +00:00
return 0;
}
/**
* Ensure that the directory name for the module doesn't already exist.
*/
private function ensureDirectoryDoesNotExist()
{
if (is_dir($this->moduleName)) {
throw CannotCreateModuleException::directoryAlreadyExists();
}
2020-02-09 13:32:21 +00:00
return $this;
}
private function createModuleDirectory()
{
mkdir($this->moduleName);
return $this;
}
private function createFiles()
{
2020-02-09 14:27:12 +00:00
$createdFiles = new Collection();
2020-02-09 13:32:21 +00:00
/** @var SplFileInfo $file */
2020-02-09 13:55:11 +00:00
foreach ($this->finder->in('fixtures/drupal7_module')->name('/.[info,module]/') as $file) {
2020-02-09 13:32:21 +00:00
$contents = $this->updateFileContents($file->getContents());
file_put_contents(
"{$this->moduleName}/{$this->moduleName}.{$file->getExtension()}",
$contents
);
2020-02-09 14:27:12 +00:00
$createdFiles->push("{$this->moduleName}.{$file->getExtension()}");
2020-02-09 13:32:21 +00:00
}
2020-02-09 14:27:12 +00:00
$this->io->listing($createdFiles->sort()->toArray());
2020-02-09 13:32:21 +00:00
}
private function updateFileContents($contents)
{
$contents = str_replace('{{ name }}', $this->moduleName, $contents);
return $contents;
}
}