-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathInjectedService.php
More file actions
84 lines (68 loc) · 2.6 KB
/
InjectedService.php
File metadata and controls
84 lines (68 loc) · 2.6 KB
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
<?php
namespace DrupalCodeBuilder\Generator;
use DrupalCodeBuilder\Exception\InvalidInputException;
use CaseConverter\StringAssembler;
/**
* Generator for a service injection into a class.
*/
class InjectedService extends BaseGenerator {
use NameFormattingTrait;
/**
* {@inheritdoc}
*/
public static function componentDataDefinition() {
$data_definition = parent::componentDataDefinition();
$data_definition['service_id'] = [
'label' => 'Service name',
'required' => TRUE,
'processing' => function($value, &$component_data, $property_name, &$property_info) {
// Validate the service name.
$task_handler_report_services = \DrupalCodeBuilder\Factory::getTask('ReportServiceData');
$services_data = $task_handler_report_services->listServiceData();
if (!isset($services_data[$value])) {
throw new InvalidInputException("Service {$value} not found.");
}
// Build up the service info.
$service_info = [];
$service_info['id'] = $service_id = $value;
// Copy these explicitly for maintainability and readability.
$service_info['description'] = $services_data[$service_id]['description'];
$service_info['interface'] = $services_data[$service_id]['interface'];
// Derive further information.
$service_id_pieces = preg_split('@[_.]@', $value);
$service_info['variable_name'] = (new StringAssembler($service_id_pieces))->snake();
$service_info['property_name'] = (new StringAssembler($service_id_pieces))->camel();
// If the service has no interface, typehint on the class.
$service_info['typehint'] = $service_info['interface'] ?? $service_info['class'];
// Set the service info.
// Bit of a cheat, as undeclared data property!
$component_data['service_info'] = $service_info;
}
];
return $data_definition;
}
/**
* {@inheritdoc}
*/
protected function buildComponentContents($children_contents) {
$service_info = $this->component_data['service_info'];
return [
'service' => [
'role' => 'service',
'content' => $service_info,
],
'container_extraction' => [
'role' => 'container_extraction',
'content' => "\$container->get('{$service_info['id']}'),",
],
'constructor_param' => [
'role' => 'constructor_param',
'content' => [
'name' => $service_info['variable_name'],
'typehint' => $service_info['typehint'],
'description' => $service_info['description'] . '.',
],
],
];
}
}