Skip to content
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

Add "skipDestructor" option to lazy loading proxies #641

Closed
wants to merge 1 commit into from
Closed
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
12 changes: 8 additions & 4 deletions src/ProxyManager/Factory/AbstractBaseFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
use function assert;
use function class_exists;
use function is_a;
use function serialize;
use function sha1;

/**
* Base factory common logic
Expand All @@ -29,7 +31,7 @@ abstract class AbstractBaseFactory
* Cached checked class names
*
* @var array<string, string>
* @psalm-var array<class-string, class-string>
* @psalm-var array<string, class-string>
*/
private array $checkedClasses = [];

Expand All @@ -54,8 +56,10 @@ public function __construct(?Configuration $configuration = null)
*/
protected function generateProxy(string $className, array $proxyOptions = []): string
{
if (array_key_exists($className, $this->checkedClasses)) {
$generatedClassName = $this->checkedClasses[$className];
$cacheKey = $proxyOptions ? sha1(serialize([$className, $proxyOptions])) : $className;

if (array_key_exists($cacheKey, $this->checkedClasses)) {
$generatedClassName = $this->checkedClasses[$cacheKey];

assert(is_a($generatedClassName, $className, true));

Expand Down Expand Up @@ -87,7 +91,7 @@ protected function generateProxy(string $className, array $proxyOptions = []): s
->getSignatureChecker()
->checkSignature(new ReflectionClass($proxyClassName), $proxyParameters);

return $this->checkedClasses[$className] = $proxyClassName;
return $this->checkedClasses[$cacheKey] = $proxyClassName;
}

abstract protected function getGenerator(): ProxyGeneratorInterface;
Expand Down
1 change: 1 addition & 0 deletions src/ProxyManager/Factory/LazyLoadingValueHolderFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ public function __construct(?Configuration $configuration = null)
* array<string, mixed>=,
* ?Closure=
* ) : bool $initializer
* @psalm-param array{skipDestructor?: bool} $proxyOptions
*
* @psalm-return RealObjectType&ValueHolderInterface<RealObjectType>&VirtualProxyInterface
*
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

declare(strict_types=1);

namespace ProxyManager\ProxyGenerator\LazyLoadingGhost\MethodGenerator;

use Laminas\Code\Generator\Exception\InvalidArgumentException;
use Laminas\Code\Generator\PropertyGenerator;
use ProxyManager\Generator\MethodGenerator;

/**
* Destructor that skips the original destructor when the proxy is not initialized.
*/
class SkipDestructor extends MethodGenerator
{
/**
* Constructor
*
* @throws InvalidArgumentException
*/
public function __construct(PropertyGenerator $initializerProperty)
{
parent::__construct('__destruct');

$this->setBody(
'$this->' . $initializerProperty->getName() . ' || parent::__destruct();'
);
}
}
27 changes: 22 additions & 5 deletions src/ProxyManager/ProxyGenerator/LazyLoadingGhostGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
use ProxyManager\ProxyGenerator\LazyLoadingGhost\MethodGenerator\MagicSleep;
use ProxyManager\ProxyGenerator\LazyLoadingGhost\MethodGenerator\MagicUnset;
use ProxyManager\ProxyGenerator\LazyLoadingGhost\MethodGenerator\SetProxyInitializer;
use ProxyManager\ProxyGenerator\LazyLoadingGhost\MethodGenerator\SkipDestructor;
use ProxyManager\ProxyGenerator\LazyLoadingGhost\PropertyGenerator\InitializationTracker;
use ProxyManager\ProxyGenerator\LazyLoadingGhost\PropertyGenerator\InitializerProperty;
use ProxyManager\ProxyGenerator\LazyLoadingGhost\PropertyGenerator\PrivatePropertiesMap;
Expand All @@ -48,7 +49,7 @@ class LazyLoadingGhostGenerator implements ProxyGeneratorInterface
/**
* {@inheritDoc}
*
* @psalm-param array{skippedProperties?: array<int, string>} $proxyOptions
* @psalm-param array{skippedProperties?: array<int, string>, skipDestructor?: bool} $proxyOptions
*
* @return void
*
Expand All @@ -65,6 +66,7 @@ public function generate(ReflectionClass $originalClass, ClassGenerator $classGe
$publicProperties = new PublicPropertiesMap($filteredProperties);
$privateProperties = new PrivatePropertiesMap($filteredProperties);
$protectedProperties = new ProtectedPropertiesMap($filteredProperties);
$skipDestructor = ($proxyOptions['skipDestructor'] ?? false) && $originalClass->hasMethod('__destruct');

$classGenerator->setExtendedClass($originalClass->getName());
$classGenerator->setImplementedInterfaces([GhostObjectInterface::class]);
Expand All @@ -81,7 +83,7 @@ static function (MethodGenerator $generatedMethod) use ($originalClass, $classGe
ClassGeneratorUtils::addMethodIfNotFinal($originalClass, $classGenerator, $generatedMethod);
},
array_merge(
$this->getAbstractProxiedMethods($originalClass),
$this->getAbstractProxiedMethods($originalClass, $skipDestructor),
[
$init,
new StaticProxyConstructor($initializer, $filteredProperties),
Expand Down Expand Up @@ -124,7 +126,8 @@ static function (MethodGenerator $generatedMethod) use ($originalClass, $classGe
new GetProxyInitializer($initializer),
new InitializeProxy($initializer, $init),
new IsProxyInitialized($initializer),
]
],
$skipDestructor ? [new SkipDestructor($initializer)] : []
)
);
}
Expand All @@ -134,8 +137,22 @@ static function (MethodGenerator $generatedMethod) use ($originalClass, $classGe
*
* @return MethodGenerator[]
*/
private function getAbstractProxiedMethods(ReflectionClass $originalClass): array
private function getAbstractProxiedMethods(ReflectionClass $originalClass, bool $skipDestructor): array
{
$excludedMethods = [
'__get',
'__set',
'__isset',
'__unset',
'__clone',
'__sleep',
'__wakeup',
];

if ($skipDestructor) {
$excludedMethods[] = '__destruct';
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: rename the option to "excludeDestructor" since that seems to be the internal wording.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure about this proposal: "exclude" here is used for a different thing.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My thinking was that you're excluding the destructor from the list of proxied methods, but I defer to your (and @Ocramius') judgment on this 👍

}

return array_map(
static function (ReflectionMethod $method): ProxyManagerMethodGenerator {
$generated = ProxyManagerMethodGenerator::fromReflectionWithoutBodyAndDocBlock(
Expand All @@ -146,7 +163,7 @@ static function (ReflectionMethod $method): ProxyManagerMethodGenerator {

return $generated;
},
ProxiedMethodsFilter::getAbstractProxiedMethods($originalClass)
ProxiedMethodsFilter::getAbstractProxiedMethods($originalClass, $excludedMethods)
);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

declare(strict_types=1);

namespace ProxyManager\ProxyGenerator\LazyLoadingValueHolder\MethodGenerator;

use Laminas\Code\Generator\PropertyGenerator;
use ProxyManager\Generator\MethodGenerator;
use ReflectionClass;

/**
* Destructor that skips the original destructor when the proxy is not initialized.
*/
class SkipDestructor extends MethodGenerator
{
/**
* Constructor
*/
public function __construct(
PropertyGenerator $initializerProperty,
PropertyGenerator $valueHolderProperty
) {
parent::__construct('__destruct');

$initializer = $initializerProperty->getName();
$valueHolder = $valueHolderProperty->getName();

$this->setBody(
'$this->' . $initializer . ' || $this->' . $valueHolder . '->__destruct();'
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
use ProxyManager\ProxyGenerator\LazyLoadingValueHolder\MethodGenerator\MagicSleep;
use ProxyManager\ProxyGenerator\LazyLoadingValueHolder\MethodGenerator\MagicUnset;
use ProxyManager\ProxyGenerator\LazyLoadingValueHolder\MethodGenerator\SetProxyInitializer;
use ProxyManager\ProxyGenerator\LazyLoadingValueHolder\MethodGenerator\SkipDestructor;
use ProxyManager\ProxyGenerator\LazyLoadingValueHolder\PropertyGenerator\InitializerProperty;
use ProxyManager\ProxyGenerator\LazyLoadingValueHolder\PropertyGenerator\ValueHolderProperty;
use ProxyManager\ProxyGenerator\PropertyGenerator\PublicPropertiesMap;
Expand All @@ -48,12 +49,14 @@ class LazyLoadingValueHolderGenerator implements ProxyGeneratorInterface
/**
* {@inheritDoc}
*
* @psalm-param array{skipDestructor?: bool} $proxyOptions
*
* @return void
*
* @throws InvalidProxiedClassException
* @throws InvalidArgumentException
*/
public function generate(ReflectionClass $originalClass, ClassGenerator $classGenerator)
public function generate(ReflectionClass $originalClass, ClassGenerator $classGenerator, array $proxyOptions = [])
nicolas-grekas marked this conversation as resolved.
Show resolved Hide resolved
{
CanProxyAssertion::assertClassCanBeProxied($originalClass);

Expand All @@ -71,14 +74,29 @@ public function generate(ReflectionClass $originalClass, ClassGenerator $classGe
$classGenerator->addPropertyFromGenerator($initializer = new InitializerProperty());
$classGenerator->addPropertyFromGenerator($publicProperties);

$skipDestructor = ($proxyOptions['skipDestructor'] ?? false) && $originalClass->hasMethod('__destruct');
$excludedMethods = [
'__get',
'__set',
'__isset',
'__unset',
'__clone',
'__sleep',
'__wakeup',
];

if ($skipDestructor) {
$excludedMethods[] = '__destruct';
}

array_map(
static function (MethodGenerator $generatedMethod) use ($originalClass, $classGenerator): void {
ClassGeneratorUtils::addMethodIfNotFinal($originalClass, $classGenerator, $generatedMethod);
},
array_merge(
array_map(
$this->buildLazyLoadingMethodInterceptor($initializer, $valueHolder),
ProxiedMethodsFilter::getProxiedMethods($originalClass)
ProxiedMethodsFilter::getProxiedMethods($originalClass, $excludedMethods)
),
[
new StaticProxyConstructor($initializer, Properties::fromReflectionClass($originalClass)),
Expand All @@ -95,7 +113,8 @@ static function (MethodGenerator $generatedMethod) use ($originalClass, $classGe
new InitializeProxy($initializer, $valueHolder),
new IsProxyInitialized($valueHolder),
new GetWrappedValueHolderValue($valueHolder),
]
],
$skipDestructor ? [new SkipDestructor($initializer, $valueHolder)] : []
)
);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
--TEST--
Verifies that generated lazy loading ghost objects can skip calling the proxied destructor
--FILE--
<?php

require_once __DIR__ . '/init.php';

class Destructable
{
public function __destruct()
{
echo __FUNCTION__;
}
}

$factory = new \ProxyManager\Factory\LazyLoadingGhostFactory($configuration);

$init = function ($object, $method, $parameters, & $initializer) {
echo 'init';
$initializer = null;
};

$proxy = $factory->createProxy(Destructable::class, $init, ['skipDestructor' => true]);
echo "NO __destruct\n";
unset($proxy);

$proxy = $factory->createProxy(Destructable::class, $init, ['skipDestructor' => true]);
echo 'DO ';
$proxy->triggerInit = true;
unset($proxy);

$proxy = $factory->createProxy(Destructable::class, $init);
echo "\nDO ";
unset($proxy);
?>
--EXPECT--
NO __destruct
DO init__destruct
DO __destruct
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
--TEST--
Verifies that generated lazy loading value holders can skip calling the proxied destructor
--FILE--
<?php

require_once __DIR__ . '/init.php';

class Destructable
{
public function __destruct()
{
echo __FUNCTION__;
}
}

$factory = new \ProxyManager\Factory\LazyLoadingValueHolderFactory($configuration);

$init = function (& $wrapped, $proxy, $method, $parameters, & $initializer) {
echo 'init';
$wrapped = new Destructable();
$initializer = null;
};

$proxy = $factory->createProxy(Destructable::class, $init, ['skipDestructor' => true]);
echo "NO __destruct\n";
unset($proxy);

$proxy = $factory->createProxy(Destructable::class, $init, ['skipDestructor' => true]);
echo "DO ";
$proxy->triggerInit = true;
unset($proxy);

$proxy = $factory->createProxy(Destructable::class, $init);
echo "\nDO ";
unset($proxy);
?>
--EXPECT--
NO __destruct
DO init__destruct__destruct
DO init__destruct__destruct