ServicesManipulator.php 2.6 KB

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