AdminGenerator.php 2.4 KB

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