ServicesManipulator.php 2.6 KB

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