AdminGenerator.php 2.4 KB

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