@param array $fields
@param \ReflectionClass $entityReflection
@param mixed $entityInstance
@param EntityFieldDefinition[] $fieldsDefinition

@throws UnknownFieldTypeException
977213
private function mapEntityFields(array $fields, \ReflectionClass $entityReflection, $entityInstance, array $fieldsDefinition)
    {
        foreach ($fieldsDefinition as $fieldName => $definition) {
            $typeName = $definition->getTypeName();

            if (!isset($this->typeMappers[$typeName])) {
                throw new UnknownFieldTypeException($typeName);
            }

            $fieldReflection = $entityReflection->getProperty($definition->getFieldName());
            $fieldReflection->setAccessible(true);
            $fieldReflection->setValue($entityInstance, $this->typeMappers[$typeName]->fromString($fieldName, $fields));
            $fieldReflection->setAccessible(false);
        }
    }
224650
@Override
    public CreateUpdateEntitiesResult updateEntities(String entityInstanceDefinition) throws AtlasException {
        entityInstanceDefinition = ParamChecker.notEmpty(entityInstanceDefinition, "Entity instance definition");
        ITypedReferenceableInstance[] typedInstances = deserializeClassInstances(entityInstanceDefinition);

        CreateUpdateEntitiesResult result = repository.updateEntities(typedInstances);
        onEntitiesAddedUpdated(result.getEntityResult());
        return result;
    }
806675
private function ensureEntityHasProvidedEnabledField(ObjectManager $objectManager, $entity, string $enabledPropertyPath): void
    {
        /** @var ClassMetadata $class */
        $class = $objectManager->getClassMetadata(get_class($entity));

        if (!$class->hasField($enabledPropertyPath) && !$class->hasAssociation($enabledPropertyPath)) {
            throw new ConstraintDefinitionException(
                sprintf("The field '%s' is not mapped by Doctrine, so it cannot be validated.", $enabledPropertyPath)
            );
        }
    }
436850
protected function fillExistingInstanceFromEntityArray(DoplioDbTable $instance, array $entityArray)
    {
        $relations = $instance->getRelations();

        foreach ($entityArray as $offset => $value) {
            if (method_exists($instance, $offset)) {
                /** @var Relation $relationship */
                $relationship     = $instance->$offset();
                $subMapper        = new GenericDataMapper($this->resolver);
                $className        = get_class($relationship->getQuery()->getModel());
                $subMapper->table = new $className();

                if (!array_key_exists($offset, $relations)) {
                    $instance->setRelation($offset, $this->createInstanceFromEntityArray($value, $subMapper));
                } else {
                    if ($relations[$offset] instanceof Collection) {
                        $filled = $relations[$offset];
                        foreach ($relations[$offset] as $collectionOffset => $item) {
                            $this->fillExistingInstanceFromEntityArray($item, $value[$collectionOffset]);
                        }
                    } else {
                        $filled = $this->fillExistingInstanceFromEntityArray($relations[$offset], $value);
                    }
                    $instance->setRelation($offset, $filled);
                }

                unset($entityArray[$offset]);
            }
        }

        $instance->fill($entityArray);
        return $instance;
    }
188235
protected function generateFieldWriteStatement(Entity $entity, FieldDescriptorProto $field)
    {
        $generator = new WriteFieldStatementGenerator($this->context);
        $statement = $generator->generateFieldWriteStatement($entity, $field);

        return $statement;
    }
332527
public function setFieldDefinitions(array $fieldDefinitionObjects)
    {
        $this->data['fields'] = [];
        foreach ($fieldDefinitionObjects as $identifier => $fieldDefinitionObject) {
            $this->addFieldDefinitionObject($identifier, $fieldDefinitionObject);
        }
    }
