AdminGenerator.php 2.3 KB

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