@param JsonApiResource $entity
@param string          $field
@param object          $item

@return mixed
@throws RestException
187992
protected function addRelationItem(JsonApiResource $entity, $field, $item)
    {
        $adder = 'add' . ucfirst($field);

        if (!method_exists($entity, $adder)) {
            throw RestException::missingAdder($entity, $field, $adder);
        }

        return $entity->$adder($item);
    }
108345
private function processAttributes($data, ApiItemInterface $item)
    {
        $result = true;
        try {
            if (isset($data['attributes']) && is_array($data['attributes'])) {
                /** @var ItemAttribute $itemAttribute */
                $get = function ($itemAttribute) {
                    return $itemAttribute->getId();
                };

                $delete = function ($itemAttribute) use ($item) {
                    // Delete item.
                    $this->em->remove($itemAttribute);
                };

                /** @var ItemAttribute $itemAttribute */
                $update = function ($itemAttribute, $matchedEntry) use ($item) {
                    $itemAttribute->setAttribute($matchedEntry['attribute']);
                    $itemAttribute->setValue($matchedEntry['value']);

                    return $itemAttribute ? true : false;
                };

                $add = function ($itemData) use ($item) {
                    $itemAttribute = new ItemAttribute();
                    $itemAttribute->setAttribute($itemData['attribute']);
                    $itemAttribute->setValue($itemData['value']);
                    $itemAttribute->setItem($item->getEntity());
                    $this->em->persist($itemAttribute);

                    return $item->addAttribute($itemAttribute);
                };

                $result = $this->processSubEntities(
                    $item->getAttributes(),
                    isset($data['attributes']) ? $data['attributes'] : [],
                    $get,
                    $add,
                    $update,
                    $delete
                );
            }
        } catch (\Exception $e) {
            throw new ItemException('Error while creating attributes: ' . $e->getMessage());
        }

        return $result;
    }
966024
public function itemCreate(Item $item)
    {
        $response = $this->getGuzzleClient()
            ->post(
                '/items',
                array_merge($this->setQuery(), $this->setBody($item))
            );

        return $this->serializer->deserialize(
            $response->getBody()->getContents(),
            Item::class,
            'json'
        );
    }
725777
public function itemRelist($item_id, $fields)
    {
        // TODO: Tests
        $response = $this->getGuzzleClient()
            ->post(
                '/items/' . $item_id . '/relist',
                array_merge(
                    $this->setQuery(),
                    $this->setBodyArray($fields)
                )
            );

        return $this->serializer->deserialize(
            $response->getBody()->getContents(),
            Item::class,
            'json'
        );
    }
1069878
protected function manageFieldDatatableJson($entity, $field, $reversedField, $type = 'one')
    {
        if ($entity == null || $field == null || $this->has($this->route_name.'_'.$field.'_datatable') == false) {
            throw new \Exception('All the parameters are not correctly set');
        }

        $postDatatable = $this->get($this->route_name.'_'.$field.'_datatable');
        $postDatatable->buildDatatable(['entity' => $entity]);

        if (method_exists($postDatatable, 'addLineFormatter') && method_exists($entity, 'getId')) {
            $postDatatable->addLineFormatter(function ($ligne) use ($entity) {
                $ligne['entity_id'] = $entity->getId();

                return $ligne;
            });
        }

        $datatable = $this->get('sg_datatables.query')->getQueryFrom($postDatatable);

        $entityName = $this->entity_name;

        if ($type === 'one') {
            $datatable->addWhereAll(function (QueryBuilder $qb) use ($entity, $entityName, $reversedField) {
                $qb
                    ->andWhere($qb->getRootAliases()[0].'.'.$reversedField." = :$entityName")
                    ->setParameter("$entityName", $entity)
                ;
            });
        } elseif ($type === 'many') {
            $datatable->addWhereAll(function (QueryBuilder $qb) use ($entity, $entityName, $reversedField) {
                $qb
                    ->join($qb->getRootAliases()[0].'.'.$reversedField, 'reverseField')
                    ->andWhere('reverseField.id = :'.$entityName.'_id')
                    ->setParameter($entityName.'_id', $entity->getId())
                ;
            });
        }

        return $datatable->getResponse();
    }
