GenerateAdminCommand.php 15 KB

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