GenerateAdminCommandTest.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  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\Tests\Command;
  11. use Sonata\AdminBundle\Command\GenerateAdminCommand;
  12. use Sonata\AdminBundle\Tests\Fixtures\Bundle\DemoAdminBundle;
  13. use Symfony\Bundle\FrameworkBundle\Console\Application;
  14. use Symfony\Component\Console\Input\InputInterface;
  15. use Symfony\Component\Console\Output\OutputInterface;
  16. use Symfony\Component\Console\Question\Question;
  17. use Symfony\Component\Console\Tester\CommandTester;
  18. use Symfony\Component\DependencyInjection\Container;
  19. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
  20. /**
  21. * @author Andrej Hudec <pulzarraider@gmail.com>
  22. */
  23. class GenerateAdminCommandTest extends \PHPUnit_Framework_TestCase
  24. {
  25. /**
  26. * @var Application
  27. */
  28. private $application;
  29. /**
  30. * @var string
  31. */
  32. private $tempDirectory;
  33. /**
  34. * @var Container
  35. */
  36. private $container;
  37. /**
  38. * @var GenerateAdminCommand
  39. */
  40. private $command;
  41. protected function setUp()
  42. {
  43. // create temp dir
  44. $tempfile = tempnam(sys_get_temp_dir(), 'sonata_admin');
  45. if (file_exists($tempfile)) {
  46. unlink($tempfile);
  47. }
  48. mkdir($tempfile);
  49. $this->tempDirectory = $tempfile;
  50. $bundle = new DemoAdminBundle();
  51. $bundle->setPath($this->tempDirectory);
  52. $kernel = $this->getMock('Symfony\Component\HttpKernel\KernelInterface');
  53. $kernel->expects($this->any())
  54. ->method('getBundles')
  55. ->will($this->returnValue(array($bundle)));
  56. $parameterBag = new ParameterBag();
  57. $this->container = new Container($parameterBag);
  58. $kernel->expects($this->any())
  59. ->method('getBundle')
  60. ->with($this->equalTo('AcmeDemoBundle'))
  61. ->will($this->returnValue($bundle));
  62. $kernel->expects($this->any())
  63. ->method('getContainer')
  64. ->will($this->returnValue($this->container));
  65. $this->application = new Application($kernel);
  66. $this->command = new GenerateAdminCommand();
  67. $this->application->add($this->command);
  68. }
  69. public function tearDown()
  70. {
  71. if ($this->tempDirectory) {
  72. if (file_exists($this->tempDirectory.'/Controller/FooAdminController.php')) {
  73. unlink($this->tempDirectory.'/Controller/FooAdminController.php');
  74. }
  75. if (file_exists($this->tempDirectory.'/Admin/FooAdmin.php')) {
  76. unlink($this->tempDirectory.'/Admin/FooAdmin.php');
  77. }
  78. if (file_exists($this->tempDirectory.'/Resources/config/admin.yml')) {
  79. unlink($this->tempDirectory.'/Resources/config/admin.yml');
  80. }
  81. if (is_dir($this->tempDirectory.'/Controller')) {
  82. rmdir($this->tempDirectory.'/Controller');
  83. }
  84. if (is_dir($this->tempDirectory.'/Admin')) {
  85. rmdir($this->tempDirectory.'/Admin');
  86. }
  87. if (is_dir($this->tempDirectory.'/Resources/config')) {
  88. rmdir($this->tempDirectory.'/Resources/config');
  89. }
  90. if (is_dir($this->tempDirectory.'/Resources')) {
  91. rmdir($this->tempDirectory.'/Resources');
  92. }
  93. if (file_exists($this->tempDirectory) && is_dir($this->tempDirectory)) {
  94. rmdir($this->tempDirectory);
  95. }
  96. }
  97. }
  98. public function testExecute()
  99. {
  100. $this->command->setContainer($this->container);
  101. $this->container->set('sonata.admin.manager.foo', $this->getMock('Sonata\AdminBundle\Model\ModelManagerInterface'));
  102. $command = $this->application->find('sonata:admin:generate');
  103. $commandTester = new CommandTester($command);
  104. $commandTester->execute(array(
  105. 'command' => $command->getName(),
  106. 'model' => 'Sonata\AdminBundle\Tests\Fixtures\Bundle\Entity\Foo',
  107. '--bundle' => 'AcmeDemoBundle',
  108. '--admin' => 'FooAdmin',
  109. '--controller' => 'FooAdminController',
  110. '--services' => 'admin.yml',
  111. '--id' => 'acme_demo_admin.admin.foo',
  112. ), array('interactive' => false));
  113. $expectedOutput = '';
  114. $expectedOutput .= sprintf('%3$sThe admin class "Sonata\AdminBundle\Tests\Fixtures\Bundle\Admin\FooAdmin" has been generated under the file "%1$s%2$sAdmin%2$sFooAdmin.php".%3$s', $this->tempDirectory, DIRECTORY_SEPARATOR, PHP_EOL);
  115. $expectedOutput .= sprintf('%3$sThe controller class "Sonata\AdminBundle\Tests\Fixtures\Bundle\Controller\FooAdminController" has been generated under the file "%1$s%2$sController%2$sFooAdminController.php".%3$s', $this->tempDirectory, DIRECTORY_SEPARATOR, PHP_EOL);
  116. $expectedOutput .= sprintf('%3$sThe service "acme_demo_admin.admin.foo" has been appended to the file "%1$s%2$sResources%2$sconfig%2$sadmin.yml".%3$s', $this->tempDirectory, DIRECTORY_SEPARATOR, PHP_EOL);
  117. $this->assertSame($expectedOutput, $commandTester->getDisplay());
  118. $this->assertFileExists($this->tempDirectory.'/Admin/FooAdmin.php');
  119. $this->assertFileExists($this->tempDirectory.'/Controller/FooAdminController.php');
  120. $this->assertFileExists($this->tempDirectory.'/Resources/config/admin.yml');
  121. $adminContent = file_get_contents($this->tempDirectory.'/Admin/FooAdmin.php');
  122. $this->assertContains('class FooAdmin extends Admin', $adminContent);
  123. $this->assertContains('use Sonata\AdminBundle\Admin\Admin;', $adminContent);
  124. $this->assertContains('use Sonata\AdminBundle\Datagrid\DatagridMapper;', $adminContent);
  125. $this->assertContains('use Sonata\AdminBundle\Datagrid\ListMapper;', $adminContent);
  126. $this->assertContains('use Sonata\AdminBundle\Form\FormMapper;', $adminContent);
  127. $this->assertContains('use Sonata\AdminBundle\Show\ShowMapper;', $adminContent);
  128. $this->assertContains('protected function configureDatagridFilters(DatagridMapper $datagridMapper)', $adminContent);
  129. $this->assertContains('protected function configureListFields(ListMapper $listMapper)', $adminContent);
  130. $this->assertContains('protected function configureFormFields(FormMapper $formMapper)', $adminContent);
  131. $this->assertContains('protected function configureShowFields(ShowMapper $showMapper)', $adminContent);
  132. $controllerContent = file_get_contents($this->tempDirectory.'/Controller/FooAdminController.php');
  133. $this->assertContains('class FooAdminController extends CRUDController', $controllerContent);
  134. $this->assertContains('use Sonata\AdminBundle\Controller\CRUDController;', $controllerContent);
  135. $configServiceContent = file_get_contents($this->tempDirectory.'/Resources/config/admin.yml');
  136. $this->assertContains('services:'."\n".' acme_demo_admin.admin.foo', $configServiceContent);
  137. $this->assertContains(' - {name: sonata.admin, manager_type: foo, group: admin, label: Foo}', $configServiceContent);
  138. }
  139. public function testExecuteWithExceptionNoModelManagers()
  140. {
  141. $this->setExpectedException('RuntimeException', 'There are no model managers registered.');
  142. $this->command->setContainer($this->container);
  143. $command = $this->application->find('sonata:admin:generate');
  144. $commandTester = new CommandTester($command);
  145. $commandTester->execute(array(
  146. 'command' => $command->getName(),
  147. 'model' => 'Sonata\AdminBundle\Tests\Fixtures\Bundle\Entity\Foo',
  148. '--bundle' => 'AcmeDemoBundle',
  149. '--admin' => 'FooAdmin',
  150. '--controller' => 'FooAdminController',
  151. '--services' => 'admin.yml',
  152. '--id' => 'acme_demo_admin.admin.foo',
  153. ), array('interactive' => false));
  154. }
  155. /**
  156. * @dataProvider getExecuteInteractiveTests
  157. */
  158. public function testExecuteInteractive($modelEntity)
  159. {
  160. $this->command->setContainer($this->container);
  161. $this->container->set('sonata.admin.manager.foo', $this->getMock('Sonata\AdminBundle\Model\ModelManagerInterface'));
  162. $this->container->set('sonata.admin.manager.bar', $this->getMock('Sonata\AdminBundle\Model\ModelManagerInterface'));
  163. $command = $this->application->find('sonata:admin:generate');
  164. // @todo remove this BC code for SensioGeneratorBundle 2.3/2.4 after dropping support for Symfony 2.3
  165. // DialogHelper does not exist in SensioGeneratorBundle 2.5+
  166. if (class_exists('Sensio\Bundle\GeneratorBundle\Command\Helper\DialogHelper')) {
  167. $dialog = $this->getMock('Sensio\Bundle\GeneratorBundle\Command\Helper\DialogHelper', array('askConfirmation', 'askAndValidate'));
  168. $dialog->expects($this->any())
  169. ->method('askConfirmation')
  170. ->will($this->returnCallback(function (OutputInterface $output, $question, $default) {
  171. $questionClean = substr($question, 6, strpos($question, '</info>') - 6);
  172. switch ($questionClean) {
  173. case 'Do you want to generate a controller':
  174. return 'yes';
  175. break;
  176. case 'Do you want to update the services YAML configuration file':
  177. return 'yes';
  178. break;
  179. }
  180. return $default;
  181. }));
  182. $dialog->expects($this->any())
  183. ->method('askAndValidate')
  184. ->will($this->returnCallback(function (OutputInterface $output, $question, $validator, $attempts = false, $default = null) use ($modelEntity) {
  185. $questionClean = substr($question, 6, strpos($question, '</info>') - 6);
  186. switch ($questionClean) {
  187. case 'The fully qualified model class':
  188. return $modelEntity;
  189. break;
  190. case 'The bundle name':
  191. return 'AcmeDemoBundle';
  192. break;
  193. case 'The admin class basename':
  194. return 'FooAdmin';
  195. break;
  196. case 'The controller class basename':
  197. return 'FooAdminController';
  198. break;
  199. case 'The services YAML configuration file':
  200. return 'admin.yml';
  201. break;
  202. case 'The admin service ID':
  203. return 'acme_demo_admin.admin.foo';
  204. break;
  205. case 'The manager type':
  206. return 'foo';
  207. break;
  208. }
  209. return $default;
  210. }));
  211. $command->getHelperSet()->set($dialog, 'dialog');
  212. } else {
  213. $questionHelper = $this->getMock('Sensio\Bundle\GeneratorBundle\Command\Helper\QuestionHelper', array('ask'));
  214. $questionHelper->expects($this->any())
  215. ->method('ask')
  216. ->will($this->returnCallback(function (InputInterface $input, OutputInterface $output, Question $question) use ($modelEntity) {
  217. $questionClean = substr($question->getQuestion(), 6, strpos($question->getQuestion(), '</info>') - 6);
  218. switch ($questionClean) {
  219. // confirmations
  220. case 'Do you want to generate a controller':
  221. return 'yes';
  222. break;
  223. case 'Do you want to update the services YAML configuration file':
  224. return 'yes';
  225. break;
  226. // inputs
  227. case 'The fully qualified model class':
  228. return $modelEntity;
  229. break;
  230. case 'The bundle name':
  231. return 'AcmeDemoBundle';
  232. break;
  233. case 'The admin class basename':
  234. return 'FooAdmin';
  235. break;
  236. case 'The controller class basename':
  237. return 'FooAdminController';
  238. break;
  239. case 'The services YAML configuration file':
  240. return 'admin.yml';
  241. break;
  242. case 'The admin service ID':
  243. return 'acme_demo_admin.admin.foo';
  244. break;
  245. case 'The manager type':
  246. return 'foo';
  247. break;
  248. }
  249. return false;
  250. }));
  251. $command->getHelperSet()->set($questionHelper, 'question');
  252. }
  253. $commandTester = new CommandTester($command);
  254. $commandTester->execute(array(
  255. 'command' => $command->getName(),
  256. 'model' => $modelEntity,
  257. ));
  258. $expectedOutput = PHP_EOL.str_pad('', 41, ' ').PHP_EOL.' Welcome to the Sonata admin generator '.PHP_EOL.str_pad('', 41, ' ').PHP_EOL.PHP_EOL;
  259. $expectedOutput .= sprintf('%3$sThe admin class "Sonata\AdminBundle\Tests\Fixtures\Bundle\Admin\FooAdmin" has been generated under the file "%1$s%2$sAdmin%2$sFooAdmin.php".%3$s', $this->tempDirectory, DIRECTORY_SEPARATOR, PHP_EOL);
  260. $expectedOutput .= sprintf('%3$sThe controller class "Sonata\AdminBundle\Tests\Fixtures\Bundle\Controller\FooAdminController" has been generated under the file "%1$s%2$sController%2$sFooAdminController.php".%3$s', $this->tempDirectory, DIRECTORY_SEPARATOR, PHP_EOL);
  261. $expectedOutput .= sprintf('%3$sThe service "acme_demo_admin.admin.foo" has been appended to the file "%1$s%2$sResources%2$sconfig%2$sadmin.yml".%3$s', $this->tempDirectory, DIRECTORY_SEPARATOR, PHP_EOL);
  262. $this->assertSame($expectedOutput, str_replace("\n", PHP_EOL, str_replace(PHP_EOL, "\n", $commandTester->getDisplay())));
  263. $this->assertFileExists($this->tempDirectory.'/Admin/FooAdmin.php');
  264. $this->assertFileExists($this->tempDirectory.'/Controller/FooAdminController.php');
  265. $this->assertFileExists($this->tempDirectory.'/Resources/config/admin.yml');
  266. $adminContent = file_get_contents($this->tempDirectory.'/Admin/FooAdmin.php');
  267. $this->assertContains('class FooAdmin extends Admin', $adminContent);
  268. $this->assertContains('use Sonata\AdminBundle\Admin\Admin;', $adminContent);
  269. $this->assertContains('use Sonata\AdminBundle\Datagrid\DatagridMapper;', $adminContent);
  270. $this->assertContains('use Sonata\AdminBundle\Datagrid\ListMapper;', $adminContent);
  271. $this->assertContains('use Sonata\AdminBundle\Form\FormMapper;', $adminContent);
  272. $this->assertContains('use Sonata\AdminBundle\Show\ShowMapper;', $adminContent);
  273. $this->assertContains('protected function configureDatagridFilters(DatagridMapper $datagridMapper)', $adminContent);
  274. $this->assertContains('protected function configureListFields(ListMapper $listMapper)', $adminContent);
  275. $this->assertContains('protected function configureFormFields(FormMapper $formMapper)', $adminContent);
  276. $this->assertContains('protected function configureShowFields(ShowMapper $showMapper)', $adminContent);
  277. $controllerContent = file_get_contents($this->tempDirectory.'/Controller/FooAdminController.php');
  278. $this->assertContains('class FooAdminController extends CRUDController', $controllerContent);
  279. $this->assertContains('use Sonata\AdminBundle\Controller\CRUDController;', $controllerContent);
  280. $configServiceContent = file_get_contents($this->tempDirectory.'/Resources/config/admin.yml');
  281. $this->assertContains('services:'."\n".' acme_demo_admin.admin.foo', $configServiceContent);
  282. $this->assertContains(' - {name: sonata.admin, manager_type: foo, group: admin, label: Foo}', $configServiceContent);
  283. }
  284. public function getExecuteInteractiveTests()
  285. {
  286. return array(
  287. array('Sonata\AdminBundle\Tests\Fixtures\Bundle\Entity\Foo'),
  288. array('Sonata\AdminBundle\Tests\Fixtures\Entity\Foo'),
  289. );
  290. }
  291. /**
  292. * @dataProvider getValidateManagerTypeTests
  293. */
  294. public function testValidateManagerType($expected, $managerType)
  295. {
  296. $this->command->setContainer($this->container);
  297. $this->container->set('sonata.admin.manager.foo', $this->getMock('Sonata\AdminBundle\Model\ModelManagerInterface'));
  298. $this->container->set('sonata.admin.manager.bar', $this->getMock('Sonata\AdminBundle\Model\ModelManagerInterface'));
  299. $this->assertSame($expected, $this->command->validateManagerType($managerType));
  300. }
  301. public function getValidateManagerTypeTests()
  302. {
  303. return array(
  304. array('foo', 'foo'),
  305. array('bar', 'bar'),
  306. );
  307. }
  308. public function testValidateManagerTypeWithException1()
  309. {
  310. $this->command->setContainer($this->container);
  311. $this->setExpectedException('InvalidArgumentException', 'Invalid manager type "foo". Available manager types are "".');
  312. $this->command->validateManagerType('foo');
  313. }
  314. public function testValidateManagerTypeWithException2()
  315. {
  316. $this->command->setContainer($this->container);
  317. $this->container->set('sonata.admin.manager.foo', $this->getMock('Sonata\AdminBundle\Model\ModelManagerInterface'));
  318. $this->container->set('sonata.admin.manager.bar', $this->getMock('Sonata\AdminBundle\Model\ModelManagerInterface'));
  319. $this->setExpectedException('InvalidArgumentException', 'Invalid manager type "baz". Available manager types are "foo", "bar".');
  320. $this->command->validateManagerType('baz');
  321. }
  322. public function testValidateManagerTypeWithException3()
  323. {
  324. $this->setExpectedException('InvalidArgumentException', 'Invalid manager type "baz". Available manager types are "".');
  325. $this->command->validateManagerType('baz');
  326. }
  327. }