67962
protected function CreateObject($methodKey, $entity, $responseClassName = null, $entityId = null, $subEntityId = null, $idempotencyKey = null)
    {
        if (is_null($entityId)) {
            $urlMethod = $this->GetRequestUrl($methodKey);
        } elseif (is_null($subEntityId)) {
            $urlMethod = sprintf($this->GetRequestUrl($methodKey), $entityId);
        } else {
            $urlMethod = sprintf($this->GetRequestUrl($methodKey), $entityId, $subEntityId);
        }

        $requestData = null;
        if (!is_null($entity)) {
            $requestData = $this->BuildRequestData($entity);
        }

        $rest = new RestTool(true, $this->_root);
        $response = $rest->Request($urlMethod, $this->GetRequestType($methodKey), $requestData, $idempotencyKey);

        if (!is_null($responseClassName)) {
            return $this->CastResponseToEntity($response, $responseClassName);
        }

        return $response;
    }
1261934
protected function wrapField($item, $field)
    {
        $formGroup =
            <<<EOD
            <div class="form-group {{ \$errors->has('%1\$s') ? 'has-error' : ''}}">
                {!! Form::label('%1\$s', '%2\$s: ', ['class' => 'col-sm-3 control-label']) !!}
                <div class="col-sm-6">
                    %3\$s
                    {!! \$errors->first('%1\$s', '<p class="help-block">:message</p>') !!}
                </div>
            </div>\n
EOD;

        return sprintf($formGroup, $item['name'], ucwords(strtolower(str_replace('_', ' ', $item['name']))), $field);
    }
606411
protected function loadAssociationObjectsToEntity(array $item, $entity)
    {
        foreach ($this->entityMetadata->getAssociationMappings() as $associationMapping) {

            $value = null;
            if (isset($item[$associationMapping['fieldName']]) && !is_object($item[$associationMapping['fieldName']])) {
                $value = $this->entityManager->getReference($associationMapping['targetEntity'], $item[$associationMapping['fieldName']]);
            }

            if (null === $value) {
                continue;
            }

            $setter = 'set' . ucfirst($associationMapping['fieldName']);
            $this->setValue($entity, $value, $setter);
        }
    }
1001474
private function getResourceClass($item, ?string $resourceClass, ResolveInfo $info, string $errorMessage = 'Resolver only handles items of class %s but retrieved item is of class %s.'): ?string
    {
        if (null === $item) {
            return $resourceClass;
        }

        $itemClass = $this->getObjectClass($item);

        if (null === $resourceClass) {
            return $itemClass;
        }

        if ($resourceClass !== $itemClass) {
            throw Error::createLocatedError(sprintf($errorMessage, (new \ReflectionClass($resourceClass))->getShortName(), (new \ReflectionClass($itemClass))->getShortName()), $info->fieldNodes, $info->path);
        }

        return $resourceClass;
    }
895613
public static function missingRemover($entity, $field, $remover)
    {
        $source = [
            'entity' => ClassUtils::getClass($entity),
            'remover' => $remover
        ];

        if ($entity instanceof JsonApiResource) {
            $source['pointer'] = $entity->getResourceKey().'.'.$field;
        }

        return static::createUnprocessable('Missing remover method.')
            ->error('missing-remover', $source, 'Missing collection remover.');
    }
6834
public function refill(Item $item, $field)
    {
        if (!($url = $this->getSourceForFill($item))) {
            return $item;
        }

        // get data
        preg_match(Filler::REG_ITEM_ID, $url, $match);
        $path = str_replace('#ID#', $match['id'], Filler::FILL_URL);
        $body = $this->browser->get($path);

        switch ($field) {
            case self::FIELD_DATE_END:
                if ($body['released_on']) {
                    $item->setDateEnd(new \DateTime($body['released_on']));
                }
                break;
            case self::FIELD_DATE_PREMIERE:
                $item->setDatePremiere(new \DateTime($body['aired_on']));
                break;
            case self::FIELD_DURATION:
                $item->setDuration($body['duration']);
                break;
            case self::FIELD_EPISODES_NUMBER:
                $ep_num = $body['episodes_aired'] ? $body['episodes_aired'] : $body['episodes'];
                $item->setEpisodesNumber($ep_num.($body['ongoing'] ? '+' : ''));
                break;
            case self::FIELD_GENRES:
                $new_item = $this->filler->setGenres(new Item(), $body);
                foreach ($new_item->getGenres() as $new_genre) {
                    $item->addGenre($new_genre);
                }
                break;
            case self::FIELD_IMAGES:
                $this->filler->setImages($item, $body);
                break;
            case self::FIELD_NAMES:
                $new_item = $this->filler->setNames(new Item(), $body);
                // set main name in top of names list
                $names = $new_item->getNames()->toArray();
                array_unshift($names, (new Name())->setName($new_item->getName()));
                foreach ($names as $new_name) {
                    $item->addName($new_name);
                }
                break;
            case self::FIELD_SOURCES:
                $new_item = $this->filler->setSources(new Item(), $body);
                foreach ($new_item->getSources() as $new_source) {
                    $item->addSource($new_source);
                }
                break;
            case self::FIELD_STUDIO:
                $this->filler->setStudio($item, $body);
                break;
            case self::FIELD_SUMMARY:
                $item->setSummary($body['description']);
                break;
        }

        return $item;
    }
710347
private static function isSortable($item, $field) {
        if (is_array($item))
            return array_key_exists($field, $item);
        elseif (is_object($item))
            return isset($item->$field) || property_exists($item, $field);
        else
            return false;
    }
102408
private function processItem($item) : JsonRpcResponse
    {
        try {
            if ($item instanceof \Exception) {
                // Exception will be caught just below and converted to response
                throw $item;
            }

            return $this->jsonRpcRequestHandler->processJsonRpcRequest($item);
        } catch (\Exception $exception) {
            return $this->exceptionHandler->getJsonRpcResponseFromException(
                $exception,
                $item instanceof JsonRpcRequest ? $item : null
            );
        }
    }
1061137
public function selectSearch(Request $request, ModelConfigurationInterface $model, $field, $id = null)
    {
        $form = $this->getModelLogic($model, $id);

        if ($form instanceof JsonResponse) {
            return $form;
        }

        /** @var DependentSelect $element */
        $element = $form->getElement($field);

        if (is_null($element)) {
            return new JsonResponse([
                'message' => 'Element not found',
            ], 404);
        }

        $field = $request->field;
        $model = new $request->model;

        if ($request->q && is_object($model)) {
            return new JsonResponse(
                $model::where($request->search, 'like', "%{$request->q}%")
                    ->get()
                    ->map(function (Model $item) use ($field) {
                        return [
                            'tag_name'    => $item->{$field},
                            'id'          => $item->id,
                            'custom_name' => $item->custom_name,
                        ];
                    })
            );
        }
    }
1356581
public function newObject($entity, $jsonObject)
	{
		$retValue = array();

		try{
			$m = new MongoDB\Driver\Manager($this->url);
			$bulk = new MongoDB\Driver\BulkWrite;

			$id = $bulk->insert($jsonObject);

			$mCol = $this->db . "."  . $entity;

			$m->executeBulkWrite($mCol, $bulk);

			$retValue = $this->findObject($entity, $id);	
		}
		catch(Exception $e) {
			$this->_log->addError($e->getMessage());
		}

		return $retValue;
	}
229470
protected function getApiEntity(CollectionInterface $entity, $locale, $entities = null, $breadcrumbEntities = null)
    {
        $apiEntity = new Collection($entity, $locale);

        $children = null;

        if (null !== $entities) {
            $children = [];
            foreach ($entities as $possibleChild) {
                if (null !== ($parent = $possibleChild->getParent()) && $parent->getId() === $entity->getId()) {
                    $children[] = $this->getApiEntity($possibleChild, $locale, $entities);
                }
            }
        }

        $apiEntity->setChildren($children);
        if (null !== $entity->getParent()) {
            $apiEntity->setParent($this->getApiEntity($entity->getParent(), $locale));
        }

        if (null !== $breadcrumbEntities) {
            $this->setBreadcrumbToCollection($apiEntity, $locale, $breadcrumbEntities);
        }

        if ($entity && $entity->getId()) {
            $apiEntity->setMediaCount($this->collectionRepository->countMedia($entity));
            $apiEntity->setSubCollectionCount($this->collectionRepository->countSubCollections($entity));
        }

        return $this->addPreview($apiEntity);
    }
107658
public static JsonArray getArray(JsonObject object, String field) {
        final JsonValue value = object.get(field);
        throwExceptionIfNull(value, field);
        return value.asArray();
    }