~ubuntu-branches/ubuntu/wily/php-doctrine-common/wily-proposed

« back to all changes in this revision

Viewing changes to lib/Doctrine/Common/Proxy/ProxyGenerator.php

  • Committer: Package Import Robot
  • Author(s): David Prévot
  • Date: 2014-06-15 11:26:00 UTC
  • mfrom: (2.1.1 experimental)
  • Revision ID: package-import@ubuntu.com-20140615112600-sg4mgpwq9sfg4mre
Tags: 2.4.2-2
* Upload to unstable
* No tests if DEB_BUILD_OPTIONS contains nocheck

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
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 MIT license. For more information, see
 
17
 * <http://www.doctrine-project.org>.
 
18
 */
 
19
 
 
20
namespace Doctrine\Common\Proxy;
 
21
 
 
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;
 
26
 
 
27
/**
 
28
 * This factory is used to generate proxy classes.
 
29
 * It builds proxies from given parameters, a template and class metadata.
 
30
 *
 
31
 * @author Marco Pivetta <ocramius@gmail.com>
 
32
 * @since  2.4
 
33
 */
 
34
class ProxyGenerator
 
35
{
 
36
    /**
 
37
     * Used to match very simple id methods that don't need
 
38
     * to be decorated since the identifier is known.
 
39
     */
 
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';
 
41
 
 
42
    /**
 
43
     * The namespace that contains all proxy classes.
 
44
     *
 
45
     * @var string
 
46
     */
 
47
    private $proxyNamespace;
 
48
 
 
49
    /**
 
50
     * The directory that contains all proxy classes.
 
51
     *
 
52
     * @var string
 
53
     */
 
54
    private $proxyDirectory;
 
55
 
 
56
    /**
 
57
     * Map of callables used to fill in placeholders set in the template.
 
58
     *
 
59
     * @var string[]|callable[]
 
60
     */
 
61
    protected $placeholders = array(
 
62
        'baseProxyInterface'   => 'Doctrine\Common\Proxy\Proxy',
 
63
        'additionalProperties' => '',
 
64
    );
 
65
 
 
66
    /**
 
67
     * Template used as a blueprint to generate proxies.
 
68
     *
 
69
     * @var string
 
70
     */
 
71
    protected $proxyClassTemplate = '<?php
 
72
 
 
73
namespace <namespace>;
 
74
 
 
75
/**
 
76
 * DO NOT EDIT THIS FILE - IT WAS CREATED BY DOCTRINE\'S PROXY GENERATOR
 
77
 */
 
78
class <proxyShortClassName> extends \<className> implements \<baseProxyInterface>
 
79
{
 
80
    /**
 
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.
 
84
     *
 
85
     * @see \Doctrine\Common\Persistence\Proxy::__setInitializer
 
86
     */
 
87
    public $__initializer__;
 
88
 
 
89
    /**
 
90
     * @var \Closure the callback responsible of loading properties that need to be copied in the cloned object
 
91
     *
 
92
     * @see \Doctrine\Common\Persistence\Proxy::__setCloner
 
93
     */
 
94
    public $__cloner__;
 
95
 
 
96
    /**
 
97
     * @var boolean flag indicating if this object was already initialized
 
98
     *
 
99
     * @see \Doctrine\Common\Persistence\Proxy::__isInitialized
 
100
     */
 
101
    public $__isInitialized__ = false;
 
102
 
 
103
    /**
 
104
     * @var array properties to be lazy loaded, with keys being the property
 
105
     *            names and values being their default values
 
106
     *
 
107
     * @see \Doctrine\Common\Persistence\Proxy::__getLazyProperties
 
108
     */
 
109
    public static $lazyPropertiesDefaults = array(<lazyPropertiesDefaults>);
 
110
 
 
111
<additionalProperties>
 
112
 
 
113
<constructorImpl>
 
114
 
 
115
<magicGet>
 
116
 
 
117
<magicSet>
 
118
 
 
119
<magicIsset>
 
120
 
 
121
<sleepImpl>
 
122
 
 
123
<wakeupImpl>
 
124
 
 
125
<cloneImpl>
 
126
 
 
127
    /**
 
128
     * Forces initialization of the proxy
 
129
     */
 
130
    public function __load()
 
131
    {
 
132
        $this->__initializer__ && $this->__initializer__->__invoke($this, \'__load\', array());
 
133
    }
 
134
 
 
135
    /**
 
136
     * {@inheritDoc}
 
137
     * @internal generated method: use only when explicitly handling proxy specific loading logic
 
138
     */
 
139
    public function __isInitialized()
 
140
    {
 
141
        return $this->__isInitialized__;
 
142
    }
 
143
 
 
144
    /**
 
145
     * {@inheritDoc}
 
146
     * @internal generated method: use only when explicitly handling proxy specific loading logic
 
147
     */
 
148
    public function __setInitialized($initialized)
 
149
    {
 
150
        $this->__isInitialized__ = $initialized;
 
151
    }
 
152
 
 
153
    /**
 
154
     * {@inheritDoc}
 
155
     * @internal generated method: use only when explicitly handling proxy specific loading logic
 
156
     */
 
157
    public function __setInitializer(\Closure $initializer = null)
 
158
    {
 
159
        $this->__initializer__ = $initializer;
 
160
    }
 
161
 
 
162
    /**
 
163
     * {@inheritDoc}
 
164
     * @internal generated method: use only when explicitly handling proxy specific loading logic
 
165
     */
 
166
    public function __getInitializer()
 
167
    {
 
168
        return $this->__initializer__;
 
169
    }
 
170
 
 
171
    /**
 
172
     * {@inheritDoc}
 
173
     * @internal generated method: use only when explicitly handling proxy specific loading logic
 
174
     */
 
175
    public function __setCloner(\Closure $cloner = null)
 
176
    {
 
177
        $this->__cloner__ = $cloner;
 
178
    }
 
179
 
 
180
    /**
 
181
     * {@inheritDoc}
 
182
     * @internal generated method: use only when explicitly handling proxy specific cloning logic
 
183
     */
 
184
    public function __getCloner()
 
185
    {
 
186
        return $this->__cloner__;
 
187
    }
 
188
 
 
189
    /**
 
190
     * {@inheritDoc}
 
191
     * @internal generated method: use only when explicitly handling proxy specific loading logic
 
192
     * @static
 
193
     */
 
194
    public function __getLazyProperties()
 
195
    {
 
196
        return self::$lazyPropertiesDefaults;
 
197
    }
 
198
 
 
199
    <methods>
 
200
}
 
201
';
 
202
 
 
203
    /**
 
204
     * Initializes a new instance of the <tt>ProxyFactory</tt> class that is
 
205
     * connected to the given <tt>EntityManager</tt>.
 
206
     *
 
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.
 
209
     *
 
210
     * @throws InvalidArgumentException
 
211
     */
 
212
    public function __construct($proxyDirectory, $proxyNamespace)
 
213
    {
 
214
        if ( ! $proxyDirectory) {
 
215
            throw InvalidArgumentException::proxyDirectoryRequired();
 
216
        }
 
217
 
 
218
        if ( ! $proxyNamespace) {
 
219
            throw InvalidArgumentException::proxyNamespaceRequired();
 
220
        }
 
221
 
 
222
        $this->proxyDirectory        = $proxyDirectory;
 
223
        $this->proxyNamespace        = $proxyNamespace;
 
224
    }
 
225
 
 
226
    /**
 
227
     * Sets a placeholder to be replaced in the template.
 
228
     *
 
229
     * @param string          $name
 
230
     * @param string|callable $placeholder
 
231
     *
 
232
     * @throws InvalidArgumentException
 
233
     */
 
234
    public function setPlaceholder($name, $placeholder)
 
235
    {
 
236
        if ( ! is_string($placeholder) && ! is_callable($placeholder)) {
 
237
            throw InvalidArgumentException::invalidPlaceholder($name);
 
238
        }
 
239
 
 
240
        $this->placeholders[$name] = $placeholder;
 
241
    }
 
242
 
 
243
    /**
 
244
     * Sets the base template used to create proxy classes.
 
245
     *
 
246
     * @param string $proxyClassTemplate
 
247
     */
 
248
    public function setProxyClassTemplate($proxyClassTemplate)
 
249
    {
 
250
        $this->proxyClassTemplate = (string) $proxyClassTemplate;
 
251
    }
 
252
 
 
253
    /**
 
254
     * Generates a proxy class file.
 
255
     *
 
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.
 
258
     *
 
259
     * @throws UnexpectedValueException
 
260
     */
 
261
    public function generateProxyClass(ClassMetadata $class, $fileName = false)
 
262
    {
 
263
        preg_match_all('(<([a-zA-Z]+)>)', $this->proxyClassTemplate, $placeholderMatches);
 
264
 
 
265
        $placeholderMatches = array_combine($placeholderMatches[0], $placeholderMatches[1]);
 
266
        $placeholders       = array();
 
267
 
 
268
        foreach ($placeholderMatches as $placeholder => $name) {
 
269
            $placeholders[$placeholder] = isset($this->placeholders[$name])
 
270
                ? $this->placeholders[$name]
 
271
                : array($this, 'generate' . $name);
 
272
        }
 
273
 
 
274
        foreach ($placeholders as & $placeholder) {
 
275
            if (is_callable($placeholder)) {
 
276
                $placeholder = call_user_func($placeholder, $class);
 
277
            }
 
278
        }
 
279
 
 
280
        $proxyCode = strtr($this->proxyClassTemplate, $placeholders);
 
281
 
 
282
        if ( ! $fileName) {
 
283
            $proxyClassName = $this->generateNamespace($class) . '\\' . $this->generateProxyShortClassName($class);
 
284
 
 
285
            if ( ! class_exists($proxyClassName)) {
 
286
                eval(substr($proxyCode, 5));
 
287
            }
 
288
 
 
289
            return;
 
290
        }
 
291
 
 
292
        $parentDirectory = dirname($fileName);
 
293
 
 
294
        if ( ! is_dir($parentDirectory) && (false === @mkdir($parentDirectory, 0775, true))) {
 
295
            throw UnexpectedValueException::proxyDirectoryNotWritable($this->proxyDirectory);
 
296
        }
 
297
 
 
298
        if ( ! is_writable($parentDirectory)) {
 
299
            throw UnexpectedValueException::proxyDirectoryNotWritable($this->proxyDirectory);
 
300
        }
 
301
 
 
302
        $tmpFileName = $fileName . '.' . uniqid('', true);
 
303
 
 
304
        file_put_contents($tmpFileName, $proxyCode);
 
305
        rename($tmpFileName, $fileName);
 
306
    }
 
307
 
 
308
    /**
 
309
     * Generates the proxy short class name to be used in the template.
 
310
     *
 
311
     * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class
 
312
     *
 
313
     * @return string
 
314
     */
 
315
    private function generateProxyShortClassName(ClassMetadata $class)
 
316
    {
 
317
        $proxyClassName = ClassUtils::generateProxyClassName($class->getName(), $this->proxyNamespace);
 
318
        $parts          = explode('\\', strrev($proxyClassName), 2);
 
319
 
 
320
        return strrev($parts[0]);
 
321
    }
 
322
 
 
323
    /**
 
324
     * Generates the proxy namespace.
 
325
     *
 
326
     * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class
 
327
     *
 
328
     * @return string
 
329
     */
 
330
    private function generateNamespace(ClassMetadata $class)
 
331
    {
 
332
        $proxyClassName = ClassUtils::generateProxyClassName($class->getName(), $this->proxyNamespace);
 
333
        $parts = explode('\\', strrev($proxyClassName), 2);
 
334
 
 
335
        return strrev($parts[1]);
 
336
    }
 
337
 
 
338
    /**
 
339
     * Generates the original class name.
 
340
     *
 
341
     * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class
 
342
     *
 
343
     * @return string
 
344
     */
 
345
    private function generateClassName(ClassMetadata $class)
 
346
    {
 
347
        return ltrim($class->getName(), '\\');
 
348
    }
 
349
 
 
350
    /**
 
351
     * Generates the array representation of lazy loaded public properties and their default values.
 
352
     *
 
353
     * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class
 
354
     *
 
355
     * @return string
 
356
     */
 
357
    private function generateLazyPropertiesDefaults(ClassMetadata $class)
 
358
    {
 
359
        $lazyPublicProperties = $this->getLazyLoadedPublicProperties($class);
 
360
        $values               = array();
 
361
 
 
362
        foreach ($lazyPublicProperties as $key => $value) {
 
363
            $values[] = var_export($key, true) . ' => ' . var_export($value, true);
 
364
        }
 
365
 
 
366
        return implode(', ', $values);
 
367
    }
 
368
 
 
369
    /**
 
370
     * Generates the constructor code (un-setting public lazy loaded properties, setting identifier field values).
 
371
     *
 
372
     * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class
 
373
     *
 
374
     * @return string
 
375
     */
 
376
    private function generateConstructorImpl(ClassMetadata $class)
 
377
    {
 
378
        $constructorImpl = <<<'EOT'
 
379
    /**
 
380
     * @param \Closure $initializer
 
381
     * @param \Closure $cloner
 
382
     */
 
383
    public function __construct($initializer = null, $cloner = null)
 
384
    {
 
385
 
 
386
EOT;
 
387
        $toUnset = array();
 
388
 
 
389
        foreach ($this->getLazyLoadedPublicProperties($class) as $lazyPublicProperty => $unused) {
 
390
            $toUnset[] = '$this->' . $lazyPublicProperty;
 
391
        }
 
392
 
 
393
        $constructorImpl .= (empty($toUnset) ? '' : '        unset(' . implode(', ', $toUnset) . ");\n")
 
394
            . <<<'EOT'
 
395
 
 
396
        $this->__initializer__ = $initializer;
 
397
        $this->__cloner__      = $cloner;
 
398
    }
 
399
EOT;
 
400
 
 
401
        return $constructorImpl;
 
402
    }
 
403
 
 
404
    /**
 
405
     * Generates the magic getter invoked when lazy loaded public properties are requested.
 
406
     *
 
407
     * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class
 
408
     *
 
409
     * @return string
 
410
     */
 
411
    private function generateMagicGet(ClassMetadata $class)
 
412
    {
 
413
        $lazyPublicProperties = array_keys($this->getLazyLoadedPublicProperties($class));
 
414
        $reflectionClass      = $class->getReflectionClass();
 
415
        $hasParentGet         = false;
 
416
        $returnReference      = '';
 
417
        $inheritDoc           = '';
 
418
 
 
419
        if ($reflectionClass->hasMethod('__get')) {
 
420
            $hasParentGet = true;
 
421
            $inheritDoc   = '{@inheritDoc}';
 
422
 
 
423
            if ($reflectionClass->getMethod('__get')->returnsReference()) {
 
424
                $returnReference = '& ';
 
425
            }
 
426
        }
 
427
 
 
428
        if (empty($lazyPublicProperties) && ! $hasParentGet) {
 
429
            return '';
 
430
        }
 
431
 
 
432
        $magicGet = <<<EOT
 
433
    /**
 
434
     * $inheritDoc
 
435
     * @param string \$name
 
436
     */
 
437
    public function {$returnReference}__get(\$name)
 
438
    {
 
439
 
 
440
EOT;
 
441
 
 
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));
 
446
 
 
447
            return $this->$name;
 
448
        }
 
449
 
 
450
 
 
451
EOT;
 
452
        }
 
