Skip to content

[ProxyManagerBridge][DI] allow proxifying interfaces with "lazy: Some\ProxifiedInterface" #27697

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 9, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .php_cs.dist
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ return PhpCsFixer\Config::create()
->in(__DIR__.'/src')
->append(array(__FILE__))
->exclude(array(
'Symfony/Bridge/ProxyManager/Tests/LazyProxy/PhpDumper/Fixtures',
// directories containing files with content that is autogenerated by `var_export`, which breaks CS in output code
'Symfony/Component/Cache/Tests/Marshaller/Fixtures',
'Symfony/Component/DependencyInjection/Tests/Fixtures',
Expand Down
5 changes: 5 additions & 0 deletions src/Symfony/Bridge/ProxyManager/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
CHANGELOG
=========

4.2.0
-----

* allowed creating lazy-proxies from interfaces

3.3.0
-----

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,14 @@
/**
* @internal
*/
class LazyLoadingValueHolderFactoryV2 extends BaseFactory
class LazyLoadingValueHolderFactory extends BaseFactory
{
private $generator;

/**
* {@inheritdoc}
*/
protected function getGenerator(): ProxyGeneratorInterface
public function getGenerator(): ProxyGeneratorInterface
{
return $this->generator ?: $this->generator = new LazyLoadingValueHolderGenerator();
}
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
namespace Symfony\Bridge\ProxyManager\LazyProxy\Instantiator;

use ProxyManager\Configuration;
use ProxyManager\Factory\LazyLoadingValueHolderFactory;
use ProxyManager\GeneratorStrategy\EvaluatingGeneratorStrategy;
use ProxyManager\Proxy\LazyLoadingInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
Expand All @@ -26,21 +25,14 @@
*/
class RuntimeInstantiator implements InstantiatorInterface
{
/**
* @var LazyLoadingValueHolderFactory
*/
private $factory;

public function __construct()
{
$config = new Configuration();
$config->setGeneratorStrategy(new EvaluatingGeneratorStrategy());

if (method_exists('ProxyManager\Version', 'getVersion')) {
$this->factory = new LazyLoadingValueHolderFactoryV2($config);
} else {
$this->factory = new LazyLoadingValueHolderFactoryV1($config);
}
$this->factory = new LazyLoadingValueHolderFactory($config);
}

/**
Expand All @@ -49,9 +41,9 @@ public function __construct()
public function instantiateProxy(ContainerInterface $container, Definition $definition, $id, $realInstantiator)
{
return $this->factory->createProxy(
$definition->getClass(),
$this->factory->getGenerator()->getProxifiedClass($definition),
function (&$wrappedInstance, LazyLoadingInterface $proxy) use ($realInstantiator) {
$wrappedInstance = call_user_func($realInstantiator);
$wrappedInstance = \call_user_func($realInstantiator);

$proxy->setProxyInitializer(null);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,20 +12,74 @@
namespace Symfony\Bridge\ProxyManager\LazyProxy\PhpDumper;

use ProxyManager\ProxyGenerator\LazyLoadingValueHolderGenerator as BaseGenerator;
use Symfony\Component\DependencyInjection\Definition;
use Zend\Code\Generator\ClassGenerator;

/**
* @internal
*/
class LazyLoadingValueHolderGenerator extends BaseGenerator
{
private $fluentSafe = false;

public function setFluentSafe(bool $fluentSafe)
{
$this->fluentSafe = $fluentSafe;
}

/**
* {@inheritdoc}
*/
public function generate(\ReflectionClass $originalClass, ClassGenerator $classGenerator)
{
parent::generate($originalClass, $classGenerator);

foreach ($classGenerator->getMethods() as $method) {
$body = preg_replace(
'/(\$this->initializer[0-9a-f]++) && \1->__invoke\(\$this->(valueHolder[0-9a-f]++), (.*?), \1\);/',
'$1 && ($1->__invoke(\$$2, $3, $1) || 1) && $this->$2 = \$$2;',
$method->getBody()
);
$body = str_replace('(new \ReflectionClass(get_class()))', '$reflection', $body);

if ($originalClass->isInterface()) {
$body = str_replace('get_parent_class($this)', var_export($originalClass->name, true), $body);
$body = preg_replace_callback('/\n\n\$realInstanceReflection = [^{]++\{([^}]++)\}\n\n.*/s', function ($m) {
$r = '';
foreach (explode("\n", $m[1]) as $line) {
$r .= "\n".substr($line, 4);
if (0 === strpos($line, ' return ')) {
break;
}
}

return $r;
}, $body);
}

if ($this->fluentSafe) {
$indent = $method->getIndentation();
$method->setIndentation('');
$code = $method->generate();
if (null !== $docBlock = $method->getDocBlock()) {
$code = substr($code, \strlen($docBlock->generate()));
}
$refAmp = (strpos($code, '&') ?: \PHP_INT_MAX) <= strpos($code, '(') ? '&' : '';
$body = preg_replace(
'/\nreturn (\$this->valueHolder[0-9a-f]++)(->[^;]++);$/',
"\nif ($1 === \$returnValue = {$refAmp}$1$2) {\n \$returnValue = \$this;\n}\n\nreturn \$returnValue;",
$body
);
$method->setIndentation($indent);
}

if (0 === strpos($originalClass->getFilename(), __FILE__)) {
$body = str_replace(var_export($originalClass->name, true), '__CLASS__', $body);
}

$method->setBody($body);
}

if ($classGenerator->hasMethod('__destruct')) {
$destructor = $classGenerator->getMethod('__destruct');
$body = $destructor->getBody();
Expand All @@ -37,5 +91,53 @@ public function generate(\ReflectionClass $originalClass, ClassGenerator $classG

$destructor->setBody($newBody);
}

if (0 === strpos($originalClass->getFilename(), __FILE__)) {
$interfaces = $classGenerator->getImplementedInterfaces();
array_pop($interfaces);
$classGenerator->setImplementedInterfaces(array_merge($interfaces, $originalClass->getInterfaceNames()));
}
}

public function getProxifiedClass(Definition $definition): ?string
{
if (!$definition->hasTag('proxy')) {
return \class_exists($class = $definition->getClass()) || \interface_exists($class) ? $class : null;
}
if (!$definition->isLazy()) {
throw new \InvalidArgumentException(sprintf('Invalid definition for service of class "%s": setting the "proxy" tag on a service requires it to be "lazy".', $definition->getClass()));
}
$tags = $definition->getTag('proxy');
if (!isset($tags[0]['interface'])) {
throw new \InvalidArgumentException(sprintf('Invalid definition for service of class "%s": the "interface" attribute is missing on the "proxy" tag.', $definition->getClass()));
}
if (1 === \count($tags)) {
return \class_exists($tags[0]['interface']) || \interface_exists($tags[0]['interface']) ? $tags[0]['interface'] : null;
}

$proxyInterface = 'LazyProxy';
$interfaces = '';
foreach ($tags as $tag) {
if (!isset($tag['interface'])) {
throw new \InvalidArgumentException(sprintf('Invalid definition for service of class "%s": the "interface" attribute is missing on a "proxy" tag.', $definition->getClass()));
}
if (!\interface_exists($tag['interface'])) {
throw new \InvalidArgumentException(sprintf('Invalid definition for service of class "%s": several "proxy" tags found but "%s" is not an interface.', $definition->getClass(), $tag['interface']));
}

$proxyInterface .= '\\'.$tag['interface'];
$interfaces .= ', \\'.$tag['interface'];
}

if (!\interface_exists($proxyInterface)) {
$i = strrpos($proxyInterface, '\\');
$namespace = substr($proxyInterface, 0, $i);
$interface = substr($proxyInterface, 1 + $i);
$interfaces = substr($interfaces, 2);

eval("namespace {$namespace}; interface {$interface} extends {$interfaces} {}");
}

return $proxyInterface;
}
}
27 changes: 11 additions & 16 deletions src/Symfony/Bridge/ProxyManager/LazyProxy/PhpDumper/ProxyDumper.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
use ProxyManager\Generator\ClassGenerator;
use ProxyManager\GeneratorStrategy\BaseGeneratorStrategy;
use ProxyManager\Version;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\LazyProxy\PhpDumper\DumperInterface;

Expand Down Expand Up @@ -43,7 +42,7 @@ public function __construct(string $salt = '')
*/
public function isProxyCandidate(Definition $definition)
{
return $definition->isLazy() && ($class = $definition->getClass()) && class_exists($class);
return ($definition->isLazy() || $definition->hasTag('proxy')) && $this->proxyGenerator->getProxifiedClass($definition);
}

/**
Expand All @@ -63,14 +62,10 @@ public function getProxyFactoryCode(Definition $definition, $id, $factoryCode =

$proxyClass = $this->getProxyClassName($definition);

$hasStaticConstructor = $this->generateProxyClass($definition)->hasMethod('staticProxyConstructor');

$constructorCall = sprintf($hasStaticConstructor ? '%s::staticProxyConstructor' : 'new %s', '\\'.$proxyClass);

return <<<EOF
if (\$lazyLoad) {
$instantiation \$this->createProxy('$proxyClass', function () {
return $constructorCall(function (&\$wrappedInstance, \ProxyManager\Proxy\LazyLoadingInterface \$proxy) {
return \\$proxyClass::staticProxyConstructor(function (&\$wrappedInstance, \ProxyManager\Proxy\LazyLoadingInterface \$proxy) {
\$wrappedInstance = $factoryCode;

\$proxy->setProxyInitializer(null);
Expand All @@ -91,12 +86,6 @@ public function getProxyCode(Definition $definition)
{
$code = $this->classGenerator->generate($this->generateProxyClass($definition));

$code = preg_replace(
'/(\$this->initializer[0-9a-f]++) && \1->__invoke\(\$this->(valueHolder[0-9a-f]++), (.*?), \1\);/',
'$1 && ($1->__invoke(\$$2, $3, $1) || 1) && $this->$2 = \$$2;',
$code
);

if (version_compare(self::getProxyManagerVersion(), '2.2', '<')) {
$code = preg_replace(
'/((?:\$(?:this|initializer|instance)->)?(?:publicProperties|initializer|valueHolder))[0-9a-f]++/',
Expand All @@ -122,20 +111,26 @@ private static function getProxyManagerVersion(): string
*/
private function getProxyClassName(Definition $definition): string
{
return preg_replace('/^.*\\\\/', '', $definition->getClass()).'_'.$this->getIdentifierSuffix($definition);
$class = $this->proxyGenerator->getProxifiedClass($definition);

return preg_replace('/^.*\\\\/', '', $class).'_'.$this->getIdentifierSuffix($definition);
}

private function generateProxyClass(Definition $definition): ClassGenerator
{
$generatedClass = new ClassGenerator($this->getProxyClassName($definition));
$class = $this->proxyGenerator->getProxifiedClass($definition);

$this->proxyGenerator->generate(new \ReflectionClass($definition->getClass()), $generatedClass);
$this->proxyGenerator->setFluentSafe($definition->hasTag('proxy'));
$this->proxyGenerator->generate(new \ReflectionClass($class), $generatedClass);

return $generatedClass;
}

private function getIdentifierSuffix(Definition $definition): string
{
return substr(hash('sha256', $definition->getClass().$this->salt), -7);
$class = $this->proxyGenerator->getProxifiedClass($definition);

return substr(hash('sha256', $class.$this->salt), -7);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

return new class
{
public $proxyClass;
private $privates = array();

public function getFooService($lazyLoad = true)
{
if ($lazyLoad) {
return $this->privates['foo'] = $this->createProxy('SunnyInterface_1eff735', function () {
return \SunnyInterface_1eff735::staticProxyConstructor(function (&$wrappedInstance, \ProxyManager\Proxy\LazyLoadingInterface $proxy) {
$wrappedInstance = $this->getFooService(false);

$proxy->setProxyInitializer(null);

return true;
});
});
}

return new Symfony\Bridge\ProxyManager\Tests\LazyProxy\PhpDumper\DummyClass();
}

protected function createProxy($class, \Closure $factory)
{
$this->proxyClass = $class;

return $factory();
}
};
Loading