GenerateAdminCommand.php 15 KB

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