706343
public function delete(EntityDefinition $definition, array $ids, WriteContext $writeContext): DeleteResult
    {
        $this->validateWriteInput($ids);

        $commandQueue = new WriteCommandQueue();

        $fields = $definition->getPrimaryKeys();

        $resolved = [];
        foreach ($ids as $raw) {
            $mapped = [];

            /** @var Field $field */
            foreach ($fields as $field) {
                if (!($field instanceof StorageAware)) {
                    continue;
                }

                if (array_key_exists($field->getPropertyName(), $raw)) {
                    $mapped[$field->getStorageName()] = $raw[$field->getPropertyName()];
                    continue;
                }

                if ($field instanceof ReferenceVersionField) {
                    $mapped[$field->getStorageName()] = $writeContext->getContext()->getVersionId();
                    continue;
                }

                if ($field instanceof VersionField) {
                    $mapped[$field->getStorageName()] = $writeContext->getContext()->getVersionId();
                    continue;
                }

                $fieldKeys = $fields
                    ->filter(function (Field $field) {
                        return !$field instanceof VersionField && !$field instanceof ReferenceVersionField;
                    })
                    ->map(function (Field $field) {
                        return $field->getPropertyName();
                    });

                throw new IncompletePrimaryKeyException($fieldKeys);
            }

            $resolved[] = $mapped;
        }

        if (!$definition instanceof MappingEntityDefinition) {
            $restrictions = $this->foreignKeyResolver->getAffectedDeleteRestrictions($definition, $resolved, $writeContext->getContext());

            if (!empty($restrictions)) {
                $restrictions = array_map(function ($restriction) {
                    return new RestrictDeleteViolation($restriction['pk'], $restriction['restrictions']);
                }, $restrictions);

                throw new RestrictDeleteViolationException($definition, $restrictions, $this->registry);
            }
        }

        $cascades = [];
        if (!$definition instanceof MappingEntityDefinition) {
            $cascadeDeletes = $this->foreignKeyResolver->getAffectedDeletes($definition, $resolved, $writeContext->getContext());

            $cascadeDeletes = array_column($cascadeDeletes, 'restrictions');
            foreach ($cascadeDeletes as $cascadeDelete) {
                $cascades = array_merge_recursive($cascades, $cascadeDelete);
            }

            foreach ($cascades as $affectedDefinitionClass => &$cascade) {
                $affectedDefinition = $this->registry->get($affectedDefinitionClass);

                $cascade = array_map(function ($key) use ($affectedDefinition) {
                    $payload = $key;

                    if (!\is_array($key)) {
                        $payload = ['id' => $key];
                    }

                    return new EntityWriteResult($key, $payload, $affectedDefinition, null);
                }, $cascade);
            }
        }

        $skipped = [];
        foreach ($resolved as $mapped) {
            $mappedBytes = array_map(function ($id) {
                return Uuid::fromHexToBytes($id);
            }, $mapped);

            $existence = $this->gateway->getExistence($definition, $mappedBytes, [], $commandQueue);

            if (!$existence->exists()) {
                $skipped[$definition->getClass()][] = new EntityWriteResult($mapped, $mapped, $definition, $existence);
                continue;
            }

            $commandQueue->add(
                $definition,
                new DeleteCommand(
                    $definition,
                    $mappedBytes,
                    $existence
                )
            );
        }

        $writeContext->setLanguages($this->languageLoader->loadLanguages());
        $identifiers = $this->getWriteResults($commandQueue);
        $this->gateway->execute($commandQueue->getCommandsInOrder(), $writeContext);

        return new DeleteResult(
            array_merge_recursive($identifiers, $cascades),
            $skipped
        );
    }
601322
public function setFieldValue($entity, $fieldName, $value)
    {
        if ($this->fieldMappings[$fieldName]['direct']) {
            $this->reflFields[$fieldName]->setValue($entity, $value);
        } else {
            if (!array_key_exists('setMethod', $this->fieldMappings[$fieldName])) {
                $this->fieldMappings[$fieldName]['setMethod'] = $this->inferSetter($fieldName);
            }
            $setter = $this->fieldMappings[$fieldName]['setMethod'];

            if ($this->reflClass->hasMethod($setter)) {
                return call_user_func(array($entity, $setter), $value);
            } else {
                throw MappingException::fieldSetMethodDoesNotExist($this->name, $fieldName, $setter);
            }
        }
    }
770271
public function readEntityMetadata(Entity $entity)
    {
        $className = $entity->getClassName();
        if (!isset($this->entities[ $className ])) {
            $this->entities[ $className ] = $entity;

            $this->readTableName($entity);

            $filter = \ReflectionProperty::IS_PRIVATE
                      | \ReflectionProperty::IS_PROTECTED
                      | \ReflectionProperty::IS_PUBLIC;

            $properties = $this->annotationReader->readProperties($className, $filter);

            try {
                foreach ($properties as $property => $comment) {
                    if ($comment->hasAnnotationType(FieldAnnotation::class)) {
                        $this->processField($comment, $property, $entity);
                    } else if ($comment->hasAnnotationType(RelationAnnotation::class)) {
                        $this->processRelation($comment, $property, $entity);
                    }
                }
                if ($entity->getPrimaryKey() === null) {
                    throw new EntityDefinitionException("Class {$className} must have a primary key.");
                }
            } catch (EntityDefinitionException $e) {
                throw new EntityDefinitionException("Could not instantiate metadata for {$className}", 0, $e);
            }
        }
    }
