ProxyFactory.php 10.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
<?php
/*
 *  $Id$
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the LGPL. For more information, see
 * <http://www.doctrine-project.org>.
 */

22
namespace Doctrine\ORM\Proxy;
23

24 25 26 27
use Doctrine\ORM\EntityManager,
    Doctrine\ORM\Mapping\ClassMetadata,
    Doctrine\ORM\Mapping\AssociationMapping,
    Doctrine\Common\DoctrineException;
28 29

/**
30
 * This factory is used to create proxy objects for entities at runtime.
31 32
 *
 * @author Roman Borschel <roman@code-factory.org>
33
 * @author Giorgio Sironi <piccoloprincipeazzurro@gmail.com>
34 35
 * @since 2.0
 */
36
class ProxyFactory
37
{
38
    /** The EntityManager this factory is bound to. */
39
    private $_em;
40 41 42 43 44 45
    /** Whether to automatically (re)generate proxy classes. */
    private $_autoGenerate;
    /** The namespace that contains all proxy classes. */
    private $_proxyNamespace;
    /** The directory that contains all proxy classes. */
    private $_proxyDir;
46 47

    /**
48 49
	 * Initializes a new instance of the <tt>ProxyFactory</tt> class that is
	 * connected to the given <tt>EntityManager</tt>.
50
	 *
51 52 53 54
	 * @param EntityManager $em The EntityManager the new factory works for.
	 * @param string $proxyDir The directory to use for the proxy classes. It must exist.
	 * @param string $proxyNs The namespace to use for the proxy classes.
	 * @param boolean $autoGenerate Whether to automatically generate proxy classes.
55
     */
56
    public function __construct(EntityManager $em, $proxyDir, $proxyNs, $autoGenerate = false)
57
    {
58 59 60 61 62 63
        if ( ! $proxyDir) {
            throw DoctrineException::proxyDirectoryRequired();
        }
        if ( ! $proxyNs) {
            throw DoctrineException::proxyNamespaceRequired();
        }
64
        $this->_em = $em;
65 66 67 68 69
        $this->_proxyDir = $proxyDir;
        $this->_autoGenerate = $autoGenerate;
        $this->_proxyNamespace = $proxyNs;
    } 
    
70
    /**
71 72
     * Gets a reference proxy instance for the entity of the given type and identified by
     * the given identifier.
73 74 75 76 77
     *
     * @param string $className
     * @param mixed $identifier
     * @return object
     */
78
    public function getProxy($className, $identifier)
79
    {
80
        $proxyClassName = str_replace('\\', '', $className) . 'Proxy';
81 82 83 84 85 86 87 88 89 90 91 92
        $fqn = $this->_proxyNamespace . '\\' . $proxyClassName;
        
        if ($this->_autoGenerate && ! class_exists($fqn, false)) {
            $fileName = $this->_proxyDir . DIRECTORY_SEPARATOR . $proxyClassName . '.php';
            $this->_generateProxyClass($this->_em->getClassMetadata($className), $proxyClassName, $fileName, self::$_proxyClassTemplate);
            require $fileName;
        }
        
        if ( ! $this->_em->getMetadataFactory()->hasMetadataFor($fqn)) {
            $this->_em->getMetadataFactory()->setMetadataFor($fqn, $this->_em->getClassMetadata($className));
        }
        
93
        $entityPersister = $this->_em->getUnitOfWork()->getEntityPersister($className);
94 95
        
        return new $fqn($entityPersister, $identifier);
96
    }
97 98 99 100 101 102 103 104 105 106 107 108 109 110
    
    /**
     * Generates proxy classes for all given classes.
     * 
     * @param array $classes The classes (ClassMetadata instances) for which to generate proxies.
     * @param string $toDir The target directory of the proxy classes. If not specified, the
     *                      directory configured on the Configuration of the EntityManager used
     *                      by this factory is used.
     */
    public function generateProxyClasses(array $classes, $toDir = null)
    {
        $proxyDir = $toDir ?: $this->_proxyDir;
        $proxyDir = rtrim($proxyDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
        foreach ($classes as $class) {
111 112 113
            $proxyClassName = str_replace('\\', '', $class->name) . 'Proxy';
            $proxyFileName = $proxyDir . $proxyClassName . '.php';
            $this->_generateProxyClass($class, $proxyClassName, $proxyFileName, self::$_proxyClassTemplate);
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
        }
    }
    
    /**
     * Generates a (reference or association) proxy class.
     * 
     * @param $class
     * @param $originalClassName
     * @param $proxyClassName
     * @param $file The path of the file to write to.
     * @return void
     */
    private function _generateProxyClass($class, $proxyClassName, $fileName, $file)
    {
        $methods = $this->_generateMethods($class);
        $sleepImpl = $this->_generateSleep($class);
        $constructorInv = $class->reflClass->hasMethod('__construct') ? 'parent::__construct();' : '';

        $placeholders = array(
            '<namespace>',
            '<proxyClassName>', '<className>',
            '<methods>', '<sleepImpl>',
            '<constructorInvocation>'
        );
138 139 140 141 142 143 144

        if(substr($class->name, 0, 1) == "\\") {
            $className = substr($class->name, 1);
        } else {
            $className = $class->name;
        }

145 146
        $replacements = array(
            $this->_proxyNamespace,
147
            $proxyClassName, $className,
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
            $methods, $sleepImpl,
            $constructorInv
        );
        
        $file = str_replace($placeholders, $replacements, $file);

        file_put_contents($fileName, $file);
    }
    
    /**
     * Generates the methods of a proxy class.
     * 
     * @param ClassMetadata $class
     * @return string The code of the generated methods.
     */
    private function _generateMethods(ClassMetadata $class)
    {
        $methods = '';
        
        foreach ($class->reflClass->getMethods() as $method) {
            if ($method->isConstructor()) {
                continue;
            }
            
            if ($method->isPublic() && ! $method->isFinal() && ! $method->isStatic()) {
                $methods .= PHP_EOL . '        public function ' . $method->getName() . '(';
                $firstParam = true;
                $parameterString = $argumentString = '';
                
                foreach ($method->getParameters() as $param) {
                    if ($firstParam) {
                        $firstParam = false;
                    } else {
                        $parameterString .= ', ';
                        $argumentString  .= ', ';
                    }
                    
                    // We need to pick the type hint class too
                    if (($paramClass = $param->getClass()) !== null) {
                        $parameterString .= '\\' . $paramClass->getName() . ' ';
                    } else if ($param->isArray()) {
                        $parameterString .= 'array ';
                    }
                    
                    if ($param->isPassedByReference()) {
                        $parameterString .= '&';
                    }
                    
                    $parameterString .= '$' . $param->getName();
                    $argumentString  .= '$' . $param->getName();
                    
                    if ($param->isDefaultValueAvailable()) {
                        $parameterString .= ' = ' . var_export($param->getDefaultValue(), true);
                    }
                }
                
                $methods .= $parameterString . ') {' . PHP_EOL;
                $methods .= '            $this->_load();' . PHP_EOL;
                $methods .= '            return parent::' . $method->getName() . '(' . $argumentString . ');';
                $methods .= PHP_EOL . '        }' . PHP_EOL;
            }
        }
        
        return $methods;
    }
    
    /**
     * Generates the code for the __sleep method for a proxy class.
     * 
     * @param $class
     * @return string
     */
    private function _generateSleep(ClassMetadata $class)
    {
        $sleepImpl = '';
        
        if ($class->reflClass->hasMethod('__sleep')) {
            $sleepImpl .= 'return parent::__sleep();';
        } else {
            $sleepImpl .= 'return array(';
            $first = true;
            
            foreach ($class->getReflectionProperties() as $name => $prop) {
                if ($first) {
                    $first = false;
                } else {
                    $sleepImpl .= ', ';
                }
                
                $sleepImpl .= "'" . $name . "'";
            }
            
            $sleepImpl .= ');';
        }
        
        return $sleepImpl;
    }
    
    /** Reference Proxy class code template */
    private static $_proxyClassTemplate =
'<?php
namespace <namespace> {
    /**
     * THIS CLASS WAS GENERATED BY THE DOCTRINE ORM. DO NOT EDIT THIS FILE.
     */
    class <proxyClassName> extends \<className> implements \Doctrine\ORM\Proxy\Proxy {
        private $_entityPersister;
        private $_identifier;
        private $_loaded = false;
        public function __construct($entityPersister, $identifier) {
            $this->_entityPersister = $entityPersister;
            $this->_identifier = $identifier;
            <constructorInvocation>
        }
        private function _load() {
            if ( ! $this->_loaded) {
                $this->_entityPersister->load($this->_identifier, $this);
                unset($this->_entityPersister);
                unset($this->_identifier);
                $this->_loaded = true;
            }
        }
270
        public function __isInitialized__() { return $this->_loaded; }
271 272 273 274 275 276 277 278 279 280 281

        <methods>

        public function __sleep() {
            if (!$this->_loaded) {
                throw new \RuntimeException("Not fully loaded proxy can not be serialized.");
            }
            <sleepImpl>
        }
    }
}';
282
}