ProxyFactory.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. <?php
  2. /*
  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.
  14. *
  15. * This software consists of voluntary contributions made by many individuals
  16. * and is licensed under the LGPL. For more information, see
  17. * <http://www.doctrine-project.org>.
  18. */
  19. namespace Doctrine\ORM\Proxy;
  20. use Doctrine\ORM\EntityManager,
  21. Doctrine\ORM\Mapping\ClassMetadata,
  22. Doctrine\ORM\Mapping\AssociationMapping,
  23. Doctrine\Common\Util\ClassUtils;
  24. /**
  25. * This factory is used to create proxy objects for entities at runtime.
  26. *
  27. * @author Roman Borschel <roman@code-factory.org>
  28. * @author Giorgio Sironi <piccoloprincipeazzurro@gmail.com>
  29. * @since 2.0
  30. */
  31. class ProxyFactory
  32. {
  33. /** The EntityManager this factory is bound to. */
  34. private $_em;
  35. /** Whether to automatically (re)generate proxy classes. */
  36. private $_autoGenerate;
  37. /** The namespace that contains all proxy classes. */
  38. private $_proxyNamespace;
  39. /** The directory that contains all proxy classes. */
  40. private $_proxyDir;
  41. /**
  42. * Used to match very simple id methods that don't need
  43. * to be proxied since the identifier is known.
  44. *
  45. * @var string
  46. */
  47. 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';
  48. /**
  49. * Initializes a new instance of the <tt>ProxyFactory</tt> class that is
  50. * connected to the given <tt>EntityManager</tt>.
  51. *
  52. * @param EntityManager $em The EntityManager the new factory works for.
  53. * @param string $proxyDir The directory to use for the proxy classes. It must exist.
  54. * @param string $proxyNs The namespace to use for the proxy classes.
  55. * @param boolean $autoGenerate Whether to automatically generate proxy classes.
  56. */
  57. public function __construct(EntityManager $em, $proxyDir, $proxyNs, $autoGenerate = false)
  58. {
  59. if ( ! $proxyDir) {
  60. throw ProxyException::proxyDirectoryRequired();
  61. }
  62. if ( ! $proxyNs) {
  63. throw ProxyException::proxyNamespaceRequired();
  64. }
  65. $this->_em = $em;
  66. $this->_proxyDir = $proxyDir;
  67. $this->_autoGenerate = $autoGenerate;
  68. $this->_proxyNamespace = $proxyNs;
  69. }
  70. /**
  71. * Gets a reference proxy instance for the entity of the given type and identified by
  72. * the given identifier.
  73. *
  74. * @param string $className
  75. * @param mixed $identifier
  76. * @return object
  77. */
  78. public function getProxy($className, $identifier)
  79. {
  80. $fqn = ClassUtils::generateProxyClassName($className, $this->_proxyNamespace);
  81. if (! class_exists($fqn, false)) {
  82. $fileName = $this->getProxyFileName($className);
  83. if ($this->_autoGenerate) {
  84. $this->_generateProxyClass($this->_em->getClassMetadata($className), $fileName, self::$_proxyClassTemplate);
  85. }
  86. require $fileName;
  87. }
  88. if ( ! $this->_em->getMetadataFactory()->hasMetadataFor($fqn)) {
  89. $this->_em->getMetadataFactory()->setMetadataFor($fqn, $this->_em->getClassMetadata($className));
  90. }
  91. $entityPersister = $this->_em->getUnitOfWork()->getEntityPersister($className);
  92. return new $fqn($entityPersister, $identifier);
  93. }
  94. /**
  95. * Generate the Proxy file name
  96. *
  97. * @param string $className
  98. * @param string $baseDir Optional base directory for proxy file name generation.
  99. * If not specified, the directory configured on the Configuration of the
  100. * EntityManager will be used by this factory.
  101. * @return string
  102. */
  103. private function getProxyFileName($className, $baseDir = null)
  104. {
  105. $proxyDir = $baseDir ?: $this->_proxyDir;
  106. return $proxyDir . DIRECTORY_SEPARATOR . '__CG__' . str_replace('\\', '', $className) . '.php';
  107. }
  108. /**
  109. * Generates proxy classes for all given classes.
  110. *
  111. * @param array $classes The classes (ClassMetadata instances) for which to generate proxies.
  112. * @param string $toDir The target directory of the proxy classes. If not specified, the
  113. * directory configured on the Configuration of the EntityManager used
  114. * by this factory is used.
  115. * @return int Number of generated proxies.
  116. */
  117. public function generateProxyClasses(array $classes, $toDir = null)
  118. {
  119. $proxyDir = $toDir ?: $this->_proxyDir;
  120. $proxyDir = rtrim($proxyDir, DIRECTORY_SEPARATOR);
  121. $num = 0;
  122. foreach ($classes as $class) {
  123. /* @var $class ClassMetadata */
  124. if ($class->isMappedSuperclass || $class->reflClass->isAbstract()) {
  125. continue;
  126. }
  127. $proxyFileName = $this->getProxyFileName($class->name, $proxyDir);
  128. $this->_generateProxyClass($class, $proxyFileName, self::$_proxyClassTemplate);
  129. $num++;
  130. }
  131. return $num;
  132. }
  133. /**
  134. * Generates a proxy class file.
  135. *
  136. * @param $class
  137. * @param $proxyClassName
  138. * @param $file The path of the file to write to.
  139. */
  140. private function _generateProxyClass($class, $fileName, $file)
  141. {
  142. $methods = $this->_generateMethods($class);
  143. $sleepImpl = $this->_generateSleep($class);
  144. $cloneImpl = $class->reflClass->hasMethod('__clone') ? 'parent::__clone();' : ''; // hasMethod() checks case-insensitive
  145. $placeholders = array(
  146. '<namespace>',
  147. '<proxyClassName>', '<className>',
  148. '<methods>', '<sleepImpl>', '<cloneImpl>'
  149. );
  150. $className = ltrim($class->name, '\\');
  151. $proxyClassName = ClassUtils::generateProxyClassName($class->name, $this->_proxyNamespace);
  152. $parts = explode('\\', strrev($proxyClassName), 2);
  153. $proxyClassNamespace = strrev($parts[1]);
  154. $proxyClassName = strrev($parts[0]);
  155. $replacements = array(
  156. $proxyClassNamespace,
  157. $proxyClassName,
  158. $className,
  159. $methods,
  160. $sleepImpl,
  161. $cloneImpl
  162. );
  163. $file = str_replace($placeholders, $replacements, $file);
  164. file_put_contents($fileName, $file, LOCK_EX);
  165. }
  166. /**
  167. * Generates the methods of a proxy class.
  168. *
  169. * @param ClassMetadata $class
  170. * @return string The code of the generated methods.
  171. */
  172. private function _generateMethods(ClassMetadata $class)
  173. {
  174. $methods = '';
  175. $methodNames = array();
  176. foreach ($class->reflClass->getMethods() as $method) {
  177. /* @var $method ReflectionMethod */
  178. if ($method->isConstructor() || in_array(strtolower($method->getName()), array("__sleep", "__clone")) || isset($methodNames[$method->getName()])) {
  179. continue;
  180. }
  181. $methodNames[$method->getName()] = true;
  182. if ($method->isPublic() && ! $method->isFinal() && ! $method->isStatic()) {
  183. $methods .= "\n" . ' public function ';
  184. if ($method->returnsReference()) {
  185. $methods .= '&';
  186. }
  187. $methods .= $method->getName() . '(';
  188. $firstParam = true;
  189. $parameterString = $argumentString = '';
  190. foreach ($method->getParameters() as $param) {
  191. if ($firstParam) {
  192. $firstParam = false;
  193. } else {
  194. $parameterString .= ', ';
  195. $argumentString .= ', ';
  196. }
  197. // We need to pick the type hint class too
  198. if (($paramClass = $param->getClass()) !== null) {
  199. $parameterString .= '\\' . $paramClass->getName() . ' ';
  200. } else if ($param->isArray()) {
  201. $parameterString .= 'array ';
  202. }
  203. if ($param->isPassedByReference()) {
  204. $parameterString .= '&';
  205. }
  206. $parameterString .= '$' . $param->getName();
  207. $argumentString .= '$' . $param->getName();
  208. if ($param->isDefaultValueAvailable()) {
  209. $parameterString .= ' = ' . var_export($param->getDefaultValue(), true);
  210. }
  211. }
  212. $methods .= $parameterString . ')';
  213. $methods .= "\n" . ' {' . "\n";
  214. if ($this->isShortIdentifierGetter($method, $class)) {
  215. $identifier = lcfirst(substr($method->getName(), 3));
  216. $cast = in_array($class->fieldMappings[$identifier]['type'], array('integer', 'smallint')) ? '(int) ' : '';
  217. $methods .= ' if ($this->__isInitialized__ === false) {' . "\n";
  218. $methods .= ' return ' . $cast . '$this->_identifier["' . $identifier . '"];' . "\n";
  219. $methods .= ' }' . "\n";
  220. }
  221. $methods .= ' $this->__load();' . "\n";
  222. $methods .= ' return parent::' . $method->getName() . '(' . $argumentString . ');';
  223. $methods .= "\n" . ' }' . "\n";
  224. }
  225. }
  226. return $methods;
  227. }
  228. /**
  229. * Check if the method is a short identifier getter.
  230. *
  231. * What does this mean? For proxy objects the identifier is already known,
  232. * however accessing the getter for this identifier usually triggers the
  233. * lazy loading, leading to a query that may not be necessary if only the
  234. * ID is interesting for the userland code (for example in views that
  235. * generate links to the entity, but do not display anything else).
  236. *
  237. * @param ReflectionMethod $method
  238. * @param ClassMetadata $class
  239. * @return bool
  240. */
  241. private function isShortIdentifierGetter($method, $class)
  242. {
  243. $identifier = lcfirst(substr($method->getName(), 3));
  244. $cheapCheck = (
  245. $method->getNumberOfParameters() == 0 &&
  246. substr($method->getName(), 0, 3) == "get" &&
  247. in_array($identifier, $class->identifier, true) &&
  248. $class->hasField($identifier) &&
  249. (($method->getEndLine() - $method->getStartLine()) <= 4)
  250. && in_array($class->fieldMappings[$identifier]['type'], array('integer', 'bigint', 'smallint', 'string'))
  251. );
  252. if ($cheapCheck) {
  253. $code = file($method->getDeclaringClass()->getFileName());
  254. $code = trim(implode(" ", array_slice($code, $method->getStartLine() - 1, $method->getEndLine() - $method->getStartLine() + 1)));
  255. $pattern = sprintf(self::PATTERN_MATCH_ID_METHOD, $method->getName(), $identifier);
  256. if (preg_match($pattern, $code)) {
  257. return true;
  258. }
  259. }
  260. return false;
  261. }
  262. /**
  263. * Generates the code for the __sleep method for a proxy class.
  264. *
  265. * @param $class
  266. * @return string
  267. */
  268. private function _generateSleep(ClassMetadata $class)
  269. {
  270. $sleepImpl = '';
  271. if ($class->reflClass->hasMethod('__sleep')) {
  272. $sleepImpl .= "return array_merge(array('__isInitialized__'), parent::__sleep());";
  273. } else {
  274. $sleepImpl .= "return array('__isInitialized__', ";
  275. $first = true;
  276. foreach ($class->getReflectionProperties() as $name => $prop) {
  277. if ($first) {
  278. $first = false;
  279. } else {
  280. $sleepImpl .= ', ';
  281. }
  282. $sleepImpl .= "'" . $name . "'";
  283. }
  284. $sleepImpl .= ');';
  285. }
  286. return $sleepImpl;
  287. }
  288. /** Proxy class code template */
  289. private static $_proxyClassTemplate =
  290. '<?php
  291. namespace <namespace>;
  292. /**
  293. * THIS CLASS WAS GENERATED BY THE DOCTRINE ORM. DO NOT EDIT THIS FILE.
  294. */
  295. class <proxyClassName> extends \<className> implements \Doctrine\ORM\Proxy\Proxy
  296. {
  297. private $_entityPersister;
  298. private $_identifier;
  299. public $__isInitialized__ = false;
  300. public function __construct($entityPersister, $identifier)
  301. {
  302. $this->_entityPersister = $entityPersister;
  303. $this->_identifier = $identifier;
  304. }
  305. /** @private */
  306. public function __load()
  307. {
  308. if (!$this->__isInitialized__ && $this->_entityPersister) {
  309. $this->__isInitialized__ = true;
  310. if (method_exists($this, "__wakeup")) {
  311. // call this after __isInitialized__to avoid infinite recursion
  312. // but before loading to emulate what ClassMetadata::newInstance()
  313. // provides.
  314. $this->__wakeup();
  315. }
  316. if ($this->_entityPersister->load($this->_identifier, $this) === null) {
  317. throw new \Doctrine\ORM\EntityNotFoundException();
  318. }
  319. unset($this->_entityPersister, $this->_identifier);
  320. }
  321. }
  322. /** @private */
  323. public function __isInitialized()
  324. {
  325. return $this->__isInitialized__;
  326. }
  327. <methods>
  328. public function __sleep()
  329. {
  330. <sleepImpl>
  331. }
  332. public function __clone()
  333. {
  334. if (!$this->__isInitialized__ && $this->_entityPersister) {
  335. $this->__isInitialized__ = true;
  336. $class = $this->_entityPersister->getClassMetadata();
  337. $original = $this->_entityPersister->load($this->_identifier);
  338. if ($original === null) {
  339. throw new \Doctrine\ORM\EntityNotFoundException();
  340. }
  341. foreach ($class->reflFields AS $field => $reflProperty) {
  342. $reflProperty->setValue($this, $reflProperty->getValue($original));
  343. }
  344. unset($this->_entityPersister, $this->_identifier);
  345. }
  346. <cloneImpl>
  347. }
  348. }';
  349. }