ProxyClassGenerator.php 9.64 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
use Doctrine\ORM\EntityManager,
    Doctrine\ORM\Mapping\ClassMetadata;
26 27

/**
28
 * The ProxyClassGenerator is used to generate proxy objects for entities at runtime.
29 30
 *
 * @author Roman Borschel <roman@code-factory.org>
31
 * @author Giorgio Sironi <piccoloprincipeazzurro@gmail.com>
32
 * @since 2.0
33
 */
34
class ProxyClassGenerator
35
{
36
	/** The namespace for the generated proxy classes. */
37
    private static $_ns = 'Doctrine\Generated\Proxies\\';
38
    private $_cacheDir;
39
    private $_em;
40

41
    /**
42
	 * Generates and stores proxy class files in the given cache directory.
43 44
	 *
	 * @param EntityManager $em
45 46
	 * @param string $cacheDir The directory where generated proxy classes will be saved.
	 *                         If not set, sys_get_temp_dir() is used.
47
     */
48 49 50
    public function __construct(EntityManager $em, $cacheDir = null)
    {
        $this->_em = $em;
51
        
52
        if ($cacheDir === null) {
53
            $cacheDir = sys_get_temp_dir();
54
        }
55
        
56
        $this->_cacheDir = rtrim($cacheDir, '/') . '/';
57 58 59
    }

    /**
60 61
     * Generates a reference proxy class.
     * This is a proxy for an object which we have the id for retrieval.
62
     *
63 64
     * @param string $originalClassName
     * @return string name of the proxy class
65
     */
66
    public function generateReferenceProxyClass($originalClassName)
67
    {
68
        $proxyClassName = str_replace('\\', '_', $originalClassName) . 'RProxy';
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87

        return $this->_generateClass($originalClassName, $proxyClassName, self::$_proxyClassTemplate);
    }

    /**
     * Generates an association proxy class.
     * This is a proxy class for an object which we have the association where
     * it is involved, but no primary key to retrieve it.
     *
     * @param string $originalClassName
     * @return string the proxy class name
     */
    public function generateAssociationProxyClass($originalClassName)
    {
        $proxyClassName = str_replace('\\', '_', $originalClassName) . 'AProxy';

        return $this->_generateClass($originalClassName, $proxyClassName, self::$_assocProxyClassTemplate);
    }

88
    private function _generateClass($originalClassName, $proxyClassName, $file)
89
    {
90
        $proxyFullyQualifiedClassName = self::$_ns . $proxyClassName;
91 92 93 94 95
        
        if ($this->_em->getMetadataFactory()->hasMetadataFor($proxyFullyQualifiedClassName)) {
            return $proxyFullyQualifiedClassName;
        }
        
96 97
        $class = $this->_em->getClassMetadata($originalClassName);
        $this->_em->getMetadataFactory()->setMetadataFor($proxyFullyQualifiedClassName, $class);
98
        
99 100 101 102 103
        if (class_exists($proxyFullyQualifiedClassName, false)) {
            return $proxyFullyQualifiedClassName;
        }

        $fileName = $this->_cacheDir . $proxyClassName . '.g.php';
104
            
105 106 107
        if (file_exists($fileName)) {
            require $fileName;
            return $proxyFullyQualifiedClassName;
108 109
        }

110 111
        $methods = $this->_generateMethods($class);
        $sleepImpl = $this->_generateSleep($class);
112
        $constructorInv = $class->reflClass->hasMethod('__construct') ? 'parent::__construct();' : '';
113 114 115

        $placeholders = array(
            '<proxyClassName>', '<className>',
116 117
            '<methods>', '<sleepImpl>',
            '<constructorInvocation>'
118 119
        );
        $replacements = array(
120 121 122
            $proxyClassName, $originalClassName,
            $methods, $sleepImpl,
            $constructorInv
123 124 125
        );
        
        $file = str_replace($placeholders, $replacements, $file);
romanb's avatar
romanb committed
126
        
127
        file_put_contents($fileName, $file);
128
        
129
        require $fileName;
130
        
131
        return $proxyFullyQualifiedClassName;
132 133
    }

134
    private function _generateMethods(ClassMetadata $class)
135
    {
136
        $methods = '';
137
        
138
        foreach ($class->reflClass->getMethods() as $method) {
139
            if ($method->isConstructor()) {
140 141
                continue;
            }
142
            
romanb's avatar
romanb committed
143
            if ($method->isPublic() && ! $method->isFinal() && ! $method->isStatic()) {
144 145
                $methods .= PHP_EOL . 'public function ' . $method->getName() . '(';
                $firstParam = true;
146 147
                $parameterString = $argumentString = '';
                
148 149 150 151 152
                foreach ($method->getParameters() as $param) {
                    if ($firstParam) {
                        $firstParam = false;
                    } else {
                        $parameterString .= ', ';
153 154 155 156 157 158
                        $argumentString  .= ', ';
                    }
                    
                    // We need to pick the type hint class too
                    if (($paramClass = $param->getClass()) !== null) {
                    	$parameterString .= '\\' . $paramClass->getName() . ' ';
romanb's avatar
romanb committed
159 160 161 162 163 164
                    } else if ($param->isArray()) {
                        $parameterString .= 'array ';
                    }
                    
                    if ($param->isPassedByReference()) {
                        $parameterString .= '&';
165
                    }
166
                    
167
                    $parameterString .= '$' . $param->getName();
168
                    $argumentString  .= '$' . $param->getName();
romanb's avatar
romanb committed
169 170 171 172
                    
                    if ($param->isDefaultValueAvailable()) {
                        $parameterString .= ' = ' . var_export($param->getDefaultValue(), true);
                    }
173
                }
174
                
175 176
                $methods .= $parameterString . ') {' . PHP_EOL;
                $methods .= '$this->_load();' . PHP_EOL;
177
                $methods .= 'return parent::' . $method->getName() . '(' . $argumentString . ');';
178
                $methods .= '}' . PHP_EOL;
179 180
            }
        }
181
        
182 183
        return $methods;
    }
184

185
    private function _generateSleep(ClassMetadata $class)
186
    {
187
        $sleepImpl = '';
188
        
189
        if ($class->reflClass->hasMethod('__sleep')) {
190 191 192 193
            $sleepImpl .= 'return parent::__sleep();';
        } else {
            $sleepImpl .= 'return array(';
            $first = true;
194
            
195 196 197 198 199 200
            foreach ($class->getReflectionProperties() as $name => $prop) {
                if ($first) {
                    $first = false;
                } else {
                    $sleepImpl .= ', ';
                }
201
                
202
                $sleepImpl .= "'" . $name . "'";
203
            }
204
            
205
            $sleepImpl .= ');';
206
        }
207
        
208
        return $sleepImpl;
209 210
    }

211 212 213 214 215 216 217

    /** Proxy class code template */
    private static $_proxyClassTemplate =
'<?php
/** This class was generated by the Doctrine ORM. DO NOT EDIT THIS FILE. */
namespace Doctrine\Generated\Proxies {
    class <proxyClassName> extends \<className> {
218 219
        private $_entityPersister;
        private $_identifier;
220
        private $_loaded = false;
221 222 223
        public function __construct($entityPersister, $identifier) {
            $this->_entityPersister = $entityPersister;
            $this->_identifier = $identifier;
224
            <constructorInvocation>
225 226 227
        }
        private function _load() {
            if ( ! $this->_loaded) {
228 229 230
                $this->_entityPersister->load($this->_identifier, $this);
                unset($this->_entityPersister);
                unset($this->_identifier);
231 232 233 234 235 236 237 238
                $this->_loaded = true;
            }
        }

        <methods>

        public function __sleep() {
            if (!$this->_loaded) {
239
                throw new \RuntimeException("Not fully loaded proxy can not be serialized.");
240 241 242 243 244
            }
            <sleepImpl>
        }
    }
}';
245 246 247 248 249 250 251 252 253

    private static $_assocProxyClassTemplate =
'<?php
/** This class was generated by the Doctrine ORM. DO NOT EDIT THIS FILE. */
namespace Doctrine\Generated\Proxies {
    class <proxyClassName> extends \<className> {
        private $_em;
        private $_assoc;
        private $_owner;
254
        private $_joinColumnValues;
255
        private $_loaded = false;
256
        public function __construct($em, $assoc, $owner, array $joinColumnValues) {
257 258 259
            $this->_em = $em;
            $this->_assoc = $assoc;
            $this->_owner = $owner;
260
            $this->_joinColumnValues = $joinColumnValues;
261
            <constructorInvocation>
262 263 264
        }
        private function _load() {
            if ( ! $this->_loaded) {
265
                $this->_assoc->load($this->_owner, $this, $this->_em, $this->_joinColumnValues);
266 267 268
                unset($this->_em);
                unset($this->_owner);
                unset($this->_assoc);
269
                unset($this->_joinColumnValues);
270 271 272 273 274 275 276 277
                $this->_loaded = true;
            }
        }

        <methods>

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