/** * Returns a string representation of the identifier of a given entity. * * @param mixed $entity * @param EntityMetadata $metadata * * @return string */ public function getEntityId($entity, EntityMetadata $metadata) { $result = null; $idFieldNames = $metadata->getIdentifierFieldNames(); $idFieldNamesCount = count($idFieldNames); if ($idFieldNamesCount === 1) { $fieldName = reset($idFieldNames); if (!$this->objectAccessor->hasProperty($entity, $fieldName)) { throw new \RuntimeException(sprintf('An object of the type "%s" does not have the identifier property "%s".', $metadata->getClassName(), $fieldName)); } $result = $this->entityIdTransformer->transform($this->objectAccessor->getValue($entity, $fieldName)); } elseif ($idFieldNamesCount > 1) { $id = []; foreach ($idFieldNames as $fieldName) { if (!$this->objectAccessor->hasProperty($entity, $fieldName)) { throw new \RuntimeException(sprintf('An object of the type "%s" does not have the identifier property "%s".', $metadata->getClassName(), $fieldName)); } $id[$fieldName] = $this->objectAccessor->getValue($entity, $fieldName); } $result = $this->entityIdTransformer->transform($id); } else { throw new \RuntimeException(sprintf('The "%s" entity does not have an identifier.', $metadata->getClassName())); } if (empty($result)) { throw new \RuntimeException(sprintf('The identifier value for "%s" entity must not be empty.', $metadata->getClassName())); } return $result; }
/** * @param mixed $object * @param string $targetClassName * @param EntityMetadata|null $targetMetadata * * @return array */ protected function prepareRelatedValue($object, $targetClassName, EntityMetadata $targetMetadata = null) { $idOnly = false; $targetEntityType = null; if (is_array($object) || is_object($object)) { if (null !== $targetMetadata && $targetMetadata->isInheritedType()) { $targetEntityType = $this->getEntityType($this->objectAccessor->getClassName($object), $targetClassName); $data = $this->objectAccessor->toArray($object); if ($this->isIdentity($data, $targetMetadata)) { $idOnly = true; $object = count($data) === 1 ? reset($data) : $data; } } } else { $idOnly = true; } if (!$targetEntityType) { $targetEntityType = $this->getEntityType($targetClassName); } return ['value' => $object, 'entityType' => $targetEntityType, 'idOnly' => $idOnly]; }