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. * @param string $managerType
  66. *
  67. * @return string
  68. *
  69. * @throws \InvalidArgumentException
  70. */
  71. public function validateManagerType($managerType)
  72. {
  73. $managerTypes = $this->getAvailableManagerTypes();
  74. if (!isset($managerTypes[$managerType])) {
  75. throw new \InvalidArgumentException(sprintf(
  76. 'Invalid manager type "%s". Available manager types are "%s".',
  77. $managerType,
  78. implode('", "', $managerTypes)
  79. ));
  80. }
  81. return $managerType;
  82. }
  83. /**
  84. * {@inheritdoc}
  85. */
  86. protected function execute(InputInterface $input, OutputInterface $output)
  87. {
  88. $modelClass = Validators::validateClass($input->getArgument('model'));
  89. $modelClassBasename = current(array_slice(explode('\\', $modelClass), -1));
  90. $bundle = $this->getBundle($input->getOption('bundle') ?: $this->getBundleNameFromClass($modelClass));
  91. $adminClassBasename = $input->getOption('admin') ?: $modelClassBasename.'Admin';
  92. $adminClassBasename = Validators::validateAdminClassBasename($adminClassBasename);
  93. $managerType = $input->getOption('manager') ?: $this->getDefaultManagerType();
  94. $modelManager = $this->getModelManager($managerType);
  95. $skeletonDirectory = __DIR__.'/../Resources/skeleton';
  96. $adminGenerator = new AdminGenerator($modelManager, $skeletonDirectory);
  97. try {
  98. $adminGenerator->generate($bundle, $adminClassBasename, $modelClass);
  99. $output->writeln(sprintf(
  100. '%sThe admin class "<info>%s</info>" has been generated under the file "<info>%s</info>".',
  101. PHP_EOL,
  102. $adminGenerator->getClass(),
  103. realpath($adminGenerator->getFile())
  104. ));
  105. } catch (\Exception $e) {
  106. $this->writeError($output, $e->getMessage());
  107. }
  108. if ($controllerClassBasename = $input->getOption('controller')) {
  109. $controllerClassBasename = Validators::validateControllerClassBasename($controllerClassBasename);
  110. $controllerGenerator = new ControllerGenerator($skeletonDirectory);
  111. try {
  112. $controllerGenerator->generate($bundle, $controllerClassBasename);
  113. $output->writeln(sprintf(
  114. '%sThe controller class "<info>%s</info>" has been generated under the file "<info>%s</info>".',
  115. PHP_EOL,
  116. $controllerGenerator->getClass(),
  117. realpath($controllerGenerator->getFile())
  118. ));
  119. } catch (\Exception $e) {
  120. $this->writeError($output, $e->getMessage());
  121. }
  122. }
  123. if ($servicesFile = $input->getOption('services')) {
  124. $adminClass = $adminGenerator->getClass();
  125. $file = sprintf('%s/Resources/config/%s', $bundle->getPath(), $servicesFile);
  126. $servicesManipulator = new ServicesManipulator($file);
  127. $controllerName = $controllerClassBasename
  128. ? sprintf('%s:%s', $bundle->getName(), substr($controllerClassBasename, 0, -10))
  129. : 'SonataAdminBundle:CRUD'
  130. ;
  131. try {
  132. $id = $input->getOption('id') ?: $this->getAdminServiceId($bundle->getName(), $adminClassBasename);
  133. $servicesManipulator->addResource($id, $modelClass, $adminClass, $controllerName, $managerType);
  134. $output->writeln(sprintf(
  135. '%sThe service "<info>%s</info>" has been appended to the file <info>"%s</info>".',
  136. PHP_EOL,
  137. $id,
  138. realpath($file)
  139. ));
  140. } catch (\Exception $e) {
  141. $this->writeError($output, $e->getMessage());
  142. }
  143. }
  144. return 0;
  145. }
  146. /**
  147. * {@inheritdoc}
  148. */
  149. protected function interact(InputInterface $input, OutputInterface $output)
  150. {
  151. $questionHelper = $this->getQuestionHelper();
  152. $questionHelper->writeSection($output, 'Welcome to the Sonata admin generator');
  153. $modelClass = $this->askAndValidate(
  154. $input,
  155. $output,
  156. 'The fully qualified model class',
  157. $input->getArgument('model'),
  158. 'Sonata\AdminBundle\Command\Validators::validateClass'
  159. );
  160. $modelClassBasename = current(array_slice(explode('\\', $modelClass), -1));
  161. $bundleName = $this->askAndValidate(
  162. $input,
  163. $output,
  164. 'The bundle name',
  165. $input->getOption('bundle') ?: $this->getBundleNameFromClass($modelClass),
  166. 'Sensio\Bundle\GeneratorBundle\Command\Validators::validateBundleName'
  167. );
  168. $adminClassBasename = $this->askAndValidate(
  169. $input,
  170. $output,
  171. 'The admin class basename',
  172. $input->getOption('admin') ?: $modelClassBasename.'Admin',
  173. 'Sonata\AdminBundle\Command\Validators::validateAdminClassBasename'
  174. );
  175. if (count($this->getAvailableManagerTypes()) > 1) {
  176. $managerType = $this->askAndValidate(
  177. $input,
  178. $output,
  179. 'The manager type',
  180. $input->getOption('manager') ?: $this->getDefaultManagerType(),
  181. array($this, 'validateManagerType')
  182. );
  183. $input->setOption('manager', $managerType);
  184. }
  185. if ($this->askConfirmation($input, $output, 'Do you want to generate a controller', 'no', '?')) {
  186. $controllerClassBasename = $this->askAndValidate(
  187. $input,
  188. $output,
  189. 'The controller class basename',
  190. $input->getOption('controller') ?: $modelClassBasename.'AdminController',
  191. 'Sonata\AdminBundle\Command\Validators::validateControllerClassBasename'
  192. );
  193. $input->setOption('controller', $controllerClassBasename);
  194. }
  195. if ($this->askConfirmation($input, $output, 'Do you want to update the services YAML configuration file', 'yes', '?')) {
  196. $path = $this->getBundle($bundleName)->getPath().'/Resources/config/';
  197. $servicesFile = $this->askAndValidate(
  198. $input,
  199. $output,
  200. 'The services YAML configuration file',
  201. is_file($path.'admin.yml') ? 'admin.yml' : 'services.yml',
  202. 'Sonata\AdminBundle\Command\Validators::validateServicesFile'
  203. );
  204. $id = $this->askAndValidate(
  205. $input,
  206. $output,
  207. 'The admin service ID',
  208. $this->getAdminServiceId($bundleName, $adminClassBasename),
  209. 'Sonata\AdminBundle\Command\Validators::validateServiceId'
  210. );
  211. $input->setOption('services', $servicesFile);
  212. $input->setOption('id', $id);
  213. }
  214. $input->setArgument('model', $modelClass);
  215. $input->setOption('admin', $adminClassBasename);
  216. $input->setOption('bundle', $bundleName);
  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. }