From 267ce7df889eb971e2e27e260ce03b110ce1f7a3 Mon Sep 17 00:00:00 2001 From: Benjamin Eberlei Date: Sat, 17 Dec 2011 19:35:10 +0100 Subject: [PATCH] DDC-1544 - Add ResolveTargetEntityListener --- .../ORM/Tools/ResolveTargetEntityListener.php | 92 +++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 lib/Doctrine/ORM/Tools/ResolveTargetEntityListener.php diff --git a/lib/Doctrine/ORM/Tools/ResolveTargetEntityListener.php b/lib/Doctrine/ORM/Tools/ResolveTargetEntityListener.php new file mode 100644 index 000000000..6151763da --- /dev/null +++ b/lib/Doctrine/ORM/Tools/ResolveTargetEntityListener.php @@ -0,0 +1,92 @@ +. + */ + +namespace Doctrine\ORM\Tools; + +use Doctrine\ORM\Events\LoadClassMetadataEventArgs; + +/** + * ResolveTargetEntityListener + * + * Mechanism to overwrite interfaces or classes specified as association + * targets. + * + * @author Benjamin Eberlei + * @since 2.2 + */ +class ResolveTargetEntityListener +{ + /** + * @var array + */ + private $resolveTargetEntities = array(); + + /** + * Add a target-entity class name to resolve to a new class name. + * + * @param string $originalEntity + * @param string $newEntity + * @param array $mapping + * @return void + */ + public function addResolveTargetEntity($originalEntity, $newEntity, array $mapping) + { + $mapping['targetEntity'] = ltrim($newEntity, "\\"); + $this->resolveTargetEntities[ltrim($originalEntity, "\\")] = $mapping; + } + + /** + * Process event and resolve new target entity names. + * + * @param LoadClassMetadataEventArgs $args + * @return void + */ + public function loadClassMetadata(LoadClassMetadataEventArgs $args) + { + $cm = $args->getClassMetadata(); + foreach ($cm->associationMappings as $assocName => $mapping) { + if (isset($this->resolveTargetEntities[$mapping['targetEntity']])) { + $this->remapAssociation($cm, $mapping); + } + } + } + + private function remapAssocation($classMetadata, $mapping) + { + $newMapping = $this->resolveTargetEntities[$mapping['targetEntity']]; + $newMapping['fieldName'] = $mapping['fieldName']; + unset($cm->associationMappings[$mapping['fieldName']]); + + switch ($mapping['type']) { + case ClassMetadata::MANY_TO_MANY: + $cm->mapManyToMany($newMapping); + break; + case ClassMetadata::MANY_TO_ONE: + $cm->mapManyToOne($newMapping); + break; + case ClassMetadata::ONE_TO_MANY: + $cm->mapOneToMany($newMapping); + break; + case ClassMetadata::ONE_TO_ONE: + $cm->mapOneToOne($newMapping); + break; + } + } +} +