ServicesManipulator.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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\Yaml\Yaml;
  13. /**
  14. * @author Marek Stipek <mario.dweller@seznam.cz>
  15. * @author Simon Cosandey <simon.cosandey@simseo.ch>
  16. */
  17. class ServicesManipulator
  18. {
  19. /** @var string */
  20. private $file;
  21. /** @var string */
  22. private $template = ' %s:
  23. class: %s
  24. arguments: [~, %s, %s]
  25. tags:
  26. - {name: sonata.admin, manager_type: %s, group: admin, label: %s}
  27. ';
  28. /**
  29. * @param string $file
  30. */
  31. public function __construct($file)
  32. {
  33. $this->file = (string) $file;
  34. }
  35. /**
  36. * @param string $serviceId
  37. * @param string $modelClass
  38. * @param string $adminClass
  39. * @param string $controllerName
  40. * @param string $managerType
  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. }