453
 
 
454
        if ($hasParentGet) {
 
455
            $magicGet .= <<<'EOT'
 
456
        $this->__initializer__ && $this->__initializer__->__invoke($this, '__get', array($name));
 
457
 
 
458
        return parent::__get($name);
 
459
 
 
460
EOT;
 
461
        } else {
 
462
            $magicGet .= <<<'EOT'
 
463
        trigger_error(sprintf('Undefined property: %s::$%s', __CLASS__, $name), E_USER_NOTICE);
 
464
 
 
465
EOT;
 
466
        }
 
467
 
 
468
        $magicGet .= "    }";
 
469
 
 
470
        return $magicGet;
 
471
    }
 
472
 
 
473
    /**
 
474
     * Generates the magic setter (currently unused).
 
475
     *
 
476
     * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class
 
477
     *
 
478
     * @return string
 
479
     */
 
480
    private function generateMagicSet(ClassMetadata $class)
 
481
    {
 
482
        $lazyPublicProperties = $this->getLazyLoadedPublicProperties($class);
 
483
        $hasParentSet         = $class->getReflectionClass()->hasMethod('__set');
 
484
 
 
485
        if (empty($lazyPublicProperties) && ! $hasParentSet) {
 
486
            return '';
 
487
        }
 
488
 
 
489
        $inheritDoc = $hasParentSet ? '{@inheritDoc}' : '';
 
490
        $magicSet   = <<<EOT
 
491
    /**
 
492
     * $inheritDoc
 
493
     * @param string \$name
 
494
     * @param mixed  \$value
 
495
     */
 
496
    public function __set(\$name, \$value)
 
497
    {
 
498
 
 
499
EOT;
 
500
 
 
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));
 
