deblan.tv/vendor/trinity/src/Trinity/Bundle/AdminBundle/Command/GenerateCrudCommand.php
2015-03-02 21:57:49 +01:00

742 lines
23 KiB
PHP

<?php
namespace Trinity\Bundle\AdminBundle\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Output\Output;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Sensio\Bundle\GeneratorBundle\Command\Helper\DialogHelper;
use Symfony\Component\Filesystem\Exception\IOException;
use Sensio\Bundle\GeneratorBundle\Command\Validators;
class GenerateCrudCommand extends ContainerAwareCommand
{
/**
* @see Command
*/
protected function configure()
{
$this
->setDefinition(array(
new InputOption('namespace', '', InputOption::VALUE_REQUIRED, 'The namespace of the bundle to create'),
new InputOption('bundle', '', InputOption::VALUE_REQUIRED, 'The bundle to generate model classes from'),
))
->setDescription('Generate basics files for the CRUD')
->setHelp(<<<EOT
EOT
)
->setName('generate:crud')
;
}
/**
* @see Command
*
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$dialog = $this->getDialogHelper();
$filesystem = $this->getContainer()->get('filesystem');
if ($input->isInteractive()) {
if (!$dialog->askConfirmation($output, $dialog->getQuestion('Do you confirm generation', 'yes', '?'), true)) {
$output->writeln(
array(
'',
'<error>Command aborted</error>',
''
)
);
return 1;
}
}
$dialog->writeSection($output, 'Welcome to the CRUD generation!');
/* ------------------------------------------ */
$output->writeln(
array(
'',
'<info>Help:</info>',
' Use <comment> \ </comment> for the namespace delimiter to avoid any problem.',
'',
' You can find the bundle name in the file <comment>app/AppKernel.php</comment> without <comment>()</comment>',
'',
)
);
$namespace = $dialog->askAndValidate(
$output,
$dialog->getQuestion('Bundle namespace', $input->getOption('namespace')),
array('Sensio\Bundle\GeneratorBundle\Command\Validators', 'validateBundleNamespace'),
false,
$input->getOption('namespace')
);
$input->setOption('namespace', $namespace);
$bundle = $dialog->askAndValidate(
$output,
$dialog->getQuestion('Bundle name', $input->getOption('bundle')),
array('Sensio\Bundle\GeneratorBundle\Command\Validators', 'validateBundleName'),
false,
$input->getOption('bundle')
);
$input->setOption('bundle', $bundle);
$kernel = $this->getContainer()->get('kernel');
$kernel->getBundle($bundle);
$namespace_explode = explode("\\",$namespace);
/* ------------------------------------------ */
// target dir
$path = dirname($this->getContainer()->getParameter('kernel.root_dir')).'/src'.DIRECTORY_SEPARATOR;
$path.= implode(DIRECTORY_SEPARATOR, $namespace_explode);
if (!$filesystem->exists($path)) {
$output->writeln(array('','<error>Command aborted. The directory '.$path.' doesn\'t exist.</error>',''));
return 1;
}
/* ------------------------------------------ */
$errors = array();
$runner = $dialog->getRunner($output, $errors);
/* ------------------------------------------ */
$output->writeln(array('','Step 1: <info>Generate CrudConfiguration</info>',''));
$model = str_replace($namespace_explode[0], '', $bundle);
$model = str_replace('Bundle','',$model);
$model = $dialog->ask($output, $dialog->getQuestion('Model', $model, ':'), $model);
$classNameConfiguration = $model.'CrudConfiguration';
$nameSpaceConfiguration = $namespace.'\Configuration';
$modelPeer = $model.'Peer';
$modelQuery = $model.'Query';
$routePrefix = $bundle.$model.'Admin';
$formNamespace = '';
$modelNamespace = '';
$class = '';
foreach ($namespace_explode as $dir) {
$formNamespace .= $dir."\\\\";
$modelNamespace .= $dir."\\\\";
$class .= $dir."\\";
}
$formNamespace .= 'Form\\Type';
$modelNamespace .= 'Model';
$class .= 'Model\\'.$model;
$formEditNew = $model.'Type';
$formFilter = $model.'FilterType';
$maxPerPage = $dialog->askAndValidate(
$output,
$dialog->getQuestion('Max per page', 20, ':'),
function ($answer) {
if (!is_numeric($answer)) {
throw new \RunTimeException(
'The value must be an integer'
);
}
return (int) $answer;
},
false,
20
);
$rankable = $dialog->askConfirmation(
$output,
$dialog->getQuestion('Rankable', 'no', ':'),
false
);
$order = null;
if ($rankable) {
$order = $dialog->select($output, $dialog->getQuestion('Rank order','ASC'), array('ASC', 'DESC'), 0);
}
$rankable = !$rankable ? 'false' : 'true';
$contentConfiguration = "<?php
namespace ".$nameSpaceConfiguration.";
class ".$classNameConfiguration." extends \\Trinity\\Bundle\\AdminBundle\\Configuration\\CrudConfiguration
{
public function __construct()
{
\$this
->setModelNamespace('".$modelNamespace."')
->setModel('".$model."')
->setModelPeer('".$modelPeer."')
->setModelQuery('".$modelQuery."')
->setRoutePrefix('".$routePrefix."')
->setFormNamespace('".$formNamespace."')
->setFormEdit('".$formEditNew."')
->setFormFilter('".$formFilter."')
->setFormNew('".$formEditNew."')
->setFieldsets(array(
'' => array(
'*',
),
))
->setMaxPerPage(".$maxPerPage.")
->setRankable(".$rankable.")";
$orderRankable = array(0 => 'ASC', 1 => 'DESC');
if ($order) {
$contentConfiguration .= "
->setSort('orderByRank', \\Criteria::".$orderRankable[$order].")
";
}
$contentConfiguration .= "
->setListTitle('".$model."')
->setNewTitle('New ".strtolower($model)."')
->setEditTitle('Edition of \"%id%\"')
// Listing:
// ->setFieldTemplate('visible', 'TrinityAdminBundle:BaseAdmin:bool.html.twig')
// ->setDisplayFields(array(
//
// ))
// ->setFieldname('foo', 'bar')
;
}
}
";
//demande si ok ?
$output->writeln($contentConfiguration);
if ($input->isInteractive()) {
if (!$dialog->askConfirmation($output, $dialog->getQuestion('Do you agree', 'yes', '?'), true)) {
$output->writeln(
array(
'',
'<error>Command aborted</error>',
''
)
);
return 1;
}
}
// on regarde si le dossier configuration existe
$pathConfiguration = $path.DIRECTORY_SEPARATOR.'Configuration';
$configurationFile = $pathConfiguration.DIRECTORY_SEPARATOR.$classNameConfiguration.'.php';
try {
$filesystem->mkdir($pathConfiguration, 0777);
} catch (\IOException $e) {
$output->writeln(
array(
'',
'<error>$e</error>',
''
)
);
return 1;
}
if ($filesystem->exists($configurationFile)) {
$output->writeln(
array(
'',
'<info>The file '.$configurationFile.'</info> already exists.',
''
)
);
if ($input->isInteractive()) {
if ($dialog->askConfirmation($output, $dialog->getQuestion('Do you want to replace it', 'no', '?'), false)) {
$filesystem->remove($configurationFile);
$output->writeln(
array(
'',
'File <info>'.$configurationFile.'</info> <error>REMOVED</error>',
''
)
);
try {
$filesystem->touch($configurationFile, 0777);
file_put_contents($configurationFile, $contentConfiguration);
} catch (\IOException $e) {
$output->writeln(
array(
'',
'<error>$e</error>',
''
)
);
return 1;
}
}
}
} else {
try {
file_put_contents($configurationFile, $contentConfiguration);
} catch (\IOException $e) {
$output->writeln(
array(
'',
'<error>$e</error>',
''
)
);
return 1;
}
}
$output->writeln(array('', 'Generating the CRUD configuration: <info>OK</info>',''));
/* ------------------------------------------ */
$output->writeln(array('','Step 2: <info>Generate Controller</info>',''));
if ($input->isInteractive()) {
if (!$dialog->askConfirmation($output, $dialog->getQuestion('Continue', 'yes', '?'), true)) {
$output->writeln(
array(
'',
'<error>Command aborted</error>',
''
)
);
return 1;
}
}
$classNameController = $model.'AdminController';
$nameSpaceController = $namespace.'\Controller';
$contentController = '<?php
namespace '.$nameSpaceController.';
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Trinity\Bundle\AdminBundle\Controller\BaseAdminController;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpFoundation\Request;
use '.$nameSpaceConfiguration.'\\'.$classNameConfiguration.' as CrudConfiguration;
/**
* @Route("/admin/'.strtolower($model).'")
*/
class '.$classNameController.' extends BaseAdminController
{
public function __construct()
{
$this->configuration = new CrudConfiguration();
}
/**
* @Route("/{page}", name="'.$routePrefix.'_index", defaults={"page" = "1"}, requirements={"page" = "\d+"})
* @Template()
*/
public function indexAction($page, Request $request)
{
return parent::indexAction($page, $request);
}
/**
* @Route("/new", name="'.$routePrefix.'_new")
* @Template()
*/
public function newAction(Request $request)
{
return parent::newAction($request);
}
/**
* @Route("/edit/{id}", name="'.$routePrefix.'_edit")
* @Template()
* @ParamConverter("object", class="'.$class.'")
*/
public function editAction($object, Request $request)
{
return parent::editAction($object, $request);
}
/**
* @Route("/remove/{id}/{token}", name="'.$routePrefix.'_remove")
* @Template()
* @ParamConverter("object", class="'.$class.'")
*/
public function removeAction($object, $token, Request $request)
{
return parent::removeAction($object, $token, $request);
}
/**
* @Route("/batch", name="'.$routePrefix.'_batch")
* @Template()
* @Method({"POST"})
*/
public function batchAction(Request $request)
{
return parent::batchAction($request);
}
/**
* @Route("/filter/clear", name="'.$routePrefix.'_filter_clear")
* @Template()
*/
public function clearFilterAction(Request $request)
{
return parent::clearFilterAction($request);
}';
if ($rankable) {
$contentController .= '
/**
* @Route("/rank", name="'.$routePrefix.'_rank")
* @Template("TrinityAdminBundle:BaseAdmin:rank.html.twig")
* @Method({"POST"})
*/
public function rankAction(Request $request)
{
return parent::rankAction($request);
}';
}
$contentController .= '
}
';
$output->writeln($contentController);
if ($input->isInteractive()) {
if (!$dialog->askConfirmation($output, $dialog->getQuestion('Are you agree', 'yes', '?'), true)) {
$output->writeln(
array(
'',
'<error>Command aborted</error>',
''
)
);
return 1;
}
}
// on regarde si le dossier configuration existe
$pathController = $path.DIRECTORY_SEPARATOR.'Controller';
$controllerFile = $pathController.DIRECTORY_SEPARATOR.$classNameController.'.php';
try {
$filesystem->mkdir($pathController, 0777);
} catch (\IOException $e) {
$output->writeln(
array(
'',
'<error>$e</error>',
''
)
);
return 1;
}
if ($filesystem->exists($controllerFile)) {
$output->writeln(
array(
'',
'<info>The file '.$controllerFile.'</info> already exists.',
''
)
);
if ($input->isInteractive()) {
if ($dialog->askConfirmation($output, $dialog->getQuestion('Do you want to replace it', 'no', '?'), false)) {
$filesystem->remove($controllerFile);
$output->writeln(
array(
'',
'File <info>'.$controllerFile.'</info> <error>REMOVED</error>',
''
)
);
try {
$filesystem->touch($controllerFile, 0777);
file_put_contents($controllerFile, $contentController);
} catch (\IOException $e) {
$output->writeln(
array(
'',
'<error>$e</error>',
''
)
);
return 1;
}
}
}
} else {
try {
$filesystem->touch($controllerFile, 0777);
file_put_contents($controllerFile, $contentController);
} catch (\IOException $e) {
$output->writeln(
array(
'',
'<error>$e</error>',
''
)
);
return 1;
}
}
$output->writeln(array('', 'Generating the file Controller: <info>OK</info>',''));
/* ------------------------------------------ */
$output->writeln(array('','Step 3: <info>Generate views</info>',''));
$pathViews = $path.DIRECTORY_SEPARATOR.'Resources'.DIRECTORY_SEPARATOR.'views'.DIRECTORY_SEPARATOR.$model.'Admin';
try {
$filesystem->mkdir($pathViews, 0777);
} catch (\IOException $e) {
$output->writeln(
array(
'',
'<error>$e</error>',
''
)
);
return 1;
}
// test des fichiers de vues
if ($filesystem->exists($pathViews.DIRECTORY_SEPARATOR.'index.html.twig')) {
$output->writeln(
array(
'',
'<info>The file '.$pathViews.DIRECTORY_SEPARATOR.'index.html.twig</info> already exists.',
''
)
);
if ($input->isInteractive()) {
if ($dialog->askConfirmation($output, $dialog->getQuestion('Do you want to replace it', 'no', '?'), false)) {
$filesystem->remove($pathViews.DIRECTORY_SEPARATOR.'index.html.twig');
$output->writeln(
array(
'',
'File <info>'.$pathViews.DIRECTORY_SEPARATOR.'index.html.twig</info> <error>REMOVED</error>',
''
)
);
try {
$filesystem->touch($pathViews.DIRECTORY_SEPARATOR.'index.html.twig', 0777);
file_put_contents($pathViews.DIRECTORY_SEPARATOR.'index.html.twig', '{% extends "TrinityAdminBundle:BaseAdmin:index.html.twig" %}');
} catch (\IOException $e) {
$output->writeln(
array(
'',
'<error>$e</error>',
''
)
);
return 1;
}
}
}
} else {
try {
$filesystem->touch($pathViews.DIRECTORY_SEPARATOR.'index.html.twig', 0777);
file_put_contents($pathViews.DIRECTORY_SEPARATOR.'index.html.twig', '{% extends "TrinityAdminBundle:BaseAdmin:index.html.twig" %}');
} catch (\IOException $e) {
$output->writeln(
array(
'',
'<error>$e</error>',
''
)
);
return 1;
}
}
if ($filesystem->exists($pathViews.DIRECTORY_SEPARATOR.'edit.html.twig')) {
$output->writeln(
array(
'',
'<info>The file '.$pathViews.DIRECTORY_SEPARATOR.'edit.html.twig</info> already exists.',
''
)
);
if ($input->isInteractive()) {
if ($dialog->askConfirmation($output, $dialog->getQuestion('Do you want to replace it', 'no', '?'), false)) {
$filesystem->remove($pathViews.DIRECTORY_SEPARATOR.'edit.html.twig');
$output->writeln(
array(
'',
'File <info>'.$pathViews.DIRECTORY_SEPARATOR.'edit.html.twig</info> <error>REMOVED</error>',
''
)
);
try {
$filesystem->touch($pathViews.DIRECTORY_SEPARATOR.'edit.html.twig', 0777);
file_put_contents($pathViews.DIRECTORY_SEPARATOR.'edit.html.twig', '{% extends "TrinityAdminBundle:BaseAdmin:edit.html.twig" %}');
} catch (\IOException $e) {
$output->writeln(
array(
'',
'<error>$e</error>',
''
)
);
return 1;
}
}
}
} else {
try {
$filesystem->touch($pathViews.DIRECTORY_SEPARATOR.'edit.html.twig', 0777);
file_put_contents($pathViews.DIRECTORY_SEPARATOR.'edit.html.twig', '{% extends "TrinityAdminBundle:BaseAdmin:edit.html.twig" %}');
} catch (\IOException $e) {
$output->writeln(
array(
'',
'<error>$e</error>',
''
)
);
return 1;
}
}
if ($filesystem->exists($pathViews.DIRECTORY_SEPARATOR.'new.html.twig')) {
$output->writeln(
array(
'',
'<info>The file '.$pathViews.DIRECTORY_SEPARATOR.'new.html.twig</info> already exists.',
''
)
);
if ($input->isInteractive()) {
if ($dialog->askConfirmation($output, $dialog->getQuestion('Do you want to replace it', 'no', '?'), false)) {
$filesystem->remove($pathViews.DIRECTORY_SEPARATOR.'new.html.twig');
$output->writeln(
array(
'',
'File <info>'.$pathViews.DIRECTORY_SEPARATOR.'new.html.twig</info> <error>REMOVED</error>',
''
)
);
try {
$filesystem->touch($pathViews.DIRECTORY_SEPARATOR.'new.html.twig', 0777);
file_put_contents($pathViews.DIRECTORY_SEPARATOR.'new.html.twig', '{% extends "TrinityAdminBundle:BaseAdmin:new.html.twig" %}');
} catch (\IOException $e) {
$output->writeln(
array(
'',
'<error>$e</error>',
''
)
);
return 1;
}
}
}
} else {
try {
$filesystem->touch($pathViews.DIRECTORY_SEPARATOR.'new.html.twig', 0777);
file_put_contents($pathViews.DIRECTORY_SEPARATOR.'new.html.twig', '{% extends "TrinityAdminBundle:BaseAdmin:new.html.twig" %}');
} catch (\IOException $e) {
$output->writeln(
array(
'',
'<error>$e</error>',
''
)
);
return 1;
}
}
$output->writeln(array('', 'Generating views: <info>OK</info>',''));
/* ------------------------------------------ */
$dialog->writeGeneratorSummary($output, $errors);
}
protected function getDialogHelper()
{
$dialog = $this->getHelperSet()->get('dialog');
if (!$dialog || get_class($dialog) !== 'Sensio\Bundle\GeneratorBundle\Command\Helper\DialogHelper') {
$this->getHelperSet()->set($dialog = new DialogHelper());
}
return $dialog;
}
}