AdminGenerator.php 2.4 KB

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