505
 
 
506
            $this->$name = $value;
 
507
 
 
508
            return;
 
509
        }
 
510
 
 
511
 
 
512
EOT;
 
513
        }
 
514
 
 
515
        if ($hasParentSet) {
 
516
            $magicSet .= <<<'EOT'
 
517
        $this->__initializer__ && $this->__initializer__->__invoke($this, '__set', array($name, $value));
 
518
 
 
519
        return parent::__set($name, $value);
 
520
EOT;
 
521
        } else {
 
522
            $magicSet .= "        \$this->\$name = \$value;";
 
523
        }
 
524
 
 
525
        $magicSet .= "\n    }";
 
526
 
 
527
        return $magicSet;
 
528
    }
 
529
 
 
530
    /**
 
531
     * Generates the magic issetter invoked when lazy loaded public properties are checked against isset().
 
532
     *
 
533
     * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class
 
534
     *
 
535
     * @return string
 
536
     */
 
537
    private function generateMagicIsset(ClassMetadata $class)
 
538
    {
 
539
        $lazyPublicProperties = array_keys($this->getLazyLoadedPublicProperties($class));
 
540
        $hasParentIsset       = $class->getReflectionClass()->hasMethod('__isset');
 
541
 
 
542
        if (empty($lazyPublicProperties) && ! $hasParentIsset) {
 
543
            return '';
 
544
        }
 
545
 
 
546
        $inheritDoc = $hasParentIsset ? '{@inheritDoc}' : '';
 
547
        $magicIsset = <<<EOT
 
548
    /**
 
549
     * $inheritDoc
 
550
     * @param  string \$name
 
551
     * @return boolean
 
552
     */
 
553
    public function __isset(\$name)
 
554
    {
 
555
 
 
556
EOT;
 
557
 
 
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));
 
