GenerateAdminCommandTest.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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 AbstractAdmin', $adminContent);
  123. $this->assertContains('use Sonata\AdminBundle\Admin\AbstractAdmin;', $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. case 'Do you want to update the services YAML configuration file':
  176. return 'yes';
  177. }
  178. return $default;
  179. }));
  180. $dialog->expects($this->any())
  181. ->method('askAndValidate')
  182. ->will($this->returnCallback(function (OutputInterface $output, $question, $validator, $attempts = false, $default = null) use ($modelEntity) {
  183. $questionClean = substr($question, 6, strpos($question, '</info>') - 6);
  184. switch ($questionClean) {
  185. case 'The fully qualified model class':
  186. return $modelEntity;
  187. case 'The bundle name':
  188. return 'AcmeDemoBundle';
  189. case 'The admin class basename':
  190. return 'FooAdmin';
  191. case 'The controller class basename':
  192. return 'FooAdminController';
  193. case 'The services YAML configuration file':
  194. return 'admin.yml';
  195. case 'The admin service ID':
  196. return 'acme_demo_admin.admin.foo';
  197. case 'The manager type':
  198. return 'foo';
  199. }
  200. return $default;
  201. }));
  202. $command->getHelperSet()->set($dialog, 'dialog');
  203. } else {
  204. $questionHelper = $this->getMock('Sensio\Bundle\GeneratorBundle\Command\Helper\QuestionHelper', array('ask'));
  205. $questionHelper->expects($this->any())
  206. ->method('ask')
  207. ->will($this->returnCallback(function (InputInterface $input, OutputInterface $output, Question $question) use ($modelEntity) {
  208. $questionClean = substr($question->getQuestion(), 6, strpos($question->getQuestion(), '</info>') - 6);
  209. switch ($questionClean) {
  210. // confirmations
  211. case 'Do you want to generate a controller':
  212. return 'yes';
  213. case 'Do you want to update the services YAML configuration file':
  214. return 'yes';
  215. // inputs
  216. case 'The fully qualified model class':
  217. return $modelEntity;
  218. case 'The bundle name':
  219. return 'AcmeDemoBundle';
  220. case 'The admin class basename':
  221. return 'FooAdmin';
  222. case 'The controller class basename':
  223. return 'FooAdminController';
  224. case 'The services YAML configuration file':
  225. return 'admin.yml';
  226. case 'The admin service ID':
  227. return 'acme_demo_admin.admin.foo';
  228. case 'The manager type':
  229. return 'foo';
  230. }
  231. return false;
  232. }));
  233. $command->getHelperSet()->set($questionHelper, 'question');
  234. }
  235. $commandTester = new CommandTester($command);
  236. $commandTester->execute(array(
  237. 'command' => $command->getName(),
  238. 'model' => $modelEntity,
  239. ));
  240. $expectedOutput = PHP_EOL.str_pad('', 41, ' ').PHP_EOL.' Welcome to the Sonata admin generator '.PHP_EOL.str_pad('', 41, ' ').PHP_EOL.PHP_EOL;
  241. $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);
  242. $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);
  243. $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);
  244. $this->assertSame($expectedOutput, str_replace("\n", PHP_EOL, str_replace(PHP_EOL, "\n", $commandTester->getDisplay())));
  245. $this->assertFileExists($this->tempDirectory.'/Admin/FooAdmin.php');
  246. $this->assertFileExists($this->tempDirectory.'/Controller/FooAdminController.php');
  247. $this->assertFileExists($this->tempDirectory.'/Resources/config/admin.yml');
  248. $adminContent = file_get_contents($this->tempDirectory.'/Admin/FooAdmin.php');
  249. $this->assertContains('class FooAdmin extends AbstractAdmin', $adminContent);
  250. $this->assertContains('use Sonata\AdminBundle\Admin\AbstractAdmin;', $adminContent);
  251. $this->assertContains('use Sonata\AdminBundle\Datagrid\DatagridMapper;', $adminContent);
  252. $this->assertContains('use Sonata\AdminBundle\Datagrid\ListMapper;', $adminContent);
  253. $this->assertContains('use Sonata\AdminBundle\Form\FormMapper;', $adminContent);
  254. $this->assertContains('use Sonata\AdminBundle\Show\ShowMapper;', $adminContent);
  255. $this->assertContains('protected function configureDatagridFilters(DatagridMapper $datagridMapper)', $adminContent);
  256. $this->assertContains('protected function configureListFields(ListMapper $listMapper)', $adminContent);
  257. $this->assertContains('protected function configureFormFields(FormMapper $formMapper)', $adminContent);
  258. $this->assertContains('protected function configureShowFields(ShowMapper $showMapper)', $adminContent);
  259. $controllerContent = file_get_contents($this->tempDirectory.'/Controller/FooAdminController.php');
  260. $this->assertContains('class FooAdminController extends CRUDController', $controllerContent);
  261. $this->assertContains('use Sonata\AdminBundle\Controller\CRUDController;', $controllerContent);
  262. $configServiceContent = file_get_contents($this->tempDirectory.'/Resources/config/admin.yml');
  263. $this->assertContains('services:'."\n".' acme_demo_admin.admin.foo', $configServiceContent);
  264. $this->assertContains(' - { name: sonata.admin, manager_type: foo, group: admin, label: Foo }', $configServiceContent);
  265. }
  266. public function getExecuteInteractiveTests()
  267. {
  268. return array(
  269. array('Sonata\AdminBundle\Tests\Fixtures\Bundle\Entity\Foo'),
  270. array('Sonata\AdminBundle\Tests\Fixtures\Entity\Foo'),
  271. );
  272. }
  273. /**
  274. * @dataProvider getValidateManagerTypeTests
  275. */
  276. public function testValidateManagerType($expected, $managerType)
  277. {
  278. $this->command->setContainer($this->container);
  279. $this->container->set('sonata.admin.manager.foo', $this->getMock('Sonata\AdminBundle\Model\ModelManagerInterface'));
  280. $this->container->set('sonata.admin.manager.bar', $this->getMock('Sonata\AdminBundle\Model\ModelManagerInterface'));
  281. $this->assertSame($expected, $this->command->validateManagerType($managerType));
  282. }
  283. public function getValidateManagerTypeTests()
  284. {
  285. return array(
  286. array('foo', 'foo'),
  287. array('bar', 'bar'),
  288. );
  289. }
  290. public function testValidateManagerTypeWithException1()
  291. {
  292. $this->command->setContainer($this->container);
  293. $this->setExpectedException('InvalidArgumentException', 'Invalid manager type "foo". Available manager types are "".');
  294. $this->command->validateManagerType('foo');
  295. }
  296. public function testValidateManagerTypeWithException2()
  297. {
  298. $this->command->setContainer($this->container);
  299. $this->container->set('sonata.admin.manager.foo', $this->getMock('Sonata\AdminBundle\Model\ModelManagerInterface'));
  300. $this->container->set('sonata.admin.manager.bar', $this->getMock('Sonata\AdminBundle\Model\ModelManagerInterface'));
  301. $this->setExpectedException('InvalidArgumentException', 'Invalid manager type "baz". Available manager types are "foo", "bar".');
  302. $this->command->validateManagerType('baz');
  303. }
  304. public function testValidateManagerTypeWithException3()
  305. {
  306. $this->setExpectedException('InvalidArgumentException', 'Invalid manager type "baz". Available manager types are "".');
  307. $this->command->validateManagerType('baz');
  308. }
  309. }