GenerateAdminCommand.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  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. /** @var string[] */
  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. * {@inheritdoc}
  64. */
  65. protected function execute(InputInterface $input, OutputInterface $output)
  66. {
  67. $modelClass = Validators::validateClass($input->getArgument('model'));
  68. $modelClassBasename = current(array_slice(explode('\\', $modelClass), -1));
  69. $bundle = $this->getBundle($input->getOption('bundle') ?: $this->getBundleNameFromClass($modelClass));
  70. $adminClassBasename = $input->getOption('admin') ?: $modelClassBasename.'Admin';
  71. $adminClassBasename = Validators::validateAdminClassBasename($adminClassBasename);
  72. $managerType = $input->getOption('manager') ?: $this->getDefaultManagerType();
  73. $modelManager = $this->getModelManager($managerType);
  74. $skeletonDirectory = __DIR__.'/../Resources/skeleton';
  75. $adminGenerator = new AdminGenerator($modelManager, $skeletonDirectory);
  76. try {
  77. $adminGenerator->generate($bundle, $adminClassBasename, $modelClass);
  78. $output->writeln(sprintf(
  79. '%sThe admin class "<info>%s</info>" has been generated under the file "<info>%s</info>".',
  80. PHP_EOL,
  81. $adminGenerator->getClass(),
  82. realpath($adminGenerator->getFile())
  83. ));
  84. } catch (\Exception $e) {
  85. $this->writeError($output, $e->getMessage());
  86. }
  87. if ($controllerClassBasename = $input->getOption('controller')) {
  88. $controllerClassBasename = Validators::validateControllerClassBasename($controllerClassBasename);
  89. $controllerGenerator = new ControllerGenerator($skeletonDirectory);
  90. try {
  91. $controllerGenerator->generate($bundle, $controllerClassBasename);
  92. $output->writeln(sprintf(
  93. '%sThe controller class "<info>%s</info>" has been generated under the file "<info>%s</info>".',
  94. PHP_EOL,
  95. $controllerGenerator->getClass(),
  96. realpath($controllerGenerator->getFile())
  97. ));
  98. } catch (\Exception $e) {
  99. $this->writeError($output, $e->getMessage());
  100. }
  101. }
  102. if ($servicesFile = $input->getOption('services')) {
  103. $adminClass = $adminGenerator->getClass();
  104. $file = sprintf('%s/Resources/config/%s', $bundle->getPath(), $servicesFile);
  105. $servicesManipulator = new ServicesManipulator($file);
  106. $controllerName = $controllerClassBasename
  107. ? sprintf('%s:%s', $bundle->getName(), substr($controllerClassBasename, 0, -10))
  108. : 'SonataAdminBundle:CRUD'
  109. ;
  110. try {
  111. $id = $input->getOption('id') ?: $this->getAdminServiceId($bundle->getName(), $adminClassBasename);
  112. $servicesManipulator->addResource($id, $modelClass, $adminClass, $controllerName, $managerType);
  113. $output->writeln(sprintf(
  114. '%sThe service "<info>%s</info>" has been appended to the file <info>"%s</info>".',
  115. PHP_EOL,
  116. $id,
  117. realpath($file)
  118. ));
  119. } catch (\Exception $e) {
  120. $this->writeError($output, $e->getMessage());
  121. }
  122. }
  123. return 0;
  124. }
  125. /**
  126. * {@inheritdoc}
  127. */
  128. protected function interact(InputInterface $input, OutputInterface $output)
  129. {
  130. $questionHelper = $this->getQuestionHelper();
  131. $questionHelper->writeSection($output, 'Welcome to the Sonata admin generator');
  132. $modelClass = $this->askAndValidate(
  133. $input,
  134. $output,
  135. 'The fully qualified model class',
  136. $input->getArgument('model'),
  137. 'Sonata\AdminBundle\Command\Validators::validateClass'
  138. );
  139. $modelClassBasename = current(array_slice(explode('\\', $modelClass), -1));
  140. $bundleName = $this->askAndValidate(
  141. $input,
  142. $output,
  143. 'The bundle name',
  144. $input->getOption('bundle') ?: $this->getBundleNameFromClass($modelClass),
  145. 'Sensio\Bundle\GeneratorBundle\Command\Validators::validateBundleName'
  146. );
  147. $adminClassBasename = $this->askAndValidate(
  148. $input,
  149. $output,
  150. 'The admin class basename',
  151. $input->getOption('admin') ?: $modelClassBasename.'Admin',
  152. 'Sonata\AdminBundle\Command\Validators::validateAdminClassBasename'
  153. );
  154. if (count($this->getAvailableManagerTypes()) > 1) {
  155. $managerType = $this->askAndValidate(
  156. $input,
  157. $output,
  158. 'The manager type',
  159. $input->getOption('manager') ?: $this->getDefaultManagerType(),
  160. array($this, 'validateManagerType')
  161. );
  162. $input->setOption('manager', $managerType);
  163. }
  164. if ($this->askConfirmation($input, $output, 'Do you want to generate a controller', 'no', '?')) {
  165. $controllerClassBasename = $this->askAndValidate(
  166. $input,
  167. $output,
  168. 'The controller class basename',
  169. $input->getOption('controller') ?: $modelClassBasename.'AdminController',
  170. 'Sonata\AdminBundle\Command\Validators::validateControllerClassBasename'
  171. );
  172. $input->setOption('controller', $controllerClassBasename);
  173. }
  174. if ($this->askConfirmation($input, $output, 'Do you want to update the services YAML configuration file', 'yes', '?')) {
  175. $path = $this->getBundle($bundleName)->getPath().'/Resources/config/';
  176. $servicesFile = $this->askAndValidate(
  177. $input,
  178. $output,
  179. 'The services YAML configuration file',
  180. is_file($path.'admin.yml') ? 'admin.yml' : 'services.yml',
  181. 'Sonata\AdminBundle\Command\Validators::validateServicesFile'
  182. );
  183. $id = $this->askAndValidate(
  184. $input,
  185. $output,
  186. 'The admin service ID',
  187. $this->getAdminServiceId($bundleName, $adminClassBasename),
  188. 'Sonata\AdminBundle\Command\Validators::validateServiceId'
  189. );
  190. $input->setOption('services', $servicesFile);
  191. $input->setOption('id', $id);
  192. }
  193. $input->setArgument('model', $modelClass);
  194. $input->setOption('admin', $adminClassBasename);
  195. $input->setOption('bundle', $bundleName);
  196. }
  197. /**
  198. * @param string $managerType
  199. *
  200. * @return string
  201. *
  202. * @throws \InvalidArgumentException
  203. */
  204. public function validateManagerType($managerType)
  205. {
  206. $managerTypes = $this->getAvailableManagerTypes();
  207. if (!isset($managerTypes[$managerType])) {
  208. throw new \InvalidArgumentException(sprintf(
  209. 'Invalid manager type "%s". Available manager types are "%s".',
  210. $managerType,
  211. implode('", "', $managerTypes)
  212. ));
  213. }
  214. return $managerType;
  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. if ($questionHelper instanceof DialogHelper) {
  264. // @todo remove this BC code for SensioGeneratorBundle 2.3/2.4 after dropping support for Symfony 2.3
  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. private function askConfirmation(InputInterface $input, OutputInterface $output, $questionText, $default, $separator)
  272. {
  273. $questionHelper = $this->getQuestionHelper();
  274. if ($questionHelper instanceof DialogHelper) {
  275. // @todo remove this BC code for SensioGeneratorBundle 2.3/2.4 after dropping support for Symfony 2.3
  276. $question = $questionHelper->getQuestion($questionText, $default, $separator);
  277. return $questionHelper->askConfirmation($output, $question, ($default === 'no' ? false : true));
  278. }
  279. $question = new ConfirmationQuestion($questionHelper->getQuestion(
  280. $questionText,
  281. $default,
  282. $separator
  283. ), ($default === 'no' ? false : true));
  284. return $questionHelper->ask($input, $output, $question);
  285. }
  286. /**
  287. * @return string
  288. *
  289. * @throws \RuntimeException
  290. */
  291. private function getDefaultManagerType()
  292. {
  293. if (!$managerTypes = $this->getAvailableManagerTypes()) {
  294. throw new \RuntimeException('There are no model managers registered.');
  295. }
  296. return current($managerTypes);
  297. }
  298. /**
  299. * @param string $managerType
  300. *
  301. * @return ModelManagerInterface
  302. */
  303. private function getModelManager($managerType)
  304. {
  305. return $this->getContainer()->get('sonata.admin.manager.'.$managerType);
  306. }
  307. /**
  308. * @param string $bundleName
  309. * @param string $adminClassBasename
  310. *
  311. * @return string
  312. */
  313. private function getAdminServiceId($bundleName, $adminClassBasename)
  314. {
  315. $prefix = substr($bundleName, -6) == 'Bundle' ? substr($bundleName, 0, -6) : $bundleName;
  316. $suffix = substr($adminClassBasename, -5) == 'Admin' ? substr($adminClassBasename, 0, -5) : $adminClassBasename;
  317. $suffix = str_replace('\\', '.', $suffix);
  318. return Container::underscore(sprintf(
  319. '%s.admin.%s',
  320. $prefix,
  321. $suffix
  322. ));
  323. }
  324. /**
  325. * @return string[]
  326. */
  327. private function getAvailableManagerTypes()
  328. {
  329. $container = $this->getContainer();
  330. if (!$container instanceof Container) {
  331. return array();
  332. }
  333. if ($this->managerTypes === null) {
  334. $this->managerTypes = array();
  335. foreach ($container->getServiceIds() as $id) {
  336. if (strpos($id, 'sonata.admin.manager.') === 0) {
  337. $managerType = substr($id, 21);
  338. $this->managerTypes[$managerType] = $managerType;
  339. }
  340. }
  341. }
  342. return $this->managerTypes;
  343. }
  344. /**
  345. * @return KernelInterface
  346. */
  347. private function getKernel()
  348. {
  349. $application = $this->getApplication();
  350. /* @var $application Application */
  351. return $application->getKernel();
  352. }
  353. /**
  354. * @return QuestionHelper|DialogHelper
  355. */
  356. private function getQuestionHelper()
  357. {
  358. if (class_exists('Sensio\Bundle\GeneratorBundle\Command\Helper\DialogHelper')) {
  359. // @todo remove this BC code for SensioGeneratorBundle 2.3/2.4 after dropping support for Symfony 2.3
  360. $questionHelper = $this->getHelper('dialog');
  361. if (!$questionHelper instanceof DialogHelper) {
  362. $questionHelper = new DialogHelper();
  363. $this->getHelperSet()->set($questionHelper);
  364. }
  365. } else {
  366. $questionHelper = $this->getHelper('question');
  367. if (!$questionHelper instanceof QuestionHelper) {
  368. $questionHelper = new QuestionHelper();
  369. $this->getHelperSet()->set($questionHelper);
  370. }
  371. }
  372. return $questionHelper;
  373. }
  374. }