AdminGenerator.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. /** @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. *
  42. * @throws \RuntimeException
  43. */
  44. public function generate(BundleInterface $bundle, $adminClassBasename, $modelClass)
  45. {
  46. $this->class = sprintf('%s\Admin\%s', $bundle->getNamespace(), $adminClassBasename);
  47. $this->file = sprintf('%s/Admin/%s.php', $bundle->getPath(), str_replace('\\', '/', $adminClassBasename));
  48. $parts = explode('\\', $this->class);
  49. if (file_exists($this->file)) {
  50. throw new \RuntimeException(sprintf(
  51. 'Unable to generate the admin class "%s". The file "%s" already exists.',
  52. $this->class,
  53. realpath($this->file)
  54. ));
  55. }
  56. $this->renderFile('Admin.php.twig', $this->file, array(
  57. 'classBasename' => array_pop($parts),
  58. 'namespace' => implode('\\', $parts),
  59. 'fields' => $this->modelManager->getExportFields($modelClass),
  60. ));
  61. }
  62. /**
  63. * @return string|null
  64. */
  65. public function getClass()
  66. {
  67. return $this->class;
  68. }
  69. /**
  70. * @return string|null
  71. */
  72. public function getFile()
  73. {
  74. return $this->file;
  75. }
  76. }