GenerateAdminCommand.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. <?php
  2. /*
  3. * This file is part of the Sonata Project package.
  4. *
  5. * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Sonata\AdminBundle\Command;
  11. use Sensio\Bundle\GeneratorBundle\Command\Helper\DialogHelper;
  12. use Sensio\Bundle\GeneratorBundle\Command\Helper\QuestionHelper;
  13. use Sonata\AdminBundle\Generator\AdminGenerator;
  14. use Sonata\AdminBundle\Generator\ControllerGenerator;
  15. use Sonata\AdminBundle\Manipulator\ServicesManipulator;
  16. use Sonata\AdminBundle\Model\ModelManagerInterface;
  17. use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
  18. use Symfony\Bundle\FrameworkBundle\Console\Application;
  19. use Symfony\Component\Console\Input\InputArgument;
  20. use Symfony\Component\Console\Input\InputInterface;
  21. use Symfony\Component\Console\Input\InputOption;
  22. use Symfony\Component\Console\Output\OutputInterface;
  23. use Symfony\Component\Console\Question\ConfirmationQuestion;
  24. use Symfony\Component\Console\Question\Question;
  25. use Symfony\Component\DependencyInjection\Container;
  26. use Symfony\Component\HttpKernel\Bundle\BundleInterface;
  27. use Symfony\Component\HttpKernel\KernelInterface;
  28. /**
  29. * @author Marek Stipek <mario.dweller@seznam.cz>
  30. * @author Simon Cosandey <simon.cosandey@simseo.ch>
  31. */
  32. class GenerateAdminCommand extends ContainerAwareCommand
  33. {
  34. /** @var string[] */
  35. private $managerTypes;
  36. /**
  37. * {@inheritdoc}
  38. */
  39. public function configure()
  40. {
  41. $this
  42. ->setName('sonata:admin:generate')
  43. ->setDescription('Generates an admin class based on the given model class')
  44. ->addArgument('model', InputArgument::REQUIRED, 'The fully qualified model class')
  45. ->addOption('bundle', 'b', InputOption::VALUE_OPTIONAL, 'The bundle name')
  46. ->addOption('admin', 'a', InputOption::VALUE_OPTIONAL, 'The admin class basename')
  47. ->addOption('controller', 'c', InputOption::VALUE_OPTIONAL, 'The controller class basename')
  48. ->addOption('manager', 'm', InputOption::VALUE_OPTIONAL, 'The model manager type')
  49. ->addOption('services', 'y', InputOption::VALUE_OPTIONAL, 'The services YAML file', 'services.yml')
  50. ->addOption('id', 'i', InputOption::VALUE_OPTIONAL, 'The admin service ID')
  51. ;
  52. }
  53. /**
  54. * {@inheritdoc}
  55. */
  56. protected function execute(InputInterface $input, OutputInterface $output)
  57. {
  58. $modelClass = Validators::validateClass($input->getArgument('model'));
  59. $modelClassBasename = current(array_slice(explode('\\', $modelClass), -1));
  60. $bundle = $this->getBundle($input->getOption('bundle') ?: $this->getBundleNameFromClass($modelClass));
  61. $adminClassBasename = $input->getOption('admin') ?: $modelClassBasename.'Admin';
  62. $adminClassBasename = Validators::validateAdminClassBasename($adminClassBasename);
  63. $managerType = $input->getOption('manager') ?: $this->getDefaultManagerType();
  64. $modelManager = $this->getModelManager($managerType);
  65. $skeletonDirectory = __DIR__.'/../Resources/skeleton';
  66. $adminGenerator = new AdminGenerator($modelManager, $skeletonDirectory);
  67. try {
  68. $adminGenerator->generate($bundle, $adminClassBasename, $modelClass);
  69. $output->writeln(sprintf(
  70. '%sThe admin class "<info>%s</info>" has been generated under the file "<info>%s</info>".',
  71. PHP_EOL,
  72. $adminGenerator->getClass(),
  73. realpath($adminGenerator->getFile())
  74. ));
  75. } catch (\Exception $e) {
  76. $this->writeError($output, $e->getMessage());
  77. }
  78. if ($controllerClassBasename = $input->getOption('controller')) {
  79. $controllerClassBasename = Validators::validateControllerClassBasename($controllerClassBasename);
  80. $controllerGenerator = new ControllerGenerator($skeletonDirectory);
  81. try {
  82. $controllerGenerator->generate($bundle, $controllerClassBasename);
  83. $output->writeln(sprintf(
  84. '%sThe controller class "<info>%s</info>" has been generated under the file "<info>%s</info>".',
  85. PHP_EOL,
  86. $controllerGenerator->getClass(),
  87. realpath($controllerGenerator->getFile())
  88. ));
  89. } catch (\Exception $e) {
  90. $this->writeError($output, $e->getMessage());
  91. }
  92. }
  93. if ($servicesFile = $input->getOption('services')) {
  94. $adminClass = $adminGenerator->getClass();
  95. $file = sprintf('%s/Resources/config/%s', $bundle->getPath(), $servicesFile);
  96. $servicesManipulator = new ServicesManipulator($file);
  97. $controllerName = $controllerClassBasename
  98. ? sprintf('%s:%s', $bundle->getName(), substr($controllerClassBasename, 0, -10))
  99. : 'SonataAdminBundle:CRUD'
  100. ;
  101. try {
  102. $id = $input->getOption('id') ?: $this->getAdminServiceId($bundle->getName(), $adminClassBasename);
  103. $servicesManipulator->addResource($id, $modelClass, $adminClass, $controllerName, $managerType);
  104. $output->writeln(sprintf(
  105. '%sThe service "<info>%s</info>" has been appended to the file <info>"%s</info>".',
  106. PHP_EOL,
  107. $id,
  108. realpath($file)
  109. ));
  110. } catch (\Exception $e) {
  111. $this->writeError($output, $e->getMessage());
  112. }
  113. }
  114. return 0;
  115. }
  116. /**
  117. * {@inheritdoc}
  118. */
  119. protected function interact(InputInterface $input, OutputInterface $output)
  120. {
  121. $questionHelper = $this->getQuestionHelper();
  122. $questionHelper->writeSection($output, 'Welcome to the Sonata admin generator');
  123. $modelClass = $this->askAndValidate(
  124. $input,
  125. $output,
  126. 'The fully qualified model class',
  127. $input->getArgument('model'),
  128. 'Sonata\AdminBundle\Command\Validators::validateClass'
  129. );
  130. $modelClassBasename = current(array_slice(explode('\\', $modelClass), -1));
  131. $bundleName = $this->askAndValidate(
  132. $input,
  133. $output,
  134. 'The bundle name',
  135. $input->getOption('bundle') ?: $this->getBundleNameFromClass($modelClass),
  136. 'Sensio\Bundle\GeneratorBundle\Command\Validators::validateBundleName'
  137. );
  138. $adminClassBasename = $this->askAndValidate(
  139. $input,
  140. $output,
  141. 'The admin class basename',
  142. $input->getOption('admin') ?: $modelClassBasename.'Admin',
  143. 'Sonata\AdminBundle\Command\Validators::validateAdminClassBasename'
  144. );
  145. if (count($this->getAvailableManagerTypes()) > 1) {
  146. $managerType = $this->askAndValidate(
  147. $input,
  148. $output,
  149. 'The manager type',
  150. $input->getOption('manager') ?: $this->getDefaultManagerType(),
  151. array($this, 'validateManagerType')
  152. );
  153. $input->setOption('manager', $managerType);
  154. }
  155. if ($this->askConfirmation($input, $output, 'Do you want to generate a controller', 'no', '?')) {
  156. $controllerClassBasename = $this->askAndValidate(
  157. $input,
  158. $output,
  159. 'The controller class basename',
  160. $input->getOption('controller') ?: $modelClassBasename.'AdminController',
  161. 'Sonata\AdminBundle\Command\Validators::validateControllerClassBasename'
  162. );
  163. $input->setOption('controller', $controllerClassBasename);
  164. }
  165. if ($this->askConfirmation($input, $output, 'Do you want to update the services YAML configuration file', 'yes', '?')) {
  166. $path = $this->getBundle($bundleName)->getPath().'/Resources/config/';
  167. $servicesFile = $this->askAndValidate(
  168. $input,
  169. $output,
  170. 'The services YAML configuration file',
  171. is_file($path.'admin.yml') ? 'admin.yml' : 'services.yml',
  172. 'Sonata\AdminBundle\Command\Validators::validateServicesFile'
  173. );
  174. $id = $this->askAndValidate(
  175. $input,
  176. $output,
  177. 'The admin service ID',
  178. $this->getAdminServiceId($bundleName, $adminClassBasename),
  179. 'Sonata\AdminBundle\Command\Validators::validateServiceId'
  180. );
  181. $input->setOption('services', $servicesFile);
  182. $input->setOption('id', $id);
  183. }
  184. $input->setArgument('model', $modelClass);
  185. $input->setOption('admin', $adminClassBasename);
  186. $input->setOption('bundle', $bundleName);
  187. }
  188. /**
  189. * @param string $managerType
  190. *
  191. * @return string
  192. *
  193. * @throws \InvalidArgumentException
  194. */
  195. public function validateManagerType($managerType)
  196. {
  197. $managerTypes = $this->getAvailableManagerTypes();
  198. if (!isset($managerTypes[$managerType])) {
  199. throw new \InvalidArgumentException(sprintf(
  200. 'Invalid manager type "%s". Available manager types are "%s".',
  201. $managerType,
  202. implode('", "', $managerTypes)
  203. ));
  204. }
  205. return $managerType;
  206. }
  207. /**
  208. * @param string $class
  209. *
  210. * @return string|null
  211. *
  212. * @throws \InvalidArgumentException
  213. */
  214. private function getBundleNameFromClass($class)
  215. {
  216. $application = $this->getApplication();
  217. /* @var $application Application */
  218. foreach ($application->getKernel()->getBundles() as $bundle) {
  219. if (strpos($class, $bundle->getNamespace().'\\') === 0) {
  220. return $bundle->getName();
  221. }
  222. }
  223. return;
  224. }
  225. /**
  226. * @param string $name
  227. *
  228. * @return BundleInterface
  229. */
  230. private function getBundle($name)
  231. {
  232. return $this->getKernel()->getBundle($name);
  233. }
  234. /**
  235. * @param OutputInterface $output
  236. * @param string $message
  237. */
  238. private function writeError(OutputInterface $output, $message)
  239. {
  240. $output->writeln(sprintf("\n<error>%s</error>", $message));
  241. }
  242. /**
  243. * @param InputInterface $input
  244. * @param OutputInterface $output
  245. * @param string $questionText
  246. * @param mixed $default
  247. * @param callable $validator
  248. *
  249. * @return mixed
  250. */
  251. private function askAndValidate(InputInterface $input, OutputInterface $output, $questionText, $default, $validator)
  252. {
  253. $questionHelper = $this->getQuestionHelper();
  254. if ($questionHelper instanceof DialogHelper) {
  255. // @todo remove this BC code for SensioGeneratorBundle 2.3/2.4 after dropping support for Symfony 2.3
  256. return $questionHelper->askAndValidate($output, $questionHelper->getQuestion($questionText, $default), $validator, false, $default);
  257. }
  258. $question = new Question($questionHelper->getQuestion($questionText, $default), $default);
  259. $question->setValidator($validator);
  260. return $questionHelper->ask($input, $output, $question);
  261. }
  262. private function askConfirmation(InputInterface $input, OutputInterface $output, $questionText, $default, $separator)
  263. {
  264. $questionHelper = $this->getQuestionHelper();
  265. if ($questionHelper instanceof DialogHelper) {
  266. // @todo remove this BC code for SensioGeneratorBundle 2.3/2.4 after dropping support for Symfony 2.3
  267. $question = $questionHelper->getQuestion($questionText, $default, $separator);
  268. return $questionHelper->askConfirmation($output, $question, ($default === 'no' ? false : true));
  269. }
  270. $question = new ConfirmationQuestion($questionHelper->getQuestion(
  271. $questionText,
  272. $default,
  273. $separator
  274. ), ($default === 'no' ? false : true));
  275. return $questionHelper->ask($input, $output, $question);
  276. }
  277. /**
  278. * @return string
  279. *
  280. * @throws \RuntimeException
  281. */
  282. private function getDefaultManagerType()
  283. {
  284. if (!$managerTypes = $this->getAvailableManagerTypes()) {
  285. throw new \RuntimeException('There are no model managers registered.');
  286. }
  287. return current($managerTypes);
  288. }
  289. /**
  290. * @param string $managerType
  291. *
  292. * @return ModelManagerInterface
  293. */
  294. private function getModelManager($managerType)
  295. {
  296. return $this->getContainer()->get('sonata.admin.manager.'.$managerType);
  297. }
  298. /**
  299. * @param string $bundleName
  300. * @param string $adminClassBasename
  301. *
  302. * @return string
  303. */
  304. private function getAdminServiceId($bundleName, $adminClassBasename)
  305. {
  306. $prefix = substr($bundleName, -6) == 'Bundle' ? substr($bundleName, 0, -6) : $bundleName;
  307. $suffix = substr($adminClassBasename, -5) == 'Admin' ? substr($adminClassBasename, 0, -5) : $adminClassBasename;
  308. $suffix = str_replace('\\', '.', $suffix);
  309. return Container::underscore(sprintf(
  310. '%s.admin.%s',
  311. $prefix,
  312. $suffix
  313. ));
  314. }
  315. /**
  316. * @return string[]
  317. */
  318. private function getAvailableManagerTypes()
  319. {
  320. $container = $this->getContainer();
  321. if (!$container instanceof Container) {
  322. return array();
  323. }
  324. if ($this->managerTypes === null) {
  325. $this->managerTypes = array();
  326. foreach ($container->getServiceIds() as $id) {
  327. if (strpos($id, 'sonata.admin.manager.') === 0) {
  328. $managerType = substr($id, 21);
  329. $this->managerTypes[$managerType] = $managerType;
  330. }
  331. }
  332. }
  333. return $this->managerTypes;
  334. }
  335. /**
  336. * @return KernelInterface
  337. */
  338. private function getKernel()
  339. {
  340. $application = $this->getApplication();
  341. /* @var $application Application */
  342. return $application->getKernel();
  343. }
  344. /**
  345. * @return QuestionHelper|DialogHelper
  346. */
  347. private function getQuestionHelper()
  348. {
  349. if (class_exists('Sensio\Bundle\GeneratorBundle\Command\Helper\DialogHelper')) {
  350. // @todo remove this BC code for SensioGeneratorBundle 2.3/2.4 after dropping support for Symfony 2.3
  351. $questionHelper = $this->getHelper('dialog');
  352. if (!$questionHelper instanceof DialogHelper) {
  353. $questionHelper = new DialogHelper();
  354. $this->getHelperSet()->set($questionHelper);
  355. }
  356. } else {
  357. $questionHelper = $this->getHelper('question');
  358. if (!$questionHelper instanceof QuestionHelper) {
  359. $questionHelper = new QuestionHelper();
  360. $this->getHelperSet()->set($questionHelper);
  361. }
  362. }
  363. return $questionHelper;
  364. }
  365. }