1
0
mirror of synced 2024-12-13 14:56:01 +03:00

Merge remote-tracking branch 'origin/2.2' into 2.2

This commit is contained in:
Benjamin Eberlei 2011-12-28 20:29:53 +01:00
commit 87e0c69381
12 changed files with 260 additions and 37 deletions

View File

@ -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.
*

View File

@ -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."'.");
}
}

View File

@ -0,0 +1,107 @@
<?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 LGPL. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\ORM;
/**
* Contains exception messages for all invalid lifecycle state exceptions inside UnitOfWork
*
* @author Benjamin Eberlei <kontakt@beberlei.de>
*/
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);
}
}

View File

@ -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)]);

@ -1 +1 @@
Subproject commit febecd320261d4a49a83b0c51286182cba1fa587
Subproject commit 18d11e0a54f8c4e726940a3753e3c2949dbf1c02

View File

@ -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);
}

View File

@ -0,0 +1,71 @@
<?php
namespace Doctrine\Tests\ORM\Functional;
use Doctrine\Tests\Models\CMS\CmsUser;
class UnitOfWorkLifecycleTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
protected function setUp()
{
$this->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);
}
}

View File

@ -677,4 +677,8 @@ class DDC1170Entity
$metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_NONE);
}
}
}
class Address {}
class Phonenumber {}
class Group {}

View File

@ -197,6 +197,7 @@ class MappedSuperclassBase {
private $mappedRelated1;
private $transient;
}
class MappedSuperclassRelated1 {}
/** @Entity */
class EntitySubClass2 extends MappedSuperclassBase {

View File

@ -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);

View File

@ -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'));
}
}

View File

@ -368,4 +368,17 @@ abstract class AbstractClassMetadataExporterTest extends \Doctrine\Tests\OrmTest
return rmdir($path);
}
}
}
}
class Address
{
}
class Phonenumber
{
}
class Group
{
}