418026
protected function getListBuilder($entityName, $fieldDescriptors)
    {
        /** @var RestHelperInterface $restHelper */
        $restHelper = $this->get('sulu_core.doctrine_rest_helper');

        /** @var DoctrineListBuilderFactory $factory */
        $factory = $this->get('sulu_core.doctrine_list_builder_factory');

        $listBuilder = $factory->create($entityName);

        $restHelper->initializeListBuilder(
            $listBuilder,
            $fieldDescriptors
        );

        return $listBuilder;
    }
689414
public function getErrorsForField(EntityDescriptor $ed, $field) {
		$r = array();
		foreach( static::$testedValues as $value ) {
			try {
				$ed->validateFieldValue($field, $value);
			} catch( InvalidFieldException $e ) {
				$r[$e->getKey()] = $e;
			}
		}
		return $r;
	}
1061254
protected function generateExtensionMethod(Entity $entity, FieldDescriptorProto $field)
    {
        $fieldName  = $field->getName();
        $methodName = $this->getCamelizedName($field);
        $lines      = $this->generateBody($entity, $field);
        $body       = implode(PHP_EOL, $lines);
        $method     = MethodGenerator::fromArray([
            'static'     => true,
            'body'       => $body,
            'name'       => $methodName,
            'docblock'   => [
                'shortDescription' => "Extension field : $fieldName",
                'tags'             => [
                    [
                        'name'        => 'return',
                        'description' => '\Protobuf\Extension\ExtensionField',
                    ]
                ]
            ]
        ]);

        $method->getDocblock()->setWordWrap(false);

        return $method;
    }
