forked from sonata-project/SonataAdminBundle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ServicesManipulator.php
104 lines (91 loc) · 2.66 KB
/
ServicesManipulator.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
<?php
/*
* This file is part of the Sonata Project package.
*
* (c) Thomas Rabaix <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sonata\AdminBundle\Manipulator;
use Symfony\Component\Yaml\Yaml;
/**
* Class ServicesManipulator.
*
* @author Marek Stipek <[email protected]>
* @author Simon Cosandey <[email protected]>
*/
class ServicesManipulator
{
/**
* @var string
*/
private $file;
/**
* @var string
*/
private $template = ' %s:
class: %s
arguments: [~, %s, %s]
tags:
- { name: sonata.admin, manager_type: %s, group: admin, label: %s }
';
/**
* @param string $file
*/
public function __construct($file)
{
$this->file = (string) $file;
}
/**
* @param string $serviceId
* @param string $modelClass
* @param string $adminClass
* @param string $controllerName
* @param string $managerType
*
* @throws \RuntimeException
*/
public function addResource($serviceId, $modelClass, $adminClass, $controllerName, $managerType)
{
$code = "services:\n";
if (is_file($this->file)) {
$code = rtrim(file_get_contents($this->file));
$data = (array) Yaml::parse($code);
if ($code !== '') {
$code .= "\n";
}
if (array_key_exists('services', $data)) {
if (array_key_exists($serviceId, (array) $data['services'])) {
throw new \RuntimeException(sprintf(
'The service "%s" is already defined in the file "%s".',
$serviceId,
realpath($this->file)
));
}
if ($data['services'] !== null) {
$code .= "\n";
}
} else {
$code .= $code === '' ? '' : "\n"."services:\n";
}
}
$code .= sprintf(
$this->template,
$serviceId,
$adminClass,
$modelClass,
$controllerName,
$managerType,
current(array_slice(explode('\\', $modelClass), -1))
);
@mkdir(dirname($this->file), 0777, true);
if (@file_put_contents($this->file, $code) === false) {
throw new \RuntimeException(sprintf(
'Unable to append service "%s" to the file "%s". You will have to do it manually.',
$serviceId,
$this->file
));
};
}
}