ServicesManipulator.php 2.6 KB

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