AdminGenerator.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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\Generator;
  11. use Sensio\Bundle\GeneratorBundle\Generator\Generator;
  12. use Sonata\AdminBundle\Model\ModelManagerInterface;
  13. use Symfony\Component\HttpKernel\Bundle\BundleInterface;
  14. /**
  15. * Class AdminGenerator.
  16. *
  17. * @author Marek Stipek <mario.dweller@seznam.cz>
  18. * @author Simon Cosandey <simon.cosandey@simseo.ch>
  19. */
  20. class AdminGenerator extends Generator
  21. {
  22. /**
  23. * @var ModelManagerInterface
  24. */
  25. private $modelManager;
  26. /**
  27. * @var string|null
  28. */
  29. private $class;
  30. /**
  31. * @var string|null
  32. */
  33. private $file;
  34. /**
  35. * @param ModelManagerInterface $modelManager
  36. * @param array|string $skeletonDirectories
  37. */
  38. public function __construct(ModelManagerInterface $modelManager, $skeletonDirectories)
  39. {
  40. $this->modelManager = $modelManager;
  41. $this->setSkeletonDirs($skeletonDirectories);
  42. }
  43. /**
  44. * @param BundleInterface $bundle
  45. * @param string $adminClassBasename
  46. * @param string $modelClass
  47. *
  48. * @throws \RuntimeException
  49. */
  50. public function generate(BundleInterface $bundle, $adminClassBasename, $modelClass)
  51. {
  52. $this->class = sprintf('%s\Admin\%s', $bundle->getNamespace(), $adminClassBasename);
  53. $this->file = sprintf('%s/Admin/%s.php', $bundle->getPath(), str_replace('\\', '/', $adminClassBasename));
  54. $parts = explode('\\', $this->class);
  55. if (file_exists($this->file)) {
  56. throw new \RuntimeException(sprintf(
  57. 'Unable to generate the admin class "%s". The file "%s" already exists.',
  58. $this->class,
  59. realpath($this->file)
  60. ));
  61. }
  62. $this->renderFile('Admin.php.twig', $this->file, array(
  63. 'classBasename' => array_pop($parts),
  64. 'namespace' => implode('\\', $parts),
  65. 'fields' => $this->modelManager->getExportFields($modelClass),
  66. ));
  67. }
  68. /**
  69. * @return string|null
  70. */
  71. public function getClass()
  72. {
  73. return $this->class;
  74. }
  75. /**
  76. * @return string|null
  77. */
  78. public function getFile()
  79. {
  80. return $this->file;
  81. }
  82. }