ServicesManipulator.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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\Manipulator;
  12. use Symfony\Component\HttpKernel\Bundle\BundleInterface;
  13. use Symfony\Component\DependencyInjection\Container;
  14. use Symfony\Component\Yaml\Yaml;
  15. /**
  16. * @author Marek Stipek <mario.dweller@seznam.cz>
  17. * @author Simon Cosandey <simon.cosandey@simseo.ch>
  18. */
  19. class ServicesManipulator
  20. {
  21. /** @var string */
  22. private $file;
  23. /** @var string */
  24. private $template = ' %s:
  25. class: %s
  26. arguments: [~, %s, %s]
  27. tags:
  28. - {name: sonata.admin, manager_type: %s, group: admin, label: %s}
  29. ';
  30. /**
  31. * @param string $file
  32. */
  33. public function __construct($file)
  34. {
  35. $this->file = (string) $file;
  36. }
  37. /**
  38. * @param string $serviceId
  39. * @param string $modelClass
  40. * @param string $adminClass
  41. * @param string $controllerName
  42. * @param string $managerType
  43. * @throws \RuntimeException
  44. */
  45. public function addResource($serviceId, $modelClass, $adminClass, $controllerName, $managerType)
  46. {
  47. $code = "services:\n";
  48. if (is_file($this->file)) {
  49. $code = rtrim(file_get_contents($this->file));
  50. $data = (array) Yaml::parse($code);
  51. if ($code !== '') {
  52. $code .= "\n";
  53. }
  54. if (array_key_exists('services', $data)) {
  55. if (array_key_exists($serviceId, (array) $data['services'])) {
  56. throw new \RuntimeException(sprintf(
  57. 'The service "%s" is already defined in the file "%s".',
  58. $serviceId,
  59. realpath($this->file)
  60. ));
  61. }
  62. if ($data['services'] !== null) {
  63. $code .= "\n";
  64. }
  65. } else {
  66. $code .= $code === '' ? '' : "\n" . "services:\n";
  67. }
  68. }
  69. $code .= sprintf(
  70. $this->template,
  71. $serviceId,
  72. $adminClass,
  73. $modelClass,
  74. $controllerName,
  75. $managerType,
  76. current(array_slice(explode('\\', $modelClass), -1))
  77. );
  78. @mkdir(dirname($this->file), 0777, true);
  79. if (@file_put_contents($this->file, $code) === false) {
  80. throw new \RuntimeException(sprintf(
  81. 'Unable to append service "%s" to the file "%s". You will have to do it manually.',
  82. $serviceId,
  83. $this->file
  84. ));
  85. };
  86. }
  87. }