562
 
 
563
            return isset($this->$name);
 
564
        }
 
565
 
 
566
 
 
567
EOT;
 
568
        }
 
569
 
 
570
        if ($hasParentIsset) {
 
571
            $magicIsset .= <<<'EOT'
 
572
        $this->__initializer__ && $this->__initializer__->__invoke($this, '__isset', array($name));
 
573
 
 
574
        return parent::__isset($name);
 
575
 
 
576
EOT;
 
577
        } else {
 
578
            $magicIsset .= "        return false;";
 
579
        }
 
580
 
 
581
        return $magicIsset . "\n    }";
 
582
    }
 
583
 
 
584
    /**
 
585
     * Generates implementation for the `__sleep` method of proxies.
 
586
     *
 
587
     * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class
 
588
     *
 
589
     * @return string
 
590
     */
 
591
    private function generateSleepImpl(ClassMetadata $class)
 
592
    {
 
593
        $hasParentSleep = $class->getReflectionClass()->hasMethod('__sleep');
 
594
        $inheritDoc     = $hasParentSleep ? '{@inheritDoc}' : '';
 
595
        $sleepImpl      = <<<EOT
 
596
    /**
 
597
     * $inheritDoc
 
598
     * @return array
 
599
     */
 
600
    public function __sleep()
 
601
    {
 
602
 
 
603
EOT;
 
604
 
 
605
        if ($hasParentSleep) {
 
606
            return $sleepImpl . <<<'EOT'
 
607
        $properties = array_merge(array('__isInitialized__'), parent::__sleep());
 
608
 
 
609
        if ($this->__isInitialized__) {
 
610
            $properties = array_diff($properties, array_keys($this->__getLazyProperties()));
 
611
        }
 
612
 
 
613
        return $properties;
 
614
    }
 
615
EOT;
 
616
        }
 
617
 
 
618
        $allProperties = array('__isInitialized__');
 
619
 
 
620
        /* @var $prop \ReflectionProperty */
 
621
        foreach ($class->getReflectionClass()->getProperties() as $prop) {
 
622
            if ($prop->isStatic()) {
 
623
                continue;
 
624
            }
 
625
 
 
626
            $allProperties[] = $prop->isPrivate()
 
627
                ? "\0" . $prop->getDeclaringClass()->getName() . "\0" . $prop->getName()
 
628
                : $prop->getName();
 
629
        }
 
630
 
 
631
        $lazyPublicProperties = array_keys($this->getLazyLoadedPublicProperties($class));
 
632
        $protectedProperties  = array_diff($allProperties, $lazyPublicProperties);
 
633
 
 
634
        foreach ($allProperties as &$property) {
 
635
            $property = var_export($property, true);
 
636
        }
 
637
 
 
638
        foreach ($protectedProperties as &$property) {
 
639
            $property = var_export($property, true);
 
640
        }
 
641
 
 
642
        $allProperties       = implode(', ', $allProperties);
 
643
        $protectedProperties = implode(', ', $protectedProperties);
 
644
 
 
645
        return $sleepImpl . <<<EOT
 
646
        if (\$this->__isInitialized__) {
 
647
            return array($allProperties);
 
648
        }
 
649
 
 
650
        return array($protectedProperties);
 
651
    }
 
