GenerateAdminCommand.php 12 KB

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