ServicesManipulator.php 2.7 KB

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