3
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
4
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
13
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
15
* This software consists of voluntary contributions made by many individuals
16
* and is licensed under the MIT license. For more information, see
17
* <http://www.doctrine-project.org>.
20
namespace Doctrine\Common\Proxy;
22
use Doctrine\Common\Persistence\Mapping\ClassMetadata;
23
use Doctrine\Common\Util\ClassUtils;
24
use Doctrine\Common\Proxy\Exception\InvalidArgumentException;
25
use Doctrine\Common\Proxy\Exception\UnexpectedValueException;
28
* This factory is used to generate proxy classes.
29
* It builds proxies from given parameters, a template and class metadata.
31
* @author Marco Pivetta <ocramius@gmail.com>
37
* Used to match very simple id methods that don't need
38
* to be decorated since the identifier is known.
40
const PATTERN_MATCH_ID_METHOD = '((public\s)?(function\s{1,}%s\s?\(\)\s{1,})\s{0,}{\s{0,}return\s{0,}\$this->%s;\s{0,}})i';
43
* The namespace that contains all proxy classes.
47
private $proxyNamespace;
50
* The directory that contains all proxy classes.
54
private $proxyDirectory;
57
* Map of callables used to fill in placeholders set in the template.
59
* @var string[]|callable[]
61
protected $placeholders = array(
62
'baseProxyInterface' => 'Doctrine\Common\Proxy\Proxy',
63
'additionalProperties' => '',
67
* Template used as a blueprint to generate proxies.
71
protected $proxyClassTemplate = '<?php
73
namespace <namespace>;
76
* DO NOT EDIT THIS FILE - IT WAS CREATED BY DOCTRINE\'S PROXY GENERATOR
78
class <proxyShortClassName> extends \<className> implements \<baseProxyInterface>
81
* @var \Closure the callback responsible for loading properties in the proxy object. This callback is called with
82
* three parameters, being respectively the proxy object to be initialized, the method that triggered the
83
* initialization process and an array of ordered parameters that were passed to that method.
85
* @see \Doctrine\Common\Persistence\Proxy::__setInitializer
87
public $__initializer__;
90
* @var \Closure the callback responsible of loading properties that need to be copied in the cloned object
92
* @see \Doctrine\Common\Persistence\Proxy::__setCloner
97
* @var boolean flag indicating if this object was already initialized
99
* @see \Doctrine\Common\Persistence\Proxy::__isInitialized
101
public $__isInitialized__ = false;
104
* @var array properties to be lazy loaded, with keys being the property
105
* names and values being their default values
107
* @see \Doctrine\Common\Persistence\Proxy::__getLazyProperties
109
public static $lazyPropertiesDefaults = array(<lazyPropertiesDefaults>);
111
<additionalProperties>
128
* Forces initialization of the proxy
130
public function __load()
132
$this->__initializer__ && $this->__initializer__->__invoke($this, \'__load\', array());
137
* @internal generated method: use only when explicitly handling proxy specific loading logic
139
public function __isInitialized()
141
return $this->__isInitialized__;
146
* @internal generated method: use only when explicitly handling proxy specific loading logic
148
public function __setInitialized($initialized)
150
$this->__isInitialized__ = $initialized;
155
* @internal generated method: use only when explicitly handling proxy specific loading logic
157
public function __setInitializer(\Closure $initializer = null)
159
$this->__initializer__ = $initializer;
164
* @internal generated method: use only when explicitly handling proxy specific loading logic
166
public function __getInitializer()
168
return $this->__initializer__;
173
* @internal generated method: use only when explicitly handling proxy specific loading logic
175
public function __setCloner(\Closure $cloner = null)
177
$this->__cloner__ = $cloner;
182
* @internal generated method: use only when explicitly handling proxy specific cloning logic
184
public function __getCloner()
186
return $this->__cloner__;
191
* @internal generated method: use only when explicitly handling proxy specific loading logic
194
public function __getLazyProperties()
196
return self::$lazyPropertiesDefaults;
204
* Initializes a new instance of the <tt>ProxyFactory</tt> class that is
205
* connected to the given <tt>EntityManager</tt>.
207
* @param string $proxyDirectory The directory to use for the proxy classes. It must exist.
208
* @param string $proxyNamespace The namespace to use for the proxy classes.
210
* @throws InvalidArgumentException
212
public function __construct($proxyDirectory, $proxyNamespace)
214
if ( ! $proxyDirectory) {
215
throw InvalidArgumentException::proxyDirectoryRequired();
218
if ( ! $proxyNamespace) {
219
throw InvalidArgumentException::proxyNamespaceRequired();
222
$this->proxyDirectory = $proxyDirectory;
223
$this->proxyNamespace = $proxyNamespace;
227
* Sets a placeholder to be replaced in the template.
229
* @param string $name
230
* @param string|callable $placeholder
232
* @throws InvalidArgumentException
234
public function setPlaceholder($name, $placeholder)
236
if ( ! is_string($placeholder) && ! is_callable($placeholder)) {
237
throw InvalidArgumentException::invalidPlaceholder($name);
240
$this->placeholders[$name] = $placeholder;
244
* Sets the base template used to create proxy classes.
246
* @param string $proxyClassTemplate
248
public function setProxyClassTemplate($proxyClassTemplate)
250
$this->proxyClassTemplate = (string) $proxyClassTemplate;
254
* Generates a proxy class file.
256
* @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class Metadata for the original class.
257
* @param string|bool $fileName Filename (full path) for the generated class. If none is given, eval() is used.
259
* @throws UnexpectedValueException
261
public function generateProxyClass(ClassMetadata $class, $fileName = false)
263
preg_match_all('(<([a-zA-Z]+)>)', $this->proxyClassTemplate, $placeholderMatches);
265
$placeholderMatches = array_combine($placeholderMatches[0], $placeholderMatches[1]);
266
$placeholders = array();
268
foreach ($placeholderMatches as $placeholder => $name) {
269
$placeholders[$placeholder] = isset($this->placeholders[$name])
270
? $this->placeholders[$name]
271
: array($this, 'generate' . $name);
274
foreach ($placeholders as & $placeholder) {
275
if (is_callable($placeholder)) {
276
$placeholder = call_user_func($placeholder, $class);
280
$proxyCode = strtr($this->proxyClassTemplate, $placeholders);
283
$proxyClassName = $this->generateNamespace($class) . '\\' . $this->generateProxyShortClassName($class);
285
if ( ! class_exists($proxyClassName)) {
286
eval(substr($proxyCode, 5));
292
$parentDirectory = dirname($fileName);
294
if ( ! is_dir($parentDirectory) && (false === @mkdir($parentDirectory, 0775, true))) {
295
throw UnexpectedValueException::proxyDirectoryNotWritable($this->proxyDirectory);
298
if ( ! is_writable($parentDirectory)) {
299
throw UnexpectedValueException::proxyDirectoryNotWritable($this->proxyDirectory);
302
$tmpFileName = $fileName . '.' . uniqid('', true);
304
file_put_contents($tmpFileName, $proxyCode);
305
rename($tmpFileName, $fileName);
309
* Generates the proxy short class name to be used in the template.
311
* @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class
315
private function generateProxyShortClassName(ClassMetadata $class)
317
$proxyClassName = ClassUtils::generateProxyClassName($class->getName(), $this->proxyNamespace);
318
$parts = explode('\\', strrev($proxyClassName), 2);
320
return strrev($parts[0]);
324
* Generates the proxy namespace.
326
* @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class
330
private function generateNamespace(ClassMetadata $class)
332
$proxyClassName = ClassUtils::generateProxyClassName($class->getName(), $this->proxyNamespace);
333
$parts = explode('\\', strrev($proxyClassName), 2);
335
return strrev($parts[1]);
339
* Generates the original class name.
341
* @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class
345
private function generateClassName(ClassMetadata $class)
347
return ltrim($class->getName(), '\\');
351
* Generates the array representation of lazy loaded public properties and their default values.
353
* @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class
357
private function generateLazyPropertiesDefaults(ClassMetadata $class)
359
$lazyPublicProperties = $this->getLazyLoadedPublicProperties($class);
362
foreach ($lazyPublicProperties as $key => $value) {
363
$values[] = var_export($key, true) . ' => ' . var_export($value, true);
366
return implode(', ', $values);
370
* Generates the constructor code (un-setting public lazy loaded properties, setting identifier field values).
372
* @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class
376
private function generateConstructorImpl(ClassMetadata $class)
378
$constructorImpl = <<<'EOT'
380
* @param \Closure $initializer
381
* @param \Closure $cloner
383
public function __construct($initializer = null, $cloner = null)
389
foreach ($this->getLazyLoadedPublicProperties($class) as $lazyPublicProperty => $unused) {
390
$toUnset[] = '$this->' . $lazyPublicProperty;
393
$constructorImpl .= (empty($toUnset) ? '' : ' unset(' . implode(', ', $toUnset) . ");\n")
396
$this->__initializer__ = $initializer;
397
$this->__cloner__ = $cloner;
401
return $constructorImpl;
405
* Generates the magic getter invoked when lazy loaded public properties are requested.
407
* @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class
411
private function generateMagicGet(ClassMetadata $class)
413
$lazyPublicProperties = array_keys($this->getLazyLoadedPublicProperties($class));
414
$reflectionClass = $class->getReflectionClass();
415
$hasParentGet = false;
416
$returnReference = '';
419
if ($reflectionClass->hasMethod('__get')) {
420
$hasParentGet = true;
421
$inheritDoc = '{@inheritDoc}';
423
if ($reflectionClass->getMethod('__get')->returnsReference()) {
424
$returnReference = '& ';
428
if (empty($lazyPublicProperties) && ! $hasParentGet) {
435
* @param string \$name
437
public function {$returnReference}__get(\$name)
442
if ( ! empty($lazyPublicProperties)) {
443
$magicGet .= <<<'EOT'
444
if (array_key_exists($name, $this->__getLazyProperties())) {
445
$this->__initializer__ && $this->__initializer__->__invoke($this, '__get', array($name));
455
$magicGet .= <<<'EOT'
456
$this->__initializer__ && $this->__initializer__->__invoke($this, '__get', array($name));
458
return parent::__get($name);
462
$magicGet .= <<<'EOT'
463
trigger_error(sprintf('Undefined property: %s::$%s', __CLASS__, $name), E_USER_NOTICE);
474
* Generates the magic setter (currently unused).
476
* @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class
480
private function generateMagicSet(ClassMetadata $class)
482
$lazyPublicProperties = $this->getLazyLoadedPublicProperties($class);
483
$hasParentSet = $class->getReflectionClass()->hasMethod('__set');
485
if (empty($lazyPublicProperties) && ! $hasParentSet) {
489
$inheritDoc = $hasParentSet ? '{@inheritDoc}' : '';
493
* @param string \$name
494
* @param mixed \$value
496
public function __set(\$name, \$value)
501
if ( ! empty($lazyPublicProperties)) {
502
$magicSet .= <<<'EOT'
503
if (array_key_exists($name, $this->__getLazyProperties())) {
504
$this->__initializer__ && $this->__initializer__->__invoke($this, '__set', array($name, $value));
506
$this->$name = $value;
516
$magicSet .= <<<'EOT'
517
$this->__initializer__ && $this->__initializer__->__invoke($this, '__set', array($name, $value));
519
return parent::__set($name, $value);
522
$magicSet .= " \$this->\$name = \$value;";
531
* Generates the magic issetter invoked when lazy loaded public properties are checked against isset().
533
* @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class
537
private function generateMagicIsset(ClassMetadata $class)
539
$lazyPublicProperties = array_keys($this->getLazyLoadedPublicProperties($class));
540
$hasParentIsset = $class->getReflectionClass()->hasMethod('__isset');
542
if (empty($lazyPublicProperties) && ! $hasParentIsset) {
546
$inheritDoc = $hasParentIsset ? '{@inheritDoc}' : '';
550
* @param string \$name
553
public function __isset(\$name)
558
if ( ! empty($lazyPublicProperties)) {
559
$magicIsset .= <<<'EOT'
560
if (array_key_exists($name, $this->__getLazyProperties())) {
561
$this->__initializer__ && $this->__initializer__->__invoke($this, '__isset', array($name));
563
return isset($this->$name);
570
if ($hasParentIsset) {
571
$magicIsset .= <<<'EOT'
572
$this->__initializer__ && $this->__initializer__->__invoke($this, '__isset', array($name));
574
return parent::__isset($name);
578
$magicIsset .= " return false;";
581
return $magicIsset . "\n }";
585
* Generates implementation for the `__sleep` method of proxies.
587
* @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class
591
private function generateSleepImpl(ClassMetadata $class)
593
$hasParentSleep = $class->getReflectionClass()->hasMethod('__sleep');
594
$inheritDoc = $hasParentSleep ? '{@inheritDoc}' : '';
600
public function __sleep()
605
if ($hasParentSleep) {
606
return $sleepImpl . <<<'EOT'
607
$properties = array_merge(array('__isInitialized__'), parent::__sleep());
609
if ($this->__isInitialized__) {
610
$properties = array_diff($properties, array_keys($this->__getLazyProperties()));
618
$allProperties = array('__isInitialized__');
620
/* @var $prop \ReflectionProperty */
621
foreach ($class->getReflectionClass()->getProperties() as $prop) {
622
if ($prop->isStatic()) {
626
$allProperties[] = $prop->isPrivate()
627
? "\0" . $prop->getDeclaringClass()->getName() . "\0" . $prop->getName()
631
$lazyPublicProperties = array_keys($this->getLazyLoadedPublicProperties($class));
632
$protectedProperties = array_diff($allProperties, $lazyPublicProperties);
634
foreach ($allProperties as &$property) {
635
$property = var_export($property, true);
638
foreach ($protectedProperties as &$property) {
639
$property = var_export($property, true);
642
$allProperties = implode(', ', $allProperties);
643
$protectedProperties = implode(', ', $protectedProperties);
645
return $sleepImpl . <<<EOT
646
if (\$this->__isInitialized__) {
647
return array($allProperties);
650
return array($protectedProperties);
656
* Generates implementation for the `__wakeup` method of proxies.
658
* @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class
662
private function generateWakeupImpl(ClassMetadata $class)
664
$unsetPublicProperties = array();
665
$hasWakeup = $class->getReflectionClass()->hasMethod('__wakeup');
667
foreach (array_keys($this->getLazyLoadedPublicProperties($class)) as $lazyPublicProperty) {
668
$unsetPublicProperties[] = '$this->' . $lazyPublicProperty;
671
$shortName = $this->generateProxyShortClassName($class);
672
$inheritDoc = $hasWakeup ? '{@inheritDoc}' : '';
677
public function __wakeup()
679
if ( ! \$this->__isInitialized__) {
680
\$this->__initializer__ = function ($shortName \$proxy) {
681
\$proxy->__setInitializer(null);
682
\$proxy->__setCloner(null);
684
\$existingProperties = get_object_vars(\$proxy);
686
foreach (\$proxy->__getLazyProperties() as \$property => \$defaultValue) {
687
if ( ! array_key_exists(\$property, \$existingProperties)) {
688
\$proxy->\$property = \$defaultValue;
695
if ( ! empty($unsetPublicProperties)) {
696
$wakeupImpl .= "\n unset(" . implode(', ', $unsetPublicProperties) . ");";
699
$wakeupImpl .= "\n }";
702
$wakeupImpl .= "\n parent::__wakeup();";
705
$wakeupImpl .= "\n }";
711
* Generates implementation for the `__clone` method of proxies.
713
* @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class
717
private function generateCloneImpl(ClassMetadata $class)
719
$hasParentClone = $class->getReflectionClass()->hasMethod('__clone');
720
$inheritDoc = $hasParentClone ? '{@inheritDoc}' : '';
721
$callParentClone = $hasParentClone ? "\n parent::__clone();\n" : '';
727
public function __clone()
729
\$this->__cloner__ && \$this->__cloner__->__invoke(\$this, '__clone', array());
735
* Generates decorated methods by picking those available in the parent class.
737
* @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class
741
private function generateMethods(ClassMetadata $class)
744
$methodNames = array();
745
$reflectionMethods = $class->getReflectionClass()->getMethods(\ReflectionMethod::IS_PUBLIC);
746
$skippedMethods = array(
755
foreach ($reflectionMethods as $method) {
756
$name = $method->getName();
759
$method->isConstructor() ||
760
isset($skippedMethods[strtolower($name)]) ||
761
isset($methodNames[$name]) ||
762
$method->isFinal() ||
763
$method->isStatic() ||
764
( ! $method->isPublic())
769
$methodNames[$name] = true;
770
$methods .= "\n /**\n"
771
. " * {@inheritDoc}\n"
773
. ' public function ';
775
if ($method->returnsReference()) {
779
$methods .= $name . '(';
782
$parameterString = '';
783
$argumentString = '';
784
$parameters = array();
786
foreach ($method->getParameters() as $param) {
790
$parameterString .= ', ';
791
$argumentString .= ', ';
795
$paramClass = $param->getClass();
796
} catch (\ReflectionException $previous) {
797
throw UnexpectedValueException::invalidParameterTypeHint(
805
// We need to pick the type hint class too
806
if (null !== $paramClass) {
807
$parameterString .= '\\' . $paramClass->getName() . ' ';
808
} elseif ($param->isArray()) {
809
$parameterString .= 'array ';
810
} elseif (method_exists($param, 'isCallable') && $param->isCallable()) {
811
$parameterString .= 'callable ';
814
if ($param->isPassedByReference()) {
815
$parameterString .= '&';
818
$parameters[] = '$' . $param->getName();
819
$parameterString .= '$' . $param->getName();
820
$argumentString .= '$' . $param->getName();
822
if ($param->isDefaultValueAvailable()) {
823
$parameterString .= ' = ' . var_export($param->getDefaultValue(), true);
827
$methods .= $parameterString . ')';
828
$methods .= "\n" . ' {' . "\n";
830
if ($this->isShortIdentifierGetter($method, $class)) {
831
$identifier = lcfirst(substr($name, 3));
832
$fieldType = $class->getTypeOfField($identifier);
833
$cast = in_array($fieldType, array('integer', 'smallint')) ? '(int) ' : '';
835
$methods .= ' if ($this->__isInitialized__ === false) {' . "\n";
836
$methods .= ' return ' . $cast . ' parent::' . $method->getName() . "();\n";
837
$methods .= ' }' . "\n\n";
840
$methods .= "\n \$this->__initializer__ "
841
. "&& \$this->__initializer__->__invoke(\$this, " . var_export($name, true)
842
. ", array(" . implode(', ', $parameters) . "));"
843
. "\n\n return parent::" . $name . '(' . $argumentString . ');'
844
. "\n" . ' }' . "\n";
851
* Generates the Proxy file name.
853
* @param string $className
854
* @param string $baseDirectory Optional base directory for proxy file name generation.
855
* If not specified, the directory configured on the Configuration of the
856
* EntityManager will be used by this factory.
860
public function getProxyFileName($className, $baseDirectory = null)
862
$baseDirectory = $baseDirectory ?: $this->proxyDirectory;
864
return rtrim($baseDirectory, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . Proxy::MARKER
865
. str_replace('\\', '', $className) . '.php';
869
* Checks if the method is a short identifier getter.
871
* What does this mean? For proxy objects the identifier is already known,
872
* however accessing the getter for this identifier usually triggers the
873
* lazy loading, leading to a query that may not be necessary if only the
874
* ID is interesting for the userland code (for example in views that
875
* generate links to the entity, but do not display anything else).
877
* @param \ReflectionMethod $method
878
* @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class
882
private function isShortIdentifierGetter($method, ClassMetadata $class)
884
$identifier = lcfirst(substr($method->getName(), 3));
885
$startLine = $method->getStartLine();
886
$endLine = $method->getEndLine();
888
$method->getNumberOfParameters() == 0
889
&& substr($method->getName(), 0, 3) == 'get'
890
&& in_array($identifier, $class->getIdentifier(), true)
891
&& $class->hasField($identifier)
892
&& (($endLine - $startLine) <= 4)
896
$code = file($method->getDeclaringClass()->getFileName());
897
$code = trim(implode(' ', array_slice($code, $startLine - 1, $endLine - $startLine + 1)));
899
$pattern = sprintf(self::PATTERN_MATCH_ID_METHOD, $method->getName(), $identifier);
901
if (preg_match($pattern, $code)) {
910
* Generates the list of public properties to be lazy loaded, with their default values.
912
* @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class
916
private function getLazyLoadedPublicProperties(ClassMetadata $class)
918
$defaultProperties = $class->getReflectionClass()->getDefaultProperties();
919
$properties = array();
921
foreach ($class->getReflectionClass()->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) {
922
$name = $property->getName();
924
if (($class->hasField($name) || $class->hasAssociation($name)) && ! $class->isIdentifier($name)) {
925
$properties[$name] = $defaultProperties[$name];