diff --git a/lib/Doctrine/ORM/Mapping/ClassMetadata.php b/lib/Doctrine/ORM/Mapping/ClassMetadata.php index b6c31c52d..a5b983fbb 100644 --- a/lib/Doctrine/ORM/Mapping/ClassMetadata.php +++ b/lib/Doctrine/ORM/Mapping/ClassMetadata.php @@ -123,6 +123,25 @@ class ClassMetadata extends ClassMetadataInfo implements IClassMetadata $this->reflFields[$mapping['fieldName']] = $refProp; } + /** + * Validates & completes the basic mapping information that is common to all + * association mappings (one-to-one, many-ot-one, one-to-many, many-to-many). + * + * @param array $mapping The mapping. + * @return array The updated mapping. + * @throws MappingException If something is wrong with the mapping. + */ + protected function _validateAndCompleteAssociationMapping(array $mapping) + { + $mapping = parent::_validateAndCompleteAssociationMapping($mapping); + + if ( ! \Doctrine\Common\ClassLoader::classExists($mapping['targetEntity']) ) { + throw MappingException::invalidTargetEntityClass($mapping['targetEntity'], $this->name, $mapping['fieldName']); + } + + return $mapping; + } + /** * Extracts the identifier values of an entity of this class. * diff --git a/lib/Doctrine/ORM/Mapping/MappingException.php b/lib/Doctrine/ORM/Mapping/MappingException.php index babf4c98e..c71c2e91c 100644 --- a/lib/Doctrine/ORM/Mapping/MappingException.php +++ b/lib/Doctrine/ORM/Mapping/MappingException.php @@ -324,4 +324,9 @@ class MappingException extends \Doctrine\ORM\ORMException { return new self("Entity '". $className . "' has a composite identifier but uses an ID generator other than manually assigning (Identity, Sequence). This is not supported."); } + + public static function invalidTargetEntityClass($targetEntity, $sourceEntity, $associationName) + { + return new self("The target-entity " . $targetEntity . " cannot be found in '" . $sourceEntity."#".$associationName."'."); + } } diff --git a/lib/Doctrine/ORM/ORMInvalidArgumentException.php b/lib/Doctrine/ORM/ORMInvalidArgumentException.php new file mode 100644 index 000000000..878ee4b71 --- /dev/null +++ b/lib/Doctrine/ORM/ORMInvalidArgumentException.php @@ -0,0 +1,107 @@ +. + */ + +namespace Doctrine\ORM; + +/** + * Contains exception messages for all invalid lifecycle state exceptions inside UnitOfWork + * + * @author Benjamin Eberlei + */ +class ORMInvalidArgumentException extends \InvalidArgumentException +{ + static public function scheduleInsertForManagedEntity($entity) + { + return new self("A managed+dirty entity " . self::objToStr($entity) . " can not be scheduled for insertion."); + } + + static public function scheduleInsertForRemovedEntity($entity) + { + return new self("Removed entity " . self::objToStr($entity) . " can not be scheduled for insertion."); + } + + static public function scheduleInsertTwice($entity) + { + return new self("Entity " . self::objToStr($entity) . " can not be scheduled for insertion twice."); + } + + static public function entityWithoutIdentity($className, $entity) + { + throw new self( + "The given entity of type '" . $className . "' (".self::objToStr($entity).") has no identity/no " . + "id values set. It cannot be added to the identity map." + ); + } + + static public function readOnlyRequiresManagedEntity($entity) + { + return new self("Only managed entities can be marked or checked as read only. But " . self::objToStr($entity) . " is not"); + } + + static public function newEntityFoundThroughRelationship(array $assoc, $entry) + { + return new self("A new entity was found through the relationship '" + . $assoc['sourceEntity'] . "#" . $assoc['fieldName'] . "' that was not" + . " configured to cascade persist operations for entity: " . self::objToStr($entry) . "." + . " To solve this issue: Either explicitly call EntityManager#persist()" + . " on this unknown entity or configure cascade persist " + . " this association in the mapping for example @ManyToOne(..,cascade={\"persist\"}). " + . " If you cannot find out which entity causes the problem" + . " implement '" . $assoc['targetEntity'] . "#__toString()' to get a clue."); + } + + static public function detachedEntityFoundThroughRelationship(array $assoc, $entry) + { + throw new self("A detached entity of type " . $assoc['targetEntity'] . " (" . self::objToStr($entry) . ") " + . " was found through the relationship '" . $assoc['sourceEntity'] . "#" . $assoc['fieldName'] . "' " + . "during cascading a persist operation."); + } + + static public function entityNotManaged($entity) + { + throw new self("Entity " . self::objToStr($entity) . " is not managed. An entity is managed if its fetched " . + "from the database or registered as new through EntityManager#persist"); + } + + static public function entityHasNoIdentity($entity, $operation) + { + throw new self("Entity has no identity, therefore " . $operation ." cannot be performed. " . self::objToStr($entity)); + } + + static public function entityIsRemoved($entity, $operation) + { + throw new self("Entity is removed, therefore " . $operation ." cannot be performed. " . self::objToStr($entity)); + } + + static public function detachedEntityCannot($entity, $operation) + { + throw new self("A detached entity was found during " . $operation . " " . self::objToStr($entity)); + } + + /** + * Helper method to show an object as string. + * + * @param object $obj + * @return string + */ + private static function objToStr($obj) + { + return method_exists($obj, '__toString') ? (string)$obj : get_class($obj).'@'.spl_object_hash($obj); + } +} \ No newline at end of file diff --git a/lib/Doctrine/ORM/UnitOfWork.php b/lib/Doctrine/ORM/UnitOfWork.php index a026d001a..0ebdedcb9 100644 --- a/lib/Doctrine/ORM/UnitOfWork.php +++ b/lib/Doctrine/ORM/UnitOfWork.php @@ -710,14 +710,7 @@ class UnitOfWork implements PropertyChangedListener switch ($state) { case self::STATE_NEW: if ( ! $assoc['isCascadePersist']) { - $message = "A new entity was found through the relationship '%s#%s' that was not configured " . - ' to cascade persist operations for entity: %s. Explicitly persist the new entity or ' . - 'configure cascading persist operations on the relationship. If you cannot find out ' . - 'which entity causes the problem, implement %s#__toString() to get a clue.'; - - throw new InvalidArgumentException(sprintf( - $message, $assoc['sourceEntity'], $assoc['fieldName'], self::objToStr($entry), $assoc['targetEntity'] - )); + throw ORMInvalidArgumentException::newEntityFoundThroughRelationship($assoc, $entry); } $this->persistNew($targetClass, $entry); @@ -735,9 +728,7 @@ class UnitOfWork implements PropertyChangedListener case self::STATE_DETACHED: // Can actually not happen right now as we assume STATE_NEW, // so the exception will be raised from the DBAL layer (constraint violation). - $message = 'A detached entity was found through a relationship during cascading a persist operation.'; - - throw new InvalidArgumentException($message); + throw ORMInvalidArgumentException::detachedEntityFoundThroughRelationship($assoc, $entry); break; default: @@ -797,7 +788,7 @@ class UnitOfWork implements PropertyChangedListener $oid = spl_object_hash($entity); if ( ! isset($this->entityStates[$oid]) || $this->entityStates[$oid] != self::STATE_MANAGED) { - throw new InvalidArgumentException('Entity must be managed.'); + throw ORMInvalidArgumentException::entityNotManaged($entity); } // skip if change tracking is "NOTIFY" @@ -1077,11 +1068,14 @@ class UnitOfWork implements PropertyChangedListener } if (isset($this->entityDeletions[$oid])) { - throw new InvalidArgumentException("Removed entity can not be scheduled for insertion."); + throw ORMInvalidArgumentException::scheduleInsertForRemovedEntity($entity); + } + if (isset($this->originalEntityData[$oid]) && ! isset($this->entityInsertions[$oid])) { + throw ORMInvalidArgumentException::scheduleInsertForManagedEntity($entity); } if (isset($this->entityInsertions[$oid])) { - throw new InvalidArgumentException("Entity can not be scheduled for insertion twice."); + throw ORMInvalidArgumentException::scheduleInsertTwice($entity); } $this->entityInsertions[$oid] = $entity; @@ -1112,11 +1106,11 @@ class UnitOfWork implements PropertyChangedListener $oid = spl_object_hash($entity); if ( ! isset($this->entityIdentifiers[$oid])) { - throw new InvalidArgumentException("Entity has no identity."); + throw ORMInvalidArgumentException::entityHasNoIdentity($entity, "scheduling for update"); } if (isset($this->entityDeletions[$oid])) { - throw new InvalidArgumentException("Entity is removed."); + throw ORMInvalidArgumentException::entityIsRemoved($entity, "schedule for update"); } if ( ! isset($this->entityUpdates[$oid]) && ! isset($this->entityInsertions[$oid])) { @@ -1256,7 +1250,7 @@ class UnitOfWork implements PropertyChangedListener $idHash = implode(' ', $this->entityIdentifiers[spl_object_hash($entity)]); if ($idHash === '') { - throw new InvalidArgumentException('The given entity has no identity.'); + throw ORMInvalidArgumentException::entityWithoutIdentity($classMetadata->name, $entity); } $className = $classMetadata->rootEntityName; @@ -1366,7 +1360,7 @@ class UnitOfWork implements PropertyChangedListener $idHash = implode(' ', $this->entityIdentifiers[$oid]); if ($idHash === '') { - throw new InvalidArgumentException('The given entity has no identity.'); + throw ORMInvalidArgumentException::entityHasNoIdentity($entity, "remove from identity map"); } $className = $classMetadata->rootEntityName; @@ -1513,10 +1507,10 @@ class UnitOfWork implements PropertyChangedListener case self::STATE_DETACHED: // Can actually not happen right now since we assume STATE_NEW. - throw new InvalidArgumentException('Detached entity passed to persist().'); + throw ORMInvalidArgumentException::detachedEntityCannot($entity, "persisted"); default: - throw new UnexpectedValueException(sprintf('Unexpected entity state: %s', $entityState)); + throw new UnexpectedValueException("Unexpected entity state: $entityState." . self::objToStr($entity)); } $this->cascadePersist($entity, $visited); @@ -1580,10 +1574,9 @@ class UnitOfWork implements PropertyChangedListener break; case self::STATE_DETACHED: - throw new InvalidArgumentException('A detached entity can not be removed.'); - + throw ORMInvalidArgumentException::detachedEntityCannot($entity, "removed"); default: - throw new UnexpectedValueException(sprintf('Unexpected entity state: %s', $entityState)); + throw new UnexpectedValueException("Unexpected entity state: $entityState." . self::objToStr($entity)); } } @@ -1665,8 +1658,7 @@ class UnitOfWork implements PropertyChangedListener if ($managedCopy) { // We have the entity in-memory already, just make sure its not removed. if ($this->getEntityState($managedCopy) == self::STATE_REMOVED) { - throw new InvalidArgumentException('Removed entity detected during merge.' - . ' Can not merge with a removed entity.'); + throw ORMInvalidArgumentException::entityIsRemoved($managedCopy, "merge"); } } else { // We need to fetch the managed copy in order to merge. @@ -1883,7 +1875,7 @@ class UnitOfWork implements PropertyChangedListener $class = $this->em->getClassMetadata(get_class($entity)); if ($this->getEntityState($entity) !== self::STATE_MANAGED) { - throw new InvalidArgumentException("Entity is not MANAGED."); + throw ORMInvalidArgumentException::entityNotManaged($entity); } $this->getEntityPersister($class->name)->refresh( @@ -2107,7 +2099,7 @@ class UnitOfWork implements PropertyChangedListener public function lock($entity, $lockMode, $lockVersion = null) { if ($this->getEntityState($entity, self::STATE_DETACHED) != self::STATE_MANAGED) { - throw new InvalidArgumentException("Entity is not MANAGED."); + throw ORMInvalidArgumentException::entityNotManaged($entity); } $entityName = get_class($entity); @@ -2881,7 +2873,7 @@ class UnitOfWork implements PropertyChangedListener public function markReadOnly($object) { if ( ! is_object($object) || ! $this->isInIdentityMap($object)) { - throw new InvalidArgumentException("Managed entity required"); + throw ORMInvalidArgumentException::readOnlyRequiresManagedEntity($object); } $this->readOnlyObjects[spl_object_hash($object)] = true; @@ -2897,7 +2889,7 @@ class UnitOfWork implements PropertyChangedListener public function isReadOnly($object) { if ( ! is_object($object) ) { - throw new InvalidArgumentException("Managed entity required"); + throw ORMInvalidArgumentException::readOnlyRequiresManagedEntity($object); } return isset($this->readOnlyObjects[spl_object_hash($object)]); diff --git a/lib/vendor/doctrine-common b/lib/vendor/doctrine-common index febecd320..18d11e0a5 160000 --- a/lib/vendor/doctrine-common +++ b/lib/vendor/doctrine-common @@ -1 +1 @@ -Subproject commit febecd320261d4a49a83b0c51286182cba1fa587 +Subproject commit 18d11e0a54f8c4e726940a3753e3c2949dbf1c02 diff --git a/tests/Doctrine/Tests/ORM/Functional/Locking/LockTest.php b/tests/Doctrine/Tests/ORM/Functional/Locking/LockTest.php index 6917e7252..62c787409 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Locking/LockTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/Locking/LockTest.php @@ -71,7 +71,7 @@ class LockTest extends \Doctrine\Tests\OrmFunctionalTestCase { public function testLockUnmanagedEntity_ThrowsException() { $article = new CmsArticle(); - $this->setExpectedException('InvalidArgumentException', 'Entity is not MANAGED.'); + $this->setExpectedException('InvalidArgumentException', 'Entity Doctrine\Tests\Models\CMS\CmsArticle'); $this->_em->lock($article, LockMode::OPTIMISTIC, $article->version + 1); } diff --git a/tests/Doctrine/Tests/ORM/Functional/UnitOfWorkLifecycleTest.php b/tests/Doctrine/Tests/ORM/Functional/UnitOfWorkLifecycleTest.php new file mode 100644 index 000000000..08e3720ca --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Functional/UnitOfWorkLifecycleTest.php @@ -0,0 +1,71 @@ +useModelSet('cms'); + parent::setUp(); + } + + public function testScheduleInsertManaged() + { + $user = new CmsUser(); + $user->username = "beberlei"; + $user->name = "Benjamin"; + $user->status = "active"; + $this->_em->persist($user); + $this->_em->flush(); + + $this->setExpectedException("Doctrine\ORM\ORMInvalidArgumentException", "A managed+dirty entity Doctrine\Tests\Models\CMS\CmsUser"); + $this->_em->getUnitOfWork()->scheduleForInsert($user); + } + + public function testScheduleInsertDeleted() + { + $user = new CmsUser(); + $user->username = "beberlei"; + $user->name = "Benjamin"; + $user->status = "active"; + $this->_em->persist($user); + $this->_em->flush(); + + $this->_em->remove($user); + + $this->setExpectedException("Doctrine\ORM\ORMInvalidArgumentException", "Removed entity Doctrine\Tests\Models\CMS\CmsUser"); + $this->_em->getUnitOfWork()->scheduleForInsert($user); + } + + public function testScheduleInsertTwice() + { + $user = new CmsUser(); + $user->username = "beberlei"; + $user->name = "Benjamin"; + $user->status = "active"; + + $this->_em->getUnitOfWork()->scheduleForInsert($user); + + $this->setExpectedException("Doctrine\ORM\ORMInvalidArgumentException", "Entity Doctrine\Tests\Models\CMS\CmsUser"); + $this->_em->getUnitOfWork()->scheduleForInsert($user); + } + + public function testAddToIdentityMapWithoutIdentity() + { + $user = new CmsUser(); + + $this->setExpectedException("Doctrine\ORM\ORMInvalidArgumentException", "The given entity of type 'Doctrine\Tests\Models\CMS\CmsUser' (Doctrine\Tests\Models\CMS\CmsUser@"); + $this->_em->getUnitOfWork()->registerManaged($user, array(), array()); + } + + public function testMarkReadOnlyNonManaged() + { + $user = new CmsUser(); + + $this->setExpectedException("Doctrine\ORM\ORMInvalidArgumentException", "Only managed entities can be marked or checked as read only. But Doctrine\Tests\Models\CMS\CmsUser@"); + $this->_em->getUnitOfWork()->markReadOnly($user); + } +} \ No newline at end of file diff --git a/tests/Doctrine/Tests/ORM/Mapping/AbstractMappingDriverTest.php b/tests/Doctrine/Tests/ORM/Mapping/AbstractMappingDriverTest.php index 330955a6f..0042259e1 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/AbstractMappingDriverTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/AbstractMappingDriverTest.php @@ -677,4 +677,8 @@ class DDC1170Entity $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_NONE); } -} \ No newline at end of file +} + +class Address {} +class Phonenumber {} +class Group {} diff --git a/tests/Doctrine/Tests/ORM/Mapping/BasicInheritanceMappingTest.php b/tests/Doctrine/Tests/ORM/Mapping/BasicInheritanceMappingTest.php index dfaf8c19a..0c739e9f8 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/BasicInheritanceMappingTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/BasicInheritanceMappingTest.php @@ -197,6 +197,7 @@ class MappedSuperclassBase { private $mappedRelated1; private $transient; } +class MappedSuperclassRelated1 {} /** @Entity */ class EntitySubClass2 extends MappedSuperclassBase { diff --git a/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataFactoryTest.php b/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataFactoryTest.php index 252428399..223ef8582 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataFactoryTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataFactoryTest.php @@ -33,12 +33,12 @@ class ClassMetadataFactoryTest extends \Doctrine\Tests\OrmTestCase // Add a mapped field $cm1->mapField(array('fieldName' => 'id', 'type' => 'integer', 'id' => true)); // and a mapped association - $cm1->mapOneToOne(array('fieldName' => 'other', 'targetEntity' => 'Other', 'mappedBy' => 'this')); + $cm1->mapOneToOne(array('fieldName' => 'other', 'targetEntity' => 'TestEntity1', 'mappedBy' => 'this')); // and an association on the owning side $joinColumns = array( array('name' => 'other_id', 'referencedColumnName' => 'id') ); - $cm1->mapOneToOne(array('fieldName' => 'association', 'targetEntity' => 'Other', 'joinColumns' => $joinColumns)); + $cm1->mapOneToOne(array('fieldName' => 'association', 'targetEntity' => 'TestEntity1', 'joinColumns' => $joinColumns)); // and an id generator type $cm1->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_AUTO); diff --git a/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataTest.php b/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataTest.php index fb43eeae7..7a4de4ca4 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataTest.php @@ -29,7 +29,7 @@ class ClassMetadataTest extends \Doctrine\Tests\OrmTestCase $cm->setParentClasses(array("UserParent")); $cm->setCustomRepositoryClass("UserRepository"); $cm->setDiscriminatorColumn(array('name' => 'disc', 'type' => 'integer')); - $cm->mapOneToOne(array('fieldName' => 'phonenumbers', 'targetEntity' => 'Bar', 'mappedBy' => 'foo')); + $cm->mapOneToOne(array('fieldName' => 'phonenumbers', 'targetEntity' => 'CmsAddress', 'mappedBy' => 'foo')); $cm->markReadOnly(); $cm->addNamedQuery(array('name' => 'dql', 'query' => 'foo')); $this->assertEquals(1, count($cm->associationMappings)); @@ -52,7 +52,7 @@ class ClassMetadataTest extends \Doctrine\Tests\OrmTestCase $oneOneMapping = $cm->getAssociationMapping('phonenumbers'); $this->assertTrue($oneOneMapping['fetch'] == ClassMetadata::FETCH_LAZY); $this->assertEquals('phonenumbers', $oneOneMapping['fieldName']); - $this->assertEquals('Doctrine\Tests\Models\CMS\Bar', $oneOneMapping['targetEntity']); + $this->assertEquals('Doctrine\Tests\Models\CMS\CmsAddress', $oneOneMapping['targetEntity']); $this->assertTrue($cm->isReadOnly); $this->assertEquals(array('dql' => array('name'=>'dql','query'=>'foo','dql'=>'foo')), $cm->namedQueries); } @@ -482,4 +482,15 @@ class ClassMetadataTest extends \Doctrine\Tests\OrmTestCase $this->setExpectedException("Doctrine\ORM\Mapping\MappingException", "Entity 'Doctrine\Tests\Models\CMS\CmsUser' has no method 'notfound' to be registered as lifecycle callback."); $cm->addLifecycleCallback('notfound', 'postLoad'); } + + /** + * @group ImproveErrorMessages + */ + public function testTargetEntityNotFound() + { + $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); + + $this->setExpectedException("Doctrine\ORM\Mapping\MappingException", "The target-entity Doctrine\Tests\Models\CMS\UnknownClass cannot be found in 'Doctrine\Tests\Models\CMS\CmsUser#address'."); + $cm->mapManyToOne(array('fieldName' => 'address', 'targetEntity' => 'UnknownClass')); + } } diff --git a/tests/Doctrine/Tests/ORM/Tools/Export/AbstractClassMetadataExporterTest.php b/tests/Doctrine/Tests/ORM/Tools/Export/AbstractClassMetadataExporterTest.php index 2267020e3..964512e81 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Export/AbstractClassMetadataExporterTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/Export/AbstractClassMetadataExporterTest.php @@ -368,4 +368,17 @@ abstract class AbstractClassMetadataExporterTest extends \Doctrine\Tests\OrmTest return rmdir($path); } } -} \ No newline at end of file +} + +class Address +{ + +} +class Phonenumber +{ + +} +class Group +{ + +}