/** * @param mixed $entity New entity * @param string $entityName Class name * @param string|array $criteria Fieldname to find existing entity * @param array $excludedProperties Excluded properties * * @return mixed */ public function findAndReplaceEntity($entity, $entityName, $criteria = 'id', $excludedProperties = []) { if (is_array($criteria)) { $existingEntity = $this->getEntityByCriteria($criteria, $entity); } else { $existingEntity = $this->getEntityOrNull($entity, $criteria, $entityName); } if ($existingEntity) { $this->strategyHelper->importEntity($existingEntity, $entity, $excludedProperties); $entity = $existingEntity; } else { /* @var ClassMetadataInfo $metadata */ $metadata = $this->getEntityManager($entityName)->getClassMetadata($entityName); $identifier = $metadata->getSingleIdentifierFieldName(); $setterMethod = 'set' . ucfirst($identifier); if (method_exists($entity, $setterMethod)) { $entity->{$setterMethod}(null); } elseif (property_exists($entity, $identifier)) { $reflection = new \ReflectionProperty(ClassUtils::getRealClass($entity), $identifier); $reflection->setAccessible(true); $reflection->setValue($entity, null); } } return $entity; }
public function testImportEntity() { $basicEntity = new \stdClass(); $importedEntity = new \stdClass(); $importedEntity->fieldOne = 'one'; $importedEntity->fieldTwo = 'two'; $importedEntity->excludedField = 'excluded'; $excludedProperties = array('excludedField'); $metadata = $this->getMockBuilder('\\Doctrine\\ORM\\Mapping\\ClassMetadata')->disableOriginalConstructor()->getMock(); $metadata->expects($this->once())->method('getFieldNames')->will($this->returnValue(array('fieldOne', 'excludedField'))); $metadata->expects($this->once())->method('getAssociationNames')->will($this->returnValue(array('fieldTwo'))); $this->fieldHelper->expects($this->atLeastOnce())->method('getObjectValue')->with($importedEntity)->will($this->returnValue('testValue')); $this->fieldHelper->expects($this->atLeastOnce())->method('setObjectValue')->with($basicEntity, $this->isType('string'), 'testValue'); $entityManager = $this->getMockBuilder('Doctrine\\ORM\\EntityManager')->disableOriginalConstructor()->getMock(); $entityManager->expects($this->once())->method('getClassMetadata')->with(get_class($basicEntity))->will($this->returnValue($metadata)); $this->managerRegistry->expects($this->once())->method('getManagerForClass')->with(get_class($basicEntity))->will($this->returnValue($entityManager)); $this->helper->importEntity($basicEntity, $importedEntity, $excludedProperties); }