652
EOT;
 
653
    }
 
654
 
 
655
    /**
 
656
     * Generates implementation for the `__wakeup` method of proxies.
 
657
     *
 
658
     * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class
 
659
     *
 
660
     * @return string
 
661
     */
 
662
    private function generateWakeupImpl(ClassMetadata $class)
 
663
    {
 
664
        $unsetPublicProperties = array();
 
665
        $hasWakeup             = $class->getReflectionClass()->hasMethod('__wakeup');
 
666
 
 
667
        foreach (array_keys($this->getLazyLoadedPublicProperties($class)) as $lazyPublicProperty) {
 
668
            $unsetPublicProperties[] = '$this->' . $lazyPublicProperty;
 
669
        }
 
670
 
 
671
        $shortName  = $this->generateProxyShortClassName($class);
 
672
        $inheritDoc = $hasWakeup ? '{@inheritDoc}' : '';
 
673
        $wakeupImpl = <<<EOT
 
674
    /**
 
675
     * $inheritDoc
 
676
     */
 
677
    public function __wakeup()
 
678
    {
 
679
        if ( ! \$this->__isInitialized__) {
 
680
            \$this->__initializer__ = function ($shortName \$proxy) {
 
681
                \$proxy->__setInitializer(null);
 
682
                \$proxy->__setCloner(null);
 
683
 
 
684
                \$existingProperties = get_object_vars(\$proxy);
 
685
 
 
686
                foreach (\$proxy->__getLazyProperties() as \$property => \$defaultValue) {
 
687
                    if ( ! array_key_exists(\$property, \$existingProperties)) {
 
688
                        \$proxy->\$property = \$defaultValue;
 
689
                    }
 
690
                }
 
691
            };
 
692
 
 
693
EOT;
 
694
 
 
695
        if ( ! empty($unsetPublicProperties)) {
 
696
            $wakeupImpl .= "\n            unset(" . implode(', ', $unsetPublicProperties) . ");";
 
697
        }
 
698
 
 
699
        $wakeupImpl .= "\n        }";
 
700
 
 
701
        if ($hasWakeup) {
 
702
            $wakeupImpl .= "\n        parent::__wakeup();";
 
703
        }
 
704
 
 
705
        $wakeupImpl .= "\n    }";
 
706
 
 
707
        return $wakeupImpl;
 
708
    }
 
709
 
 
710
    /**
 
711
     * Generates implementation for the `__clone` method of proxies.
 
712
     *
 
713
     * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class
 
714
     *
 
715
     * @return string
 
716
     */
 
717
    private function generateCloneImpl(ClassMetadata $class)
 
718
    {
 
719
        $hasParentClone  = $class->getReflectionClass()->hasMethod('__clone');
 
720
        $inheritDoc      = $hasParentClone ? '{@inheritDoc}' : '';
 
721
        $callParentClone = $hasParentClone ? "\n        parent::__clone();\n" : '';
 
722
 
 
723
        return <<<EOT
 
724
    /**
 
725
     * $inheritDoc
 
726
     */
 
727
    public function __clone()
 
728
    {
 
729
        \$this->__cloner__ && \$this->__cloner__->__invoke(\$this, '__clone', array());
 
730
$callParentClone    }
 
731
EOT;
 
732
    }
 
733
 
 
734
    /**
 
735
     * Generates decorated methods by picking those available in the parent class.
 
736
     *
 
737
     * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class
 
738
     *
 
739
     * @return string
 
740
     */
 
741
    private function generateMethods(ClassMetadata $class)
 
742
    {
 
743
        $methods           = '';
 
744
        $methodNames       = array();
 
745
        $reflectionMethods = $class->getReflectionClass()->getMethods(\ReflectionMethod::IS_PUBLIC);
 
746
        $skippedMethods    = array(
 
747
            '__sleep'   => true,
 
748
            '__clone'   => true,
 
749
            '__wakeup'  => true,
 
750
            '__get'     => true,
 
751
            '__set'     => true,
 
752
            '__isset'   => true,
 
753
        );
 
754
 
 
755
        foreach ($reflectionMethods as $method) {
 
756
            $name = $method->getName();
 
757
 
 
758
            if (
 
759
                $method->isConstructor() ||
 
760
                isset($skippedMethods[strtolower($name)]) ||
 
761
                isset($methodNames[$name]) ||
 
762
                $method->isFinal() ||
 
763
                $method->isStatic() ||
 
764
                ( ! $method->isPublic())
 
765
            ) {
 
766
                continue;
 
767
            }
 
768
 
 
769
            $methodNames[$name] = true;
 
770
            $methods .= "\n    /**\n"
 
771
                . "     * {@inheritDoc}\n"
 
772
                . "     */\n"
 
773
                . '    public function ';
 
774
 
 
775
            if ($method->returnsReference()) {
 
776
                $methods .= '&';
 
777
            }
 
778
 
 
779
            $methods .= $name . '(';
 
780
 
 
781
            $firstParam      = true;
 
782
            $parameterString = '';
 
783
            $argumentString  = '';
 
784
            $parameters      = array();
 
785
 
 
786
            foreach ($method->getParameters() as $param) {
 
787
                if ($firstParam) {
 
788
                    $firstParam = false;
 
789
                } else {
 
790
                    $parameterString .= ', ';
 
791
                    $argumentString  .= ', ';
 
792
                }
 
793
 
 
794
                try {
 
795
                    $paramClass = $param->getClass();
 
796
                } catch (\ReflectionException $previous) {
 
797
                    throw UnexpectedValueException::invalidParameterTypeHint(
 
798
                        $class->getName(),
 
799
                        $method->getName(),
 
800
                        $param->getName(),
 
801
                        $previous
 
802
                    );
 
803
                }
 
804
 
 
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 ';
 
812
                }
 
813
 
 
814
                if ($param->isPassedByReference()) {
 
815
                    $parameterString .= '&';
 
816
                }
 
817
 
 
818
                $parameters[] = '$' . $param->getName();
 
819
                $parameterString .= '$' . $param->getName();
 
820
                $argumentString  .= '$' . $param->getName();
 
821
 
 
822
                if ($param->isDefaultValueAvailable()) {
 
823
                    $parameterString .= ' = ' . var_export($param->getDefaultValue(), true);
 
824
                }
 
825
            }
 
826
 
 
827
            $methods .= $parameterString . ')';
 
828
            $methods .= "\n" . '    {' . "\n";
 
829
 
 
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) ' : '';
 
834
 
 
835
                $methods .= '        if ($this->__isInitialized__ === false) {' . "\n";
 
836
                $methods .= '            return ' . $cast . ' parent::' . $method->getName() . "();\n";
 
837
                $methods .= '        }' . "\n\n";
 
838
            }
 
839
 
 
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";
 
845
        }
 
846
 
 
847
        return $methods;
 
848
    }
 
849
 
 
850
    /**
 
851
     * Generates the Proxy file name.
 
852
     *
 
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.
 
857
     *
 
858
     * @return string
 
859
     */
 
860
    public function getProxyFileName($className, $baseDirectory = null)
 
861
    {
 
862
        $baseDirectory = $baseDirectory ?: $this->proxyDirectory;
 
863
 
 
864
        return rtrim($baseDirectory, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . Proxy::MARKER
 
865
            . str_replace('\\', '', $className) . '.php';
 
866
    }
 
867
 
 
868
    /**
 
869
     * Checks if the method is a short identifier getter.
 
870
     *
 
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).
 
876
     *
 
877
     * @param \ReflectionMethod                                  $method
 
878
     * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class
 
879
     *
 
880
     * @return boolean
 
881
     */
 
882
    private function isShortIdentifierGetter($method, ClassMetadata $class)
 
883
    {
 
884
        $identifier = lcfirst(substr($method->getName(), 3));
 
885
        $startLine = $method->getStartLine();
 
886
        $endLine = $method->getEndLine();
 
887
        $cheapCheck = (
 
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)
 
893
        );
 
894
 
 
895
        if ($cheapCheck) {
 
896
            $code = file($method->getDeclaringClass()->getFileName());
 
897
            $code = trim(implode(' ', array_slice($code, $startLine - 1, $endLine - $startLine + 1)));
 
898
 
 
899
            $pattern = sprintf(self::PATTERN_MATCH_ID_METHOD, $method->getName(), $identifier);
 
900
 
 
901
            if (preg_match($pattern, $code)) {
 
902
                return true;
 
903
            }
 
904
        }
 
905
 
 
906
        return false;
 
907
    }
 
908
 
 
909
    /**
 
910
     * Generates the list of public properties to be lazy loaded, with their default values.
 
911
     *
 
912
     * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class
 
913
     *
 
914
     * @return mixed[]
 
915
     */
 
916
    private function getLazyLoadedPublicProperties(ClassMetadata $class)
 
917
    {
 
918
        $defaultProperties = $class->getReflectionClass()->getDefaultProperties();
 
919
        $properties = array();
 
920
 
 
921
        foreach ($class->getReflectionClass()->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) {
 
922
            $name = $property->getName();
 
923
 
 
924
            if (($class->hasField($name) || $class->hasAssociation($name)) && ! $class->isIdentifier($name)) {
 
925
                $properties[$name] = $defaultProperties[$name];
 
926
            }
 
927
        }
 
928
 
 
929
        return $properties;
 
930
    }
 
931
}
 
932