ProxyDumper.php 1.56 KB
Newer Older
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
<?php

/**
 * @file
 * Contains \Drupal\Component\ProxyBuilder\ProxyDumper.
 */

namespace Drupal\Component\ProxyBuilder;

use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\LazyProxy\PhpDumper\DumperInterface;

/**
 * Dumps the proxy service into the dumped PHP container file.
 */
class ProxyDumper implements DumperInterface {

  /**
   * The proxy builder.
   *
   * @var \Drupal\Component\ProxyBuilder\ProxyBuilder
   */
  protected $builder;

  public function __construct(ProxyBuilder $builder) {
    $this->builder = $builder;
  }

  /**
   * {@inheritdoc}
   */
  public function isProxyCandidate(Definition $definition) {
    return $definition->isLazy() && ($class = $definition->getClass()) && class_exists($class);
  }

  /**
   * {@inheritdoc}
   */
  public function getProxyFactoryCode(Definition $definition, $id) {
    // Note: the specific get method is called initially with $lazyLoad=TRUE;
    // When you want to retrieve the actual service, the code generated in
    // ProxyBuilder calls the method with lazy loading disabled.
    $output = <<<'EOS'
        if ($lazyLoad) {
            return $this->services['{{ id }}'] = new {{ class_name }}($this, '{{ id }}');
        }

EOS;
    $output = str_replace('{{ id }}', $id, $output);
    $output = str_replace('{{ class_name }}', $this->builder->buildProxyClassName($definition->getClass()), $output);

    return $output;
  }

  /**
   * {@inheritdoc}
   */
  public function getProxyCode(Definition $definition) {
    return $this->builder->build($definition->getClass());
  }

}