ProxyBuilder.php 9.19 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?php

namespace Drupal\Component\ProxyBuilder;

/**
 * Generates the string representation of the proxy service.
 */
class ProxyBuilder {

  /**
   * Generates the used proxy class name from a given class name.
   *
   * @param string $class_name
   *   The class name of the actual service.
   *
   * @return string
   *   The class name of the proxy.
   */
  public static function buildProxyClassName($class_name) {
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
    $match = [];
    preg_match('/([a-zA-Z0-9_]+\\\\[a-zA-Z0-9_]+)\\\\(.+)/', $class_name, $match);
    $root_namespace = $match[1];
    $rest_fqcn = $match[2];
    $proxy_class_name = $root_namespace . '\\ProxyClass\\' . $rest_fqcn;

    return $proxy_class_name;
  }

  /**
   * Generates the used proxy namespace from a given class name.
   *
   * @param string $class_name
   *   The class name of the actual service.
   *
   * @return string
   *   The namespace name of the proxy.
   */
  public static function buildProxyNamespace($class_name) {
    $proxy_classname = static::buildProxyClassName($class_name);

    preg_match('/(.+)\\\\[a-zA-Z0-9]+/', $proxy_classname, $match);
    $proxy_namespace = $match[1];
    return $proxy_namespace;
44
45
46
47
48
49
50
  }

  /**
   * Builds a proxy class string.
   *
   * @param string $class_name
   *   The class name of the actual service.
51
52
   * @param string $proxy_class_name
   *   (optional) The class name of the proxy service.
53
54
55
56
   *
   * @return string
   *   The full string with namespace class and methods.
   */
57
  public function build($class_name, $proxy_class_name = '') {
58
59
    $reflection = new \ReflectionClass($class_name);

60
61
62
63
64
65
66
67
68
69
    if ($proxy_class_name) {
      $proxy_class_reflection = new \ReflectionClass($proxy_class_name);
      $proxy_namespace = $proxy_class_reflection->getNamespaceName();
    }
    else {
      $proxy_class_name = $this->buildProxyClassName($class_name);
      $proxy_namespace = $this->buildProxyNamespace($class_name);
      $proxy_class_shortname = str_replace($proxy_namespace . '\\', '', $proxy_class_name);
    }

70
71
    $output = '';
    $class_documentation = <<<'EOS'
72
73
74
75
76
77
78
79

namespace {{ namespace }}{

    /**
     * Provides a proxy class for \{{ class_name }}.
     *
     * @see \Drupal\Component\ProxyBuilder
     */
80
81

EOS;
82
    $class_start = '    class {{ proxy_class_shortname }}';
83

84
85
86
87
88
89
90
91
92
93
94
95
96
97
    // For cases in which the implemented interface is a child of another
    // interface, getInterfaceNames() also returns the parent. This causes a
    // PHP error.
    // In order to avoid that, check for each interface, whether one of its
    // parents is also in the list and exclude it.
    if ($interfaces = $reflection->getInterfaces()) {
      foreach ($interfaces as $interface_name => $interface) {
        // Exclude all parents from the list of implemented interfaces of the
        // class.
        if ($parent_interfaces = $interface->getInterfaceNames()) {
          foreach ($parent_interfaces as $parent_interface) {
            unset($interfaces[$parent_interface]);
          }
        }
98
      }
99
100
101
102
103
104

      $interface_names = [];
      foreach ($interfaces as $interface) {
        $interface_names[] = '\\' . $interface->getName();
      }
      $class_start .= ' implements ' . implode(', ', $interface_names);
105
106
107
108
109
110
111
    }

    $output .= $this->buildUseStatements();

    // The actual class;
    $properties = <<<'EOS'
/**
112
113
 * The id of the original proxied service.
 *
114
115
 * @var string
 */
116
protected $drupalProxyOriginalServiceId;
117
118

/**
119
120
 * The real proxied service, after it was lazy loaded.
 *
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
 * @var \{{ class_name }}
 */
protected $service;

/**
 * The service container.
 *
 * @var \Symfony\Component\DependencyInjection\ContainerInterface
 */
protected $container;


EOS;

    $output .= $properties;

    // Add all the methods.
    $methods = [];
    $methods[] = $this->buildConstructorMethod();
    $methods[] = $this->buildLazyLoadItselfMethod();

    // Add all the methods of the proxied service.
    $reflection_methods = $reflection->getMethods();

    foreach ($reflection_methods as $method) {
      if ($method->getName() === '__construct') {
        continue;
      }

      if ($method->isPublic()) {
        $methods[] = $this->buildMethod($method) . "\n";
      }
    }

    $output .= implode("\n", $methods);

    // Indent the output.
158
    $output = implode("\n", array_map(function ($value) {
159
160
161
      if ($value === '') {
        return $value;
      }
162
      return "        $value";
163
164
    }, explode("\n", $output)));

165
    $final_output = $class_documentation . $class_start . "\n    {\n\n" . $output . "\n    }\n\n}\n";
166
167

    $final_output = str_replace('{{ class_name }}', $class_name, $final_output);
168
169
    $final_output = str_replace('{{ namespace }}', $proxy_namespace ? $proxy_namespace . ' ' : '', $final_output);
    $final_output = str_replace('{{ proxy_class_shortname }}', $proxy_class_shortname, $final_output);
170
171
172
173
174
175
176
177
178
179
180

    return $final_output;
  }

  /**
   * Generates the string for the method which loads the actual service.
   *
   * @return string
   */
  protected function buildLazyLoadItselfMethod() {
    $output = <<<'EOS'
181
182
183
184
185
186
/**
 * Lazy loads the real service from the container.
 *
 * @return object
 *   Returns the constructed real service.
 */
187
188
189
protected function lazyLoadItself()
{
    if (!isset($this->service)) {
190
        $this->service = $this->container->get($this->drupalProxyOriginalServiceId);
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
    }

    return $this->service;
}

EOS;

    return $output;
  }

  /**
   * Generates the string representation of a single method: signature, body.
   *
   * @param \ReflectionMethod $reflection_method
   *   A reflection method for the method.
   *
   * @return string
   */
  protected function buildMethod(\ReflectionMethod $reflection_method) {

    $parameters = [];
    foreach ($reflection_method->getParameters() as $parameter) {
      $parameters[] = $this->buildParameter($parameter);
    }

    $function_name = $reflection_method->getName();

    $reference = '';
    if ($reflection_method->returnsReference()) {
      $reference = '&';
    }
222
223
224
225
226
227
228
229

    $signature_line = <<<'EOS'
/**
 * {@inheritdoc}
 */

EOS;

230
    if ($reflection_method->isStatic()) {
231
      $signature_line .= 'public static function ' . $reference . $function_name . '(';
232
233
    }
    else {
234
      $signature_line .= 'public function ' . $reference . $function_name . '(';
235
236
237
238
    }

    $signature_line .= implode(', ', $parameters);
    $signature_line .= ')';
239
240
241
    if ($reflection_method->hasReturnType()) {
      $signature_line .= ': ' . $reflection_method->getReturnType()->getName();
    }
242
243
244
245
246

    $output = $signature_line . "\n{\n";

    $output .= $this->buildMethodBody($reflection_method);

247
    $output .= "\n" . '}';
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
    return $output;
  }

  /**
   * Builds a string for a single parameter of a method.
   *
   * @param \ReflectionParameter $parameter
   *   A reflection object of the parameter.
   *
   * @return string
   */
  protected function buildParameter(\ReflectionParameter $parameter) {
    $parameter_string = '';

    if ($parameter->isArray()) {
      $parameter_string .= 'array ';
    }
    elseif ($parameter->isCallable()) {
      $parameter_string .= 'callable ';
    }
    elseif ($class = $parameter->getClass()) {
      $parameter_string .= '\\' . $class->getName() . ' ';
    }
271
272
273
    elseif ($parameter->hasType()) {
      $parameter_string .= $parameter->getType()->getName() . ' ';
    }
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327

    if ($parameter->isPassedByReference()) {
      $parameter_string .= '&';
    }

    $parameter_string .= '$' . $parameter->getName();

    if ($parameter->isDefaultValueAvailable()) {
      $parameter_string .= ' = ';
      $parameter_string .= var_export($parameter->getDefaultValue(), TRUE);
    }

    return $parameter_string;
  }

  /**
   * Builds the body of a wrapped method.
   *
   * @param \ReflectionMethod $reflection_method
   *   A reflection method for the method.
   *
   * @return string
   */
  protected function buildMethodBody(\ReflectionMethod $reflection_method) {
    $output = '';

    $function_name = $reflection_method->getName();

    if (!$reflection_method->isStatic()) {
      $output .= '    return $this->lazyLoadItself()->' . $function_name . '(';
    }
    else {
      $class_name = $reflection_method->getDeclaringClass()->getName();
      $output .= "    \\$class_name::$function_name(";
    }

    // Add parameters;
    $parameters = [];
    foreach ($reflection_method->getParameters() as $parameter) {
      $parameters[] = '$' . $parameter->getName();
    }

    $output .= implode(', ', $parameters) . ');';

    return $output;
  }

  /**
   * Builds the constructor used to inject the actual service ID.
   *
   * @return string
   */
  protected function buildConstructorMethod() {
    $output = <<<'EOS'
328
329
330
331
332
333
334
335
336
/**
 * Constructs a ProxyClass Drupal proxy object.
 *
 * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
 *   The container.
 * @param string $drupal_proxy_original_service_id
 *   The service ID of the original service.
 */
public function __construct(\Symfony\Component\DependencyInjection\ContainerInterface $container, $drupal_proxy_original_service_id)
337
338
{
    $this->container = $container;
339
    $this->drupalProxyOriginalServiceId = $drupal_proxy_original_service_id;
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
}

EOS;

    return $output;
  }

  /**
   * Build the required use statements of the proxy class.
   *
   * @return string
   */
  protected function buildUseStatements() {
    $output = '';

    return $output;
  }

}