344874
private function attachEntityListeners(
        array $classAnnotations,
        ReflectionClass $reflectionClass,
        Mapping\ClassMetadata $metadata
    ) : void {
        // Evaluate @EntityListeners annotation
        if (isset($classAnnotations[Annotation\EntityListeners::class])) {
            /** @var Annotation\EntityListeners $entityListenersAnnot */
            $entityListenersAnnot = $classAnnotations[Annotation\EntityListeners::class];

            foreach ($entityListenersAnnot->value as $listenerClassName) {
                if (! class_exists($listenerClassName)) {
                    throw Mapping\MappingException::entityListenerClassNotFound(
                        $listenerClassName,
                        $metadata->getClassName()
                    );
                }

                $listenerClass = new ReflectionClass($listenerClassName);

                /** @var ReflectionMethod $method */
                foreach ($listenerClass->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {
                    foreach ($this->getMethodCallbacks($method) as $callback) {
                        $metadata->addEntityListener($callback, $listenerClassName, $method->getName());
                    }
                }
            }
        }
    }
996590
private function getFieldDescriptors($entityName, $id)
    {
        if (null === $this->fieldDescriptors) {
            $this->initFieldDescriptors($entityName, $id);
        }

        return $this->fieldDescriptors;
    }
1001002
protected static function applyProperties($entityInstance, $data)
    {
        foreach ($data as $property => $value) {
            $funcName = 'set'.ucfirst($property);
            if (method_exists($entityInstance, $funcName)) {
                $entityInstance->$funcName($value);
            }
        }

        return $entityInstance;
    }
1064474
public function toEntity(
        $parent,
        ResourceTransformer $resourceTransformer,
        PropertyResolver $propertyResolver,
        PropertySetter $propertySetter,
        EntityFactory $factory,
        Context $context
    ) {
        $children = $this->getChildrenToProcess();

        $childrenToAdd = [];
        $childrenToEdit = [];

        /**
         * Keep a list of all identifies we've touched, so we can removed those we haven't
         * @var PropertyValueCollection[] $identifiersToKeep
         */
        $identifiersToKeep = [];

        /** @var RelationshipField $field */
        $field = $this->getField();

        foreach ($children as $child) {
            if (!$child) {
                continue;
            }

            /** @var RESTResource $child */

            /** @var bool $isNew */
            $isNew = $child->isNew();

            $childIdentifiers = $child->getProperties()->getIdentifiers();

            $childEntity = null;
            if (!$isNew) {
                $childEntity = $this->getChildByIdentifiers(
                    $resourceTransformer,
                    $propertyResolver,
                    $parent,
                    $childIdentifiers,
                    $context
                );

                if ($childEntity) {
                    $identifiersToKeep[] = $childIdentifiers;
                }
            }

            // Do we just link the resource? In this case we can't edit it right now.
            if ($field->canLinkExistingEntities()) {
                $entity = $factory->resolveLinkedEntity(
                    $parent,
                    $child->getResourceDefinition()->getEntityClassName(),
                    $childIdentifiers->toMap(),
                    $context
                );

                if ($entity) {
                    $childrenToAdd[] = $entity;
                    $identifiersToKeep[] = $childIdentifiers;
                    continue;
                }
            }

            // Is this a new child? We might not be able to add it...
            if (!$childEntity && !$field->canCreateNewChildren()) {
                throw new InvalidPropertyException(
                    "Only existing items can be linked to " . get_class($parent) . "->" . $field->getName()
                );
            }

            $entity = $resourceTransformer->toEntity(
                $child,
                $child->getResourceDefinition(),
                $factory,
                $context,
                $childEntity
            );

            if (!isset($childEntity)) {
                $childrenToAdd[] = $entity;
            } else {
                $childrenToEdit[] = $entity;
            }
        }

        if (count($childrenToAdd) > 0) {
            $this->addChildren(
                $resourceTransformer,
                $propertySetter,
                $parent,
                $this->getField(),
                $childrenToAdd,
                $context
            );
        }

        if (count($childrenToEdit) > 0) {
            $this->editChildren(
                $resourceTransformer,
                $propertySetter,
                $parent,
                $this->getField(),
                $childrenToEdit,
                $context
            );
        }

        // Notify the setter to remove all children that haven't been touched (in the range defined in the context)
        $this->removeAllChildrenExcept(
            $resourceTransformer,
            $propertyResolver,
            $propertySetter,
            $parent,
            $this->getField(),
            $identifiersToKeep,
            $context
        );
    }
537255
private function convertReflectionPropertyToManyToManyAssociationMetadata(
        ReflectionProperty $reflectionProperty,
        array $propertyAnnotations,
        Mapping\ClassMetadata $metadata,
        Mapping\ClassMetadataBuildingContext $metadataBuildingContext
    ) : Mapping\ManyToManyAssociationMetadata {
        $className       = $metadata->getClassName();
        $fieldName       = $reflectionProperty->getName();
        $manyToManyAnnot = $propertyAnnotations[Annotation\ManyToMany::class];
        $assocMetadata   = new Mapping\ManyToManyAssociationMetadata($fieldName);
        $targetEntity    = $manyToManyAnnot->targetEntity;

        $assocMetadata->setTargetEntity($targetEntity);
        $assocMetadata->setCascade($this->getCascade($className, $fieldName, $manyToManyAnnot->cascade));
        $assocMetadata->setOrphanRemoval($manyToManyAnnot->orphanRemoval);
        $assocMetadata->setFetchMode($this->getFetchMode($className, $manyToManyAnnot->fetch));

        if (! empty($manyToManyAnnot->mappedBy)) {
            $assocMetadata->setMappedBy($manyToManyAnnot->mappedBy);
        }

        if (! empty($manyToManyAnnot->inversedBy)) {
            $assocMetadata->setInversedBy($manyToManyAnnot->inversedBy);
        }

        if (! empty($manyToManyAnnot->indexBy)) {
            $assocMetadata->setIndexedBy($manyToManyAnnot->indexBy);
        }

        // Check for JoinTable
        if (isset($propertyAnnotations[Annotation\JoinTable::class])) {
            $joinTableAnnot    = $propertyAnnotations[Annotation\JoinTable::class];
            $joinTableMetadata = $this->convertJoinTableAnnotationToJoinTableMetadata($joinTableAnnot);

            $assocMetadata->setJoinTable($joinTableMetadata);
        }

        // Check for OrderBy
        if (isset($propertyAnnotations[Annotation\OrderBy::class])) {
            $orderByAnnot = $propertyAnnotations[Annotation\OrderBy::class];

            $assocMetadata->setOrderBy($orderByAnnot->value);
        }

        // Check for Id
        if (isset($propertyAnnotations[Annotation\Id::class])) {
            throw Mapping\MappingException::illegalToManyIdentifierAssociation($className, $fieldName);
        }

        $this->attachAssociationPropertyCache($propertyAnnotations, $reflectionProperty, $assocMetadata, $metadata);

        return $assocMetadata;
    }