-
-
Notifications
You must be signed in to change notification settings - Fork 99
/
Copy pathUnitOfWork.php
3919 lines (3435 loc) · 151 KB
/
UnitOfWork.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
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
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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*
* 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 MIT license. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\ODM\PHPCR;
use Doctrine\Common\EventArgs;
use Doctrine\Common\Persistence\Event\OnClearEventArgs;
use Doctrine\Common\Persistence\Event\LifecycleEventArgs;
use Doctrine\Common\Persistence\Event\ManagerEventArgs;
use Doctrine\Common\Proxy\Proxy;
use Doctrine\Common\Collections\Collection;
use Doctrine\Common\Util\ClassUtils;
use Doctrine\ODM\PHPCR\Event\ListenersInvoker;
use Doctrine\ODM\PHPCR\Event\PreUpdateEventArgs;
use Doctrine\ODM\PHPCR\Event\MoveEventArgs;
use Doctrine\ODM\PHPCR\Exception\ClassMismatchException;
use Doctrine\ODM\PHPCR\Exception\InvalidArgumentException;
use Doctrine\ODM\PHPCR\Exception\RuntimeException;
use Doctrine\ODM\PHPCR\Id\AssignedIdGenerator;
use Doctrine\ODM\PHPCR\Id\IdException;
use Doctrine\ODM\PHPCR\Mapping\ClassMetadata;
use Doctrine\ODM\PHPCR\Mapping\MappingException;
use Doctrine\ODM\PHPCR\Id\IdGenerator;
use Doctrine\ODM\PHPCR\Exception\CascadeException;
use Doctrine\ODM\PHPCR\Tools\Helper\PrefetchHelper;
use Doctrine\ODM\PHPCR\Translation\MissingTranslationException;
use Doctrine\ODM\PHPCR\Translation\TranslationStrategy\TranslationNodesWarmer;
use Iterator;
use PHPCR\RepositoryInterface;
use PHPCR\PropertyType;
use PHPCR\NodeInterface;
use PHPCR\RepositoryException;
use PHPCR\UnsupportedRepositoryOperationException;
use PHPCR\PathNotFoundException;
use PHPCR\ItemNotFoundException;
use PHPCR\NodeType\NoSuchNodeTypeException;
use PHPCR\Util\UUIDHelper;
use PHPCR\Util\PathHelper;
use PHPCR\Util\NodeHelper;
use Jackalope\Session as JackalopeSession;
/**
* Unit of work class
*
* @license http://www.opensource.org/licenses/MIT-license.php MIT license
* @link www.doctrine-project.com
* @since 1.0
* @author Jordi Boggiano <[email protected]>
* @author Pascal Helfenstein <[email protected]>
* @author Lukas Kahwe Smith <[email protected]>
* @author Brian King <[email protected]>
* @author David Buchmann <[email protected]>
* @author Daniel Barsotti <[email protected]>
* @author Maximilian Berghoff <[email protected]>
*/
class UnitOfWork
{
const STATE_NEW = 1;
const STATE_MANAGED = 2;
const STATE_REMOVED = 3;
const STATE_DETACHED = 4;
/**
* @var DocumentManager
*/
private $dm = null;
/**
* @var array
*/
private $identityMap = array();
/**
* @var array
*/
private $documentIds = array();
/**
* Track version history of the version documents we create, indexed by spl_object_hash
* @var \PHPCR\Version\VersionHistoryInterface[]
*/
private $documentHistory = array();
/**
* Track version objects of the version documents we create, indexed by spl_object_hash
* @var \PHPCR\Version\VersionInterface[]
*/
private $documentVersion = array();
/**
* @var array
*/
private $documentState = array();
/**
* Hashmap of spl_object_hash => locale => hashmap of all translated
* document fields to store fields until the flush, in case the user is
* using bindTranslation to store more than one locale in one flush.
*
* @var array
*/
private $documentTranslations = array();
/**
* Hashmap of spl_object_hash => { original => locale , current => locale }
* The original vs current locale is used to detect if the user changed the
* mapped locale field of a document after the last call to bindTranslation
*
* @var array
*/
private $documentLocales = array();
/**
* PHPCR always returns and updates the whole data of a document. If on update data is "missing"
* this means the data is deleted. This also applies to attachments. This is why we need to ensure
* that data that is not mapped is not lost. This map here saves all the "left-over" data and keeps
* track of it if necessary.
*
* @var array
*/
private $nonMappedData = array();
/**
* @var array
*/
private $originalData = array();
/**
* @var array
*/
private $originalTranslatedData = array();
/**
* @var array
*/
private $documentChangesets = array();
/**
* List of documents that have a changed field to be updated on next flush
* oid => document
* @var array
*/
private $scheduledUpdates = array();
/**
* List of documents that will be inserted on next flush
* oid => document
* @var array
*/
private $scheduledInserts = array();
/**
* List of documents that will be moved on next flush
* oid => array(document, target path)
* @var array
*/
private $scheduledMoves = array();
/**
* List of parent documents that have children that will be reordered on next flush
* parent oid => list of array with records array(parent document, srcName, targetName, before) with
* - parent document the document of the child to be reordered
* - srcName the Nodename of the document to be moved,
* - targetName the Nodename of the document to move srcName to
* - before a boolean telling whether to move srcName before or after targetName
*
* @var array
*/
private $scheduledReorders = array();
/**
* List of documents that will be removed on next flush
* oid => document
* @var array
*/
private $scheduledRemovals = array();
/**
* @var array
*/
private $visitedCollections = array();
/**
* @var array
*/
private $changesetComputed = array();
/**
* @var IdGenerator
*/
private $idGenerators = array();
/**
* Used to generate uuid when we need to build references before flushing.
*
* @var \Closure
*/
private $uuidGenerator;
/**
* \PHPCR\SessionInterface
*/
private $session;
/**
* @var Event\ListenersInvoker
*/
private $eventListenersInvoker;
/**
* @var \Doctrine\Common\EventManager
*/
private $eventManager;
/**
* @var DocumentClassMapperInterface
*/
private $documentClassMapper;
private $prefetchHelper;
/**
* @var boolean
*/
private $validateDocumentName;
/**
* @var boolean
*/
private $writeMetadata;
/**
* @var string
*/
private $useFetchDepth;
/**
* @param DocumentManager $dm
*/
public function __construct(DocumentManager $dm)
{
$this->dm = $dm;
$this->session = $dm->getPhpcrSession();
$this->eventListenersInvoker = new ListenersInvoker($dm);
$this->eventManager = $dm->getEventManager();
$config = $dm->getConfiguration();
$this->documentClassMapper = $config->getDocumentClassMapper();
$this->validateDocumentName = $config->getValidateDoctrineMetadata();
$this->writeMetadata = $config->getWriteDoctrineMetadata();
$this->uuidGenerator = $config->getUuidGenerator();
if ($this->session instanceof JackalopeSession) {
$this->useFetchDepth = 'jackalope.fetch_depth';
}
}
public function setPrefetchHelper($helper)
{
$this->prefetchHelper = $helper;
}
public function getPrefetchHelper()
{
if (!$this->prefetchHelper) {
$this->prefetchHelper = new PrefetchHelper();
}
return $this->prefetchHelper;
}
/**
* Validate if a document is of the specified class, if the global setting
* to validate is activated.
*
* @param object $document
* @param string|null $className The class name $document must be
* instanceof. Pass empty to not validate anything.
*
* @throws PHPCRException
*/
public function validateClassName($document, $className)
{
if (isset($className) && $this->validateDocumentName) {
$this->documentClassMapper->validateClassName($this->dm, $document, $className);
}
}
/**
* Get the existing document or proxy of the specified class and node data
* or create a new one if not existing.
*
* Supported hints are
* - refresh: reload the fields from the database if set
* - locale: use this locale instead of the one from the annotation or the default
* - fallback: whether to try other languages or throw a not found
* exception if the desired locale is not found. defaults to true if
* not set and locale is not given either.
* - prefetch: if set to false, do not attempt to prefetch related data.
* (This makes sense when the caller already did this beforehand.)
*
* @param null|string $className
* @param NodeInterface $node
* @param array $hints
*
* @return object
*
* @throws PHPCRExceptionInterface if $className was specified and does not match
* the class of the document corresponding to $node.
*/
public function getOrCreateDocument($className, NodeInterface $node, array &$hints = array())
{
$documents = $this->getOrCreateDocuments($className, array($node), $hints);
return array_shift($documents);
}
/**
* Get the existing document or proxy of the specified class and node data
* or create a new one if not existing.
*
* Supported hints are
* - refresh: reload the fields from the database if set
* - locale: use this locale instead of the one from the annotation or the default
* - fallback: whether to try other languages or throw a not found
* exception if the desired locale is not found. defaults to true if
* not set and locale is not given either.
* - prefetch: if set to false, do not attempt to prefetch related data.
* (This makes sense when the caller already did this beforehand.)
*
* @param null|string $className
* @param Iterator|array $nodes
* @param array $hints
*
* @throws Exception\InvalidArgumentException
* @throws PHPCRException
* @return array
*/
public function getOrCreateDocuments($className, $nodes, array &$hints = array())
{
$refresh = isset($hints['refresh']) ? $hints['refresh'] : false;
$locale = isset($hints['locale']) ? $hints['locale'] : null;
$fallback = isset($hints['fallback']) ? $hints['fallback'] : isset($locale);
$documents = array();
$overrideLocalValuesOids = array();
$strategies = array();
$nodesByStrategy = array();
$allLocales = array();
//prepare array of document ordered by the nodes path
$existingDocuments = 0;
foreach ($nodes as $node) {
$requestedClassName = $className;
try {
$actualClassName = $this->documentClassMapper->getClassName($this->dm, $node, $className);
} catch (ClassMismatchException $e) {
// ignore class mismatch, just skip that one
continue;
}
$id = $node->getPath();
$class = $this->dm->getClassMetadata($actualClassName);
// prepare first, add later when fine
$document = $this->getDocumentById($id);
if ($document) {
if (!$refresh) {
++$existingDocuments;
$documents[$id] = $document;
} else {
$overrideLocalValuesOids[$id] = spl_object_hash($document);
}
try {
$this->validateClassName($document, $requestedClassName);
} catch(ClassMismatchException $e) {
continue;
}
} else {
$document = $class->newInstance();
// delay registering the new document until children proxy have been created
$overrideLocalValuesOids[$id] = false;
}
$documents[$id] = $document;
if ($this->isDocumentTranslatable($class)) {
$currentStrategy = $this->dm->getTranslationStrategy($class->translator);
$localesToTry = $this->dm->getLocaleChooserStrategy()->getFallbackLocales(
$document,
$class,
$locale
);
foreach ($localesToTry as $localeToTry) {
$allLocales[$localeToTry] = $localeToTry;
}
$strategies[$class->name] = $currentStrategy;
$nodesByStrategy[$class->name][] = $node;
}
}
foreach ($nodesByStrategy as $strategyClass => $nodesForLocale) {
if (!$strategies[$strategyClass] instanceof TranslationNodesWarmer) {
continue;
}
$strategies[$strategyClass]->getTranslationsForNodes($nodesForLocale, $allLocales, $this->session);
}
// return early
if (count($documents) === $existingDocuments) {
return $documents;
}
foreach ($nodes as $node) {
$id = $node->getPath();
$document = $this->getDocumentById($id) ?: (isset($documents[$id]) ? $documents[$id] : null);
if (! $document) {
continue;
}
$documents[$id] = $document;
$class = $this->dm->getClassMetadata(get_class($document));
$documentState = array();
$nonMappedData = array();
// second param is false to get uuid rather than dereference reference properties to node instances
$properties = $node->getPropertiesValues(null, false);
foreach ($class->fieldMappings as $fieldName) {
$mapping = $class->mappings[$fieldName];
if (isset($properties[$mapping['property']])) {
if (true === $mapping['multivalue']) {
if (isset($mapping['assoc'])) {
$documentState[$fieldName] = $this->createAssoc($properties, $mapping);
} else {
$documentState[$fieldName] = (array) $properties[$mapping['property']];
}
} else {
$documentState[$fieldName] = $properties[$mapping['property']];
}
} elseif (true === $mapping['multivalue']) {
$documentState[$mapping['property']] = array();
}
}
if ($class->node) {
$documentState[$class->node] = $node;
}
if ($class->nodename) {
$documentState[$class->nodename] = $node->getName();
}
if ($class->identifier) {
$documentState[$class->identifier] = $node->getPath();
}
if (! isset($hints['prefetch']) || $hints['prefetch']) {
$this->getPrefetchHelper()->prefetchReferences($class, $node);
}
// initialize inverse side collections
foreach ($class->referenceMappings as $fieldName) {
$mapping = $class->mappings[$fieldName];
if ($mapping['type'] === ClassMetadata::MANY_TO_ONE) {
if (!$node->hasProperty($mapping['property'])) {
continue;
}
try {
$referencedNode = $node->getProperty($mapping['property'])->getNode();
$proxy = $this->getOrCreateProxyFromNode($referencedNode, $locale);
if (isset($mapping['targetDocument']) && !$proxy instanceof $mapping['targetDocument']) {
throw new PHPCRException("Unexpected class for referenced document at '{$referencedNode->getPath()}'. Expected '{$mapping['targetDocument']}' but got '".ClassUtils::getClass($proxy)."'.");
}
} catch (RepositoryException $e) {
if ($e instanceof ItemNotFoundException || isset($hints['ignoreHardReferenceNotFound'])) {
// a weak reference or an old version can have lost references
$proxy = null;
} else {
throw new PHPCRException($e->getMessage(), 0, $e);
}
}
$documentState[$fieldName] = $proxy;
} elseif ($mapping['type'] === ClassMetadata::MANY_TO_MANY) {
$referencedNodes = array();
if ($node->hasProperty($mapping['property'])) {
foreach ($node->getProperty($mapping['property'])->getString() as $reference) {
$referencedNodes[] = $reference;
}
}
$targetDocument = isset($mapping['targetDocument']) ? $mapping['targetDocument'] : null;
$coll = new ReferenceManyCollection($this->dm, $document, $mapping['property'], $referencedNodes, $targetDocument, $locale);
$documentState[$fieldName] = $coll;
}
}
if (! isset($hints['prefetch']) || $hints['prefetch']) {
if ($class->translator) {
try {
$prefetchLocale = $locale ?: $this->dm->getLocaleChooserStrategy()->getLocale();
} catch (InvalidArgumentException $e) {
throw new InvalidArgumentException($e->getMessage() . ' but document ' . $class->name . ' is mapped with translations.');
}
} else {
$prefetchLocale = null;
}
$this->getPrefetchHelper()->prefetchHierarchy($class, $node, $prefetchLocale);
}
if ($class->parentMapping && $node->getDepth() > 0) {
// do not map parent to self if we are at root
$documentState[$class->parentMapping] = $this->getOrCreateProxyFromNode($node->getParent(), $locale);
}
foreach ($class->childMappings as $fieldName) {
$mapping = $class->mappings[$fieldName];
$documentState[$fieldName] = $node->hasNode($mapping['nodeName'])
? $this->getOrCreateProxyFromNode($node->getNode($mapping['nodeName']), $locale)
: null;
}
foreach ($class->childrenMappings as $fieldName) {
$mapping = $class->mappings[$fieldName];
$documentState[$fieldName] = new ChildrenCollection($this->dm, $document, $mapping['filter'], $mapping['fetchDepth'], $locale);
}
foreach ($class->referrersMappings as $fieldName) {
$mapping = $class->mappings[$fieldName];
// get the reference type strategy (weak or hard) on the fly, as we
// can not do it in ClassMetadata
$referringMeta = $this->dm->getClassMetadata($mapping['referringDocument']);
$referringField = $referringMeta->mappings[$mapping['referencedBy']];
$documentState[$fieldName] = new ReferrersCollection(
$this->dm,
$document,
$referringField['strategy'],
$referringField['property'],
$locale,
$mapping['referringDocument']
);
}
foreach ($class->mixedReferrersMappings as $fieldName) {
$mapping = $class->mappings[$fieldName];
$documentState[$fieldName] = new ImmutableReferrersCollection(
$this->dm,
$document,
$mapping['referenceType'],
$locale
);
}
// when not set then not needed
if (!isset($overrideLocalValuesOids[$id])) {
continue;
}
if (!$overrideLocalValuesOids[$id]) {
// registering the document needs to be delayed until the children proxies where created
$overrideLocalValuesOids[$id] = $this->registerDocument($document, $id);
}
$this->nonMappedData[$overrideLocalValuesOids[$id]] = $nonMappedData;
foreach ($class->reflFields as $fieldName => $reflFields) {
$value = isset($documentState[$fieldName]) ? $documentState[$fieldName] : null;
$reflFields->setValue($document, $value);
$this->originalData[$overrideLocalValuesOids[$id]][$fieldName] = $value;
}
// Load translations
$this->doLoadTranslation($document, $class, $locale, $fallback, $refresh);
if ($invoke = $this->eventListenersInvoker->getSubscribedSystems($class, Event::postLoad)) {
$this->eventListenersInvoker->invoke(
$class,
Event::postLoad,
$document,
new LifecycleEventArgs($document, $this->dm),
$invoke
);
}
}
return $documents;
}
/**
* Get the existing document or proxy or create a new one for this PHPCR Node
*
* @param NodeInterface $node
* @param string $locale
*
* @return object
*/
public function getOrCreateProxyFromNode(NodeInterface $node, $locale = null)
{
$targetId = $node->getPath();
$className = $this->documentClassMapper->getClassName($this->dm, $node);
return $this->getOrCreateProxy($targetId, $className, $locale);
}
/**
* Get the existing document or proxy for this id of this class, or create
* a new one.
*
* @param string $targetId
* @param string $className
* @param string $locale
*
* @return object
*/
public function getOrCreateProxy($targetId, $className, $locale = null)
{
$document = $this->getDocumentById($targetId);
// check if referenced document already exists
if ($document) {
$metadata = $this->dm->getClassMetadata($className);
if ($locale && $locale !== $this->getCurrentLocale($document, $metadata)) {
$this->doLoadTranslation($document, $metadata, $locale, true);
}
return $document;
}
$metadata = $this->dm->getClassMetadata($className);
$proxyDocument = $this->dm->getProxyFactory()->getProxy($className, array($metadata->identifier => $targetId));
// register the document under its own id
$this->registerDocument($proxyDocument, $targetId);
if ($locale) {
$this->setLocale($proxyDocument, $this->dm->getClassMetadata($className), $locale);
}
return $proxyDocument;
}
/**
* Populate the proxy with actual data
*
* @param string $className
* @param Proxy $document
*/
public function refreshDocumentForProxy($className, Proxy $document)
{
$node = $this->session->getNode($this->determineDocumentId($document));
$hints = array('refresh' => true, 'fallback' => true);
$oid = spl_object_hash($document);
if (isset($this->documentLocales[$oid]['current'])) {
$hints['locale'] = $this->documentLocales[$oid]['current'];
}
$this->getOrCreateDocument($className, $node, $hints);
}
/**
* Bind the translatable fields of the document in the specified locale.
*
* This method will update the field mapped to Locale if it does not match the $locale argument.
*
* @param object $document the document to persist a translation of
* @param string $locale the locale this document currently has
*
* @throws PHPCRException if the document is not translatable
*/
public function bindTranslation($document, $locale)
{
$state = $this->getDocumentState($document);
if ($state !== self::STATE_MANAGED) {
throw new InvalidArgumentException('Document has to be managed to be able to bind a translation '.self::objToStr($document, $this->dm));
}
$class = $this->dm->getClassMetadata(get_class($document));
if (!$this->isDocumentTranslatable($class)) {
throw new PHPCRException('This document is not translatable, do not use bindTranslation: '.self::objToStr($document, $this->dm));
}
if ($this->getCurrentLocale($document) != $locale
&& false !== array_search($locale, $this->getLocalesFor($document))
) {
throw new RuntimeException(sprintf(
'Translation "%s" already exists for "%s". First load this translation if you want to change it, or remove the existing translation.',
$locale,
self::objToStr($document, $this->dm)
));
}
$this->doBindTranslation($document, $locale, $class);
}
/**
* @param object $document
* @param string $locale
* @param ClassMetadata $class
*/
private function doBindTranslation($document, $locale, ClassMetadata $class)
{
$oid = spl_object_hash($document);
// only trigger the events if we bind a new translation
if (empty($this->documentTranslations[$oid][$locale])
&& $invoke = $this->eventListenersInvoker->getSubscribedSystems($class, Event::preCreateTranslation)
) {
$this->eventListenersInvoker->invoke(
$class,
Event::preCreateTranslation,
$document,
new LifecycleEventArgs($document, $this->dm),
$invoke
);
}
$this->setLocale($document, $class, $locale);
foreach ($class->translatableFields as $field) {
$this->documentTranslations[$oid][$locale][$field] = $class->reflFields[$field]->getValue($document);
}
}
/**
* Schedule insertion of this document and cascade if necessary.
*
* @param object $document
*/
public function scheduleInsert($document)
{
$visited = array();
$this->doScheduleInsert($document, $visited);
}
private function doScheduleInsert($document, &$visited, $overrideIdGenerator = null)
{
if (!is_object($document)) {
throw new PHPCRException(sprintf(
'Expected a mapped object, found <%s>',
gettype($document)
));
}
$oid = spl_object_hash($document);
// To avoid recursion loops (over children and parents)
if (isset($visited[$oid])) {
return;
}
$visited[$oid] = true;
$class = $this->dm->getClassMetadata(get_class($document));
if ($class->isMappedSuperclass) {
throw new InvalidArgumentException('Cannot persist a mapped super class instance: '.$class->name);
}
$this->cascadeScheduleParentInsert($class, $document, $visited);
$state = $this->getDocumentState($document);
switch ($state) {
case self::STATE_NEW:
$this->persistNew($class, $document, $overrideIdGenerator);
break;
case self::STATE_MANAGED:
// TODO: Change Tracking Deferred Explicit
break;
case self::STATE_REMOVED:
unset($this->scheduledRemovals[$oid]);
$this->setDocumentState($oid, self::STATE_MANAGED);
break;
case self::STATE_DETACHED:
throw new InvalidArgumentException('Detached document or new document with already existing id passed to persist(): '.self::objToStr($document, $this->dm));
}
$this->cascadeScheduleInsert($class, $document, $visited);
}
/**
*
* @param ClassMetadata $class
* @param object $document
* @param array $visited
*/
private function cascadeScheduleInsert($class, $document, &$visited)
{
foreach (array_merge($class->referenceMappings, $class->referrersMappings) as $fieldName) {
$mapping = $class->mappings[$fieldName];
if (!($mapping['cascade'] & ClassMetadata::CASCADE_PERSIST)) {
continue;
}
$related = $class->reflFields[$fieldName]->getValue($document);
if ($related !== null) {
if (ClassMetadata::MANY_TO_ONE === $mapping['type']) {
if (is_array($related) || $related instanceof Collection) {
throw new PHPCRException(sprintf(
'Referenced document is not stored correctly in a reference-one property. Do not use array notation or a (ReferenceMany)Collection in field "%s" of document "%s"',
$fieldName,
self::objToStr($document, $this->dm)
));
}
if (!is_object($related)) {
throw new PHPCRException(sprintf(
'A reference field may only contain mapped documents, found <%s> in field "%s" of "%s"',
gettype($related),
$fieldName,
self::objToStr($document, $this->dm)
));
}
if ($this->getDocumentState($related) === self::STATE_NEW) {
$this->doScheduleInsert($related, $visited);
}
} else {
if (!is_array($related) && !$related instanceof Collection) {
throw new PHPCRException('Referenced documents are not stored correctly in a reference-many property. Use array notation or a (ReferenceMany)Collection: '.self::objToStr($document, $this->dm));
}
foreach ($related as $relatedDocument) {
if (!isset($relatedDocument)) {
continue;
}
if (!is_object($relatedDocument)) {
throw new PHPCRException(sprintf(
'A reference field may only contain mapped documents, found <%s> in field "%s" of "%s"',
gettype($relatedDocument),
$fieldName,
self::objToStr($document, $this->dm)
));
}
if ($this->getDocumentState($relatedDocument) === self::STATE_NEW) {
$this->doScheduleInsert($relatedDocument, $visited);
}
}
}
}
}
}
private function cascadeScheduleParentInsert($class, $document, &$visited)
{
if ($class->parentMapping) {
$parent = $class->reflFields[$class->parentMapping]->getValue($document);
if ($parent !== null && $this->getDocumentState($parent) === self::STATE_NEW) {
if (!is_object($parent)) {
throw new PHPCRException(sprintf(
'A parent field may only contain mapped documents, found <%s> in field "%s" of "%s"',
gettype($parent),
$class->parentMapping,
self::objToStr($document, $this->dm)
));
}
$this->doScheduleInsert($parent, $visited);
}
}
}
/**
* @param string $type the id generator type
*
* @return IdGenerator
*/
private function getIdGenerator($type)
{
if (!isset($this->idGenerators[$type])) {
$this->idGenerators[$type] = IdGenerator::create($type, $config);
}
return $this->idGenerators[$type];
}
public function scheduleMove($document, $targetPath)
{
$oid = spl_object_hash($document);
$state = $this->getDocumentState($document);
switch ($state) {
case self::STATE_NEW:
unset($this->scheduledInserts[$oid]);
break;
case self::STATE_REMOVED:
unset($this->scheduledRemovals[$oid]);
break;
case self::STATE_DETACHED:
throw new InvalidArgumentException('Detached document passed to move(): '.self::objToStr($document, $this->dm));
}
$this->scheduledMoves[$oid] = array($document, $targetPath);
$this->setDocumentState($oid, self::STATE_MANAGED);
}
public function scheduleReorder($document, $srcName, $targetName, $before)
{
$oid = spl_object_hash($document);
$state = $this->getDocumentState($document);
switch ($state) {
case self::STATE_REMOVED:
throw new InvalidArgumentException('Removed document passed to reorder(): '.self::objToStr($document, $this->dm));
case self::STATE_DETACHED:
throw new InvalidArgumentException('Detached document passed to reorder(): '.self::objToStr($document, $this->dm));
}
if (! isset($this->scheduledReorders[$oid])) {
$this->scheduledReorders[$oid] = array();
}
$this->scheduledReorders[$oid][] = array($document, $srcName, $targetName, $before);
}
public function scheduleRemove($document)
{
$visited = array();
$this->doRemove($document, $visited);
}
private function doRemove($document, &$visited)
{
$oid = spl_object_hash($document);
if (isset($visited[$oid])) {
return;
}
$visited[$oid] = true;
$state = $this->getDocumentState($document);
switch ($state) {
case self::STATE_NEW:
unset($this->scheduledInserts[$oid]);
break;
case self::STATE_MANAGED:
unset($this->scheduledMoves[$oid]);
unset($this->scheduledReorders[$oid]);
break;
case self::STATE_DETACHED:
throw new InvalidArgumentException('Detached document passed to remove(): '.self::objToStr($document, $this->dm));
}
$this->scheduledRemovals[$oid] = $document;
$this->setDocumentState($oid, self::STATE_REMOVED);
$class = $this->dm->getClassMetadata(get_class($document));
if ($invoke = $this->eventListenersInvoker->getSubscribedSystems($class, Event::preRemove)) {
$this->eventListenersInvoker->invoke(
$class,
Event::preRemove,
$document,
new LifecycleEventArgs($document, $this->dm),
$invoke
);
}
$this->cascadeRemove($class, $document, $visited);
}
private function cascadeRemove(ClassMetadata $class, $document, &$visited)
{
foreach (array_merge($class->referenceMappings, $class->referrersMappings) as $fieldName) {
$mapping = $class->mappings[$fieldName];
if (!($mapping['cascade'] & ClassMetadata::CASCADE_REMOVE)) {
continue;
}
$related = $class->reflFields[$fieldName]->getValue($document);
if ($related instanceof Collection || is_array($related)) {
// If its a PersistentCollection initialization is intended! No unwrap!
foreach ($related as $relatedDocument) {
$this->doRemove($relatedDocument, $visited);
}
} elseif ($related !== null) {
$this->doRemove($related, $visited);
}