GenerateAdminCommand.php 13 KB

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