DynamicProxyGenerator.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 22 23 24
<?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>.
 */

namespace Doctrine\ORM;

/**
25
 * The DynamicProxyGenerator is used to generate proxy objects for entities at runtime.
26 27
 *
 * @author Roman Borschel <roman@code-factory.org>
28
 * @since 2.0
29 30 31
 */
class DynamicProxyGenerator
{
32
	/** The namspace for the generated proxy classes. */
33
    private static $_ns = 'Doctrine\Generated\Proxies\\';
34
    private $_cacheDir;
35
    private $_em;
36 37 38 39 40 41 42 43 44
	
    /**
	 * Initializes a new instance of the <tt>DynamicProxyGenerator</tt> class that is
	 * connected to the given <tt>EntityManager</tt> and stores proxy class files in
	 * the given cache directory.
	 *
	 * @param EntityManager $em
	 * @param string $cacheDir
     */
45 46 47 48
    public function __construct(EntityManager $em, $cacheDir = null)
    {
        $this->_em = $em;
        if ($cacheDir === null) {
49
            $cacheDir = sys_get_temp_dir();
50 51 52 53 54
        }
        $this->_cacheDir = $cacheDir;
    }

    /**
55
     * Gets a reference proxy instance.
56
     *
57 58 59
     * @param string $className
     * @param mixed $identifier
     * @return object
60
     */
61
    public function getReferenceProxy($className, $identifier)
62
    {
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
        $class = $this->_em->getClassMetadata($className);
        $proxyClassName = str_replace('\\', '_', $className) . 'RProxy';
        if ( ! class_exists($proxyClassName, false)) {
            $this->_em->getMetadataFactory()->setMetadataFor(self::$_ns . $proxyClassName, $class);
            $fileName = $this->_cacheDir . $proxyClassName . '.g.php';
            if ( ! file_exists($fileName)) {
                $this->_generateReferenceProxyClass($className, $identifier, $proxyClassName, $fileName);
            }
            require $fileName;
        }
        $proxyClassName = '\\' . self::$_ns . $proxyClassName;
        return new $proxyClassName($this->_em, $class, $identifier);
    }

    /**
     * Gets an association proxy instance.
     */
    public function getAssociationProxy($owner, \Doctrine\ORM\Mapping\AssociationMapping $assoc)
    {
        $proxyClassName = str_replace('\\', '_', $assoc->getTargetEntityName()) . 'AProxy';
83
        if ( ! class_exists($proxyClassName, false)) {
84
            $this->_em->getMetadataFactory()->setMetadataFor(self::$_ns . $proxyClassName, $this->_em->getClassMetadata($assoc->getTargetEntityName()));
85 86
            $fileName = $this->_cacheDir . $proxyClassName . '.g.php';
            if ( ! file_exists($fileName)) {
87
                $this->_generateAssociationProxyClass($assoc->getTargetEntityName(), $proxyClassName, $fileName);
88 89 90
            }
            require $fileName;
        }
91 92
        $proxyClassName = '\\' . self::$_ns . $proxyClassName;
        return new $proxyClassName($this->_em, $assoc, $owner);
93 94 95 96 97
    }

    /**
     * Generates a proxy class.
     *
98 99 100 101
     * @param string $className
     * @param mixed $id
     * @param string $proxyClassName
     * @param string $fileName
102
     */
103
    private function _generateReferenceProxyClass($className, $id, $proxyClassName, $fileName)
104 105 106 107
    {
        $class = $this->_em->getClassMetadata($className);
        $file = self::$_proxyClassTemplate;

108
        $methods = '';
109
        foreach ($class->reflClass->getMethods() as $method) {
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
            if ($method->isPublic() && ! $method->isFinal()) {
                $methods .= PHP_EOL . 'public function ' . $method->getName() . '(';
                $firstParam = true;
                $parameterString = '';
                foreach ($method->getParameters() as $param) {
                    if ($firstParam) {
                        $firstParam = false;
                    } else {
                        $parameterString .= ', ';
                    }
                    $parameterString .= '$' . $param->getName();
                }
                $methods .= $parameterString . ') {' . PHP_EOL;
                $methods .= '$this->_load();' . PHP_EOL;
                $methods .= 'return parent::' . $method->getName() . '(' . $parameterString . ');';
                $methods .= '}' . PHP_EOL;
126 127 128
            }
        }

129
        $sleepImpl = '';
130
        if ($class->reflClass->hasMethod('__sleep')) {
131 132 133 134 135 136 137 138 139 140 141
            $sleepImpl .= 'return parent::__sleep();';
        } else {
            $sleepImpl .= 'return array(';
            $first = true;
            foreach ($class->getReflectionProperties() as $name => $prop) {
                if ($first) {
                    $first = false;
                } else {
                    $sleepImpl .= ', ';
                }
                $sleepImpl .= "'" . $name . "'";
142
            }
143
            $sleepImpl .= ');';
144 145
        }

146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
        $placeholders = array(
            '<proxyClassName>', '<className>',
            '<methods>', '<sleepImpl>'
        );
        $replacements = array(
            $proxyClassName, $className, $methods, $sleepImpl
        );
        
        $file = str_replace($placeholders, $replacements, $file);
        
        file_put_contents($fileName, $file);
    }

    /**
     * Generates a proxy class.
     *
     * @param string $className
     * @param mixed $id
     * @param string $proxyClassName
     * @param string $fileName
     */
    private function _generateAssociationProxyClass($className, $proxyClassName, $fileName)
    {
        $class = $this->_em->getClassMetadata($className);
        $file = self::$_assocProxyClassTemplate;

172
        $methods = '';
173
        foreach ($class->reflClass->getMethods() as $method) {
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
            if ($method->isPublic() && ! $method->isFinal()) {
                $methods .= PHP_EOL . 'public function ' . $method->getName() . '(';
                $firstParam = true;
                $parameterString = '';
                foreach ($method->getParameters() as $param) {
                    if ($firstParam) {
                        $firstParam = false;
                    } else {
                        $parameterString .= ', ';
                    }
                    $parameterString .= '$' . $param->getName();
                }
                $methods .= $parameterString . ') {' . PHP_EOL;
                $methods .= '$this->_load();' . PHP_EOL;
                $methods .= 'return parent::' . $method->getName() . '(' . $parameterString . ');';
                $methods .= '}' . PHP_EOL;
            }
        }

        $sleepImpl = '';
194
        if ($class->reflClass->hasMethod('__sleep')) {
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
            $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 .= ');';
        }

        $placeholders = array(
211 212
            '<proxyClassName>', '<className>',
            '<methods>', '<sleepImpl>'
213 214
        );
        $replacements = array(
215
            $proxyClassName, $className, $methods, $sleepImpl
216
        );
217

218
        $file = str_replace($placeholders, $replacements, $file);
219

220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
        file_put_contents($fileName, $file);
    }

    /** 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> {
        private $_em;
        private $_class;
        private $_loaded = false;
        public function __construct($em, $class, $identifier) {
            $this->_em = $em;
            $this->_class = $class;
            $this->_class->setIdentifierValues($this, $identifier);
        }
        private function _load() {
            if ( ! $this->_loaded) {
239
                $this->_em->getUnitOfWork()->getEntityPersister($this->_class->name)->load($this->_identifier, $this);
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
                unset($this->_em);
                unset($this->_class);
                $this->_loaded = true;
            }
        }

        <methods>

        public function __sleep() {
            if (!$this->_loaded) {
                throw new RuntimeException("Not fully loaded proxy can not be serialized.");
            }
            <sleepImpl>
        }
    }
}';
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290

    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;
        private $_loaded = false;
        public function __construct($em, $assoc, $owner) {
            $this->_em = $em;
            $this->_assoc = $assoc;
            $this->_owner = $owner;
        }
        private function _load() {
            if ( ! $this->_loaded) {
                $this->_assoc->load($this->_owner, $this, $this->_em);
                unset($this->_em);
                unset($this->_owner);
                unset($this->_assoc);
                $this->_loaded = true;
            }
        }

        <methods>

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