patch request on relationship

@param ApiRequest $request
@param Model|mixed $resourceModel
@return Model|mixed
@throws \Exception when update failes
165402
public function relatedPatch(ApiRequest $request, $resourceModel)
    {
        $requestModel = $request->asRequestModel();

        $relationshipModel = $this->getRelationshipModel($resourceModel);

        $this->validate($requestModel, $this->getUpdatingRules());

        return $this->updateRelationshipModel($relationshipModel, $requestModel);
    }
572626
def patch_resource(self, session, json_data, api_type, obj_id):
        
        model = self._fetch_model(api_type)
        resource = self._fetch_resource(session, api_type, obj_id,
                                        Permissions.EDIT)
        self._check_json_data(json_data)
        orm_desc_keys = resource.__mapper__.all_orm_descriptors.keys()

        if not ({'type', 'id'} <= set(json_data['data'].keys())):
            raise BadRequestError('Missing type or id')

        if str(json_data['data']['id']) != str(resource.id):
            raise BadRequestError('IDs do not match')

        if json_data['data']['type'] != resource.__jsonapi_type__:
            raise BadRequestError('Type does not match')

        json_data['data'].setdefault('relationships', {})
        json_data['data'].setdefault('attributes', {})

        missing_keys = set(json_data['data'].get('relationships', {}).keys()) \
            - set(resource.__jsonapi_map_to_py__.keys())

        if missing_keys:
            raise BadRequestError(
                '{} not relationships for {}.{}'.format(
                    ', '.join(list(missing_keys)),
                    model.__jsonapi_type__, resource.id))

        attrs_to_ignore = {'__mapper__', 'id'}

        session.add(resource)

        try:
            for key, relationship in resource.__mapper__.relationships.items():
                api_key = resource.__jsonapi_map_to_api__[key]
                attrs_to_ignore |= set(relationship.local_columns) | {key}

                if api_key not in json_data['data']['relationships'].keys():
                    continue

                self.patch_relationship(
                    session, json_data['data']['relationships'][api_key],
                    model.__jsonapi_type__, resource.id, api_key)

            data_keys = set(map((
                lambda x: resource.__jsonapi_map_to_py__.get(x, None)),
                json_data['data']['attributes'].keys()))
            model_keys = set(orm_desc_keys) - attrs_to_ignore

            if not data_keys <= model_keys:
                raise BadRequestError(
                    '{} not attributes for {}.{}'.format(
                        ', '.join(list(data_keys - model_keys)),
                        model.__jsonapi_type__, resource.id))

            for key in data_keys & model_keys:
                setter = get_attr_desc(resource, key, AttributeActions.SET)
                setter(resource, json_data['data']['attributes'][resource.__jsonapi_map_to_api__[key]])  # NOQA
            session.commit()
        except IntegrityError as e:
            session.rollback()
            raise ValidationError(str(e.orig))
        except AssertionError as e:
            # pragma: no cover
            session.rollback()
            raise ValidationError(e.msg)
        except TypeError as e:
            session.rollback()
            raise ValidationError('Incompatible data type')
        return self.get_resource(
            session, {}, model.__jsonapi_type__, resource.id)
924544
public function patchAction( ServerRequestInterface $request )
	{
		if( config( 'shop.authorize', true ) ) {
			$this->authorize( 'admin', [JsonadmController::class, ['admin', 'api']] );
		}

		return $this->createAdmin()->patch( $request, new Response() );
	}
880399
public function patch(Request $request, Fractal $fractal, InputGateContract $inputGate)
    {
        $this->beforeRequest($request, func_get_args());
        $id = $this->parseObjectId($request);
        $model = $this->loadAuthorizeObject($id, 'update');
        $input = $request->json()->all();
        if (!is_array($input) || empty($input)) {
            throw new UnprocessableEntityHttpException("Invalid request body");
        }
        $attributes = $originalAttributes = array_get($input, 'data.attributes', []);
        $context = app('context');
        foreach ($context as $key => $value) {
            unset($attributes[$key]);
        }
        $relationships = array_get($input, 'data.relationships', []);
        $attributes = $inputGate->process($model, $attributes, 'update');
        $validatedRelationshipData = $this->validateRelationshipData($model, $relationships, 'update');
        // do update logic
        if ($model->update($attributes) && $this->saveRelationshipData($validatedRelationshipData)) {
            return $this->respondWithUpdated(
                $fractal->createData(new FractalItem($this->loadAuthorizeObject($id, 'update'), $this->getTransformer(), $this->getResourceKey()))
            );
        }
        
        throw new ServerErrorHttpException("Unable to save object. Try again later.");
    }
1080283
public function update(Request $request, $id)
    {
        // Handle permission
//        $request = $this->handlePermission(__FUNCTION__,$request);
//        if ($request->has('permission_filters')){
//            $filters = $request['permission_filters'];
//        }else{
        $filters = [];
//        }

        // Create Response Model
        $response = new ResponseModel();

        // Filters
        array_push($filters,
            [$this->model->getKeyName(), '=', $id]
        );

        $validationErrors = $this->checkRequestValidation($request, $this->updateValidateArray);
        if ($validationErrors != null) {
            if (env('APP_DEBUG', false)) {
                $response->setData(collect($validationErrors->toArray()));
            }
            $response->setMessage($this->getTrans(__FUNCTION__, 'validation_failed'));
            $response->setStatus(false);
            $response->setError(99);
            return SmartResponse::response($response);

        }

        try {
            // sync many to many relation
            foreach ($this->pivotFields as $pivotField) {
                if (collect($request[$pivotField])->count()) {
                    $pivotMethod = (new StringHelper())->toCamel($pivotField);
                    $this->model->findOrFail($id)->$pivotMethod()->sync(json_decode($request[$pivotField], true));
                }
            }
            //get result of update
            $result = $this->model->where($filters)->firstOrFail()->update($request->all());

            // return response
            $response->setData($this->model
                ->where($filters)
                ->with(collect($this->updateLoad)->count() == 0 ? $this->indexLoad : $this->updateLoad)
                ->get());
            $response->setMessage(
                $this->getTrans(__FUNCTION__, 'successful1') .
                $result .
                $this->getTrans(__FUNCTION__, 'successful2')
            );

        } catch (ModelNotFoundException $exception) {
            $response->setStatus(false);
            $response->setMessage($this->getTrans(__FUNCTION__, 'model_not_found'));
            $response->setError($exception->getCode());
            if (env('APP_DEBUG', false)) {
                $response->setData(collect($exception->getMessage()));
            }

        } catch (QueryException $exception) {
            $response->setStatus(false);
            $response->setMessage($this->getTrans(__FUNCTION__, 'failed'));
            $response->setError($exception->getCode());
            if (env('APP_DEBUG', false)) {
                $response->setData(collect($exception->getMessage()));
            }

        }

        return SmartResponse::response($response);
    }
20714
public function patchAction($id, Request $request)
    {
        if (!$this->isGranted('IS_AUTHENTICATED_FULLY')) {
            throw new InsufficientAuthenticationException('You must be authenticated to view users');
        }
        $actionFound = false;

        $operations = $request->request->all();

        try {
            (new OperationSyntaxValidator())->validate($operations);
        } catch (InvalidOperationSyntaxException $e) {
            throw new BadRequestHttpException('operation invalid syntax: '.$e->getMessage());
        }

        $entity_patcher = new EntityPatcher(new RightManager($this->getSerializer()->getMetadataFactory()));

        foreach ($operations as $key => $operation) {
            if ('/email' === $operation['path']) {
                $actionFound = $this->patchUserIdentity($id, $operations);
            } elseif ('/groups' === $operation['path']) {
                $actionFound = $this->patchUserGroups($id, $operations);
            } elseif ('/password' === $operation['path']) {
                $actionFound = $this->patchUserPassword($id, $operations);
            } elseif ('/activated' === $operation['path']) {
                $actionFound = $this->patchUserStatus($id, $operations);
            }
        }

        if ($actionFound) {
            return new Response("", 204);
        } else {
            return $this->create404Response('Action not found');
        }
    }
416963
public function patch($model, $data)
    {
        try {
            $resource = $model->update($data);
        } catch (\Exception $e) {
            // Check for QueryException - if so, we may want to display a more meaningful message, or help with
            // development debugging
            if ($e instanceof QueryException) {
                if (stristr($e->getMessage(), 'duplicate')) {
                    throw new ConflictHttpException('Duplicate entry for ' . $this->model);
                } elseif (Config::get('api.debug') === true) {
                    throw $e;
                }
            }

            // Default HTTP exception to use for storage errors
            $errorMessage = 'Unexpected error trying to store this resource.';

            if (Config::get('api.debug') === true) {
                $errorMessage .= ' ' . $e->getMessage();
            }

            throw new UnprocessableEntityHttpException($errorMessage);
        }

        return $resource;
    }
220129
public function update(
        ItemsServiceContract $resourceService,
        SaveItemRequestContract $request,
        int $id = 0
    ): SaveResponseContract {
        return $this->save($resourceService, $request, $id);
    }
138566
public function updateTreeAction(Request $request)
    {
        /** @var Request $request */
        $nodes = $request->get('nodes') ? $request->get('nodes') : [];

        $admin = $this->get('networking_init_cms.admin.tag');

        $validator = $this->get('validator');
        try {
            foreach ($nodes as $node) {
                if (!$node['id']) {
                    continue;
                }
                /** @var $tag Tag */
                $tag = $admin->getObject($node['id']);
                if ($node['parent_id']) {
                    $parent = $admin->getObject($node['parent_id']);
                    $tag->setParent($parent);
                } else {
                    $tag->setParent(null);
                }

                $tag->setLevel($node['depth'] + 1);

                $errors = $validator->validate($tag);
                if (count($errors) > 0) {
                    throw new ValidatorException();
                }

                $this->admin->update($tag);
            }

            $response = ['status' => 'success', 'message' => $this->admin->trans('info.tag_sorted')];
        } catch (\Exception $e) {
            $response = ['status' => 'error', 'message' => $this->admin->trans('info.tag_sorted_error')];
        }

        return $this->renderJson($response);
    }
1200178
public function updateManyToManyAction(Request $request)
    {
        /** @var AbstractAdmin $admin */
        $admin = $this->getAdmin();

        $admin->checkAccess('edit');

        $em = $admin->getDoctrine()->getManager();

        $ids = $request->request->get('value');
        $id = $request->request->get('pk');

        $field = $request->request->get('field');

        $object = $admin->getObject($id);

        /** @var \Sonata\DoctrineORMAdminBundle\Model\ModelManager $mm */
        $mm = $admin->getModelManager();

        $ClassMetadata = $mm->getMetadata($admin->getClass());

        $associationMapping = $ClassMetadata->getAssociationMapping($field);

        $items = $em->getRepository($associationMapping['targetEntity'])->findBy([
            'id' => $ids,
        ]);

        \call_user_func([$object, 'set' . ucfirst($field)], $items);

        $admin->update($object);

        $result = [
        ];

        $associationAdmin = $admin->getAdminByClass($associationMapping['targetEntity']);

        foreach ($items as $item) {
            if (method_exists($item, 'getId') && method_exists($item, 'getName')) {
                $result[] = [
                    'id' => $item->getId(),
                    'label' => $item->getName(),
                    'edit_url' => $associationAdmin->generateObjectUrl('edit', $item),
                ];
            }
        }

        return new JsonResponse([
            'items' => $result,
        ]);
    }
1008460
public function update(Request $request, $id)
    {
        /** @var \SymfonyId\AdminBundle\Configuration\ConfiguratorFactory $configuratorFactory */
        $configuratorFactory = $this->getConfiguratorFactory($this->getClassName());
        /** @var CrudConfigurator $crudConfigurator */
        $crudConfigurator = $configuratorFactory->getConfigurator(CrudConfigurator::class);

        $this->isGrantedOr404Error($crudConfigurator, Constants::ACTION_UPDATE);

        /** @var ModelInterface $model */
        $model = $this->findOr404Error($id);
        $form = $crudConfigurator->getForm($model, 'PUT');

        return $this->save($request, $form, $crudConfigurator);
    }
567955
public function handleRequest(SS_HTTPRequest $request, DataModel $model) {
        return $this->original()->handleRequest($request, $model);
    }
1161830
public function updateFile($request, $match)
    {
        // Get data
        $resource = Pluf_Shortcuts_GetObjectOr404('Tenant_Resource', $match['modelId']);
        // Do action
        if (array_key_exists('file', $request->FILES)) {
            $extra = array(
                'model' => $resource
            );
            $form = new Tenant_Form_ResourceUpdate(array_merge($request->REQUEST, $request->FILES), $extra);
            $resource = $form->save();
            return $resource;
        } else {
            $myfile = fopen($resource->getAbsloutPath(), "w") or die("Unable to open file!");
            $entityBody = file_get_contents('php://input', 'r');
            fwrite($myfile, $entityBody);
            fclose($myfile);
            $resource->update();
        }
        return $resource;
    }
696407
public function update($id, Request $request)
    {
        $entity = $this->getEntityById($id);

        if (!$entity) {
            return $this->response(null, Response::HTTP_NOT_FOUND);
        }

        $params = $request->only($this->fillable);

        $result = $this->manager->update($entity, $params);

        if (!$result->ok()) {
            return $this->response(['errors' => $result->getSimpleErrors()], Response::HTTP_BAD_REQUEST);
        }

        return $this->response($this->serialize($result->getResource(), $request), Response::HTTP_OK);
    }
1368746
public function update(Request $request, $id)
    {
        /** @noinspection PhpUndefinedMethodInspection */
        $request->validate(['name' => 'required|max:128']);
        /** @noinspection PhpUndefinedMethodInspection */
        $location = Location::findOrFail($id);
        $location->name = $request->name;
        $this->authorize('update', $location);
        /** @noinspection PhpUndefinedMethodInspection */
        $location->save();
        return fractal($location, new LocationTransformer())
            ->withResourceName('location')
            ->respond();

    }
754611
def _api_model_patch_replace(conn, restApiId, modelName, path, value):
    '''
    
    '''
    response = conn.update_model(restApiId=restApiId, modelName=modelName,
                                 patchOperations=[{'op': 'replace', 'path': path, 'value': value}])
    return response
801020
public function patch($parentUuid, $uuid, Request $request)
    {
        // Check parent exists
        $parentModel = static::$parentModel;
        $parentResource = $parentModel::findOrFail($parentUuid);

        // Authorize ability to update children models for parent
        $this->authorizeUserAction($this->parentAbilitiesRequired['update'], $parentResource);

        // Get resource
        $model = new static::$model;
        $resource = static::$model::findOrFail($uuid);

        // Check resource belongs to parent
        if ($resource->getAttribute(($parentResource->getKeyName())) != $parentResource->getKey()) {
            throw new AccessDeniedHttpException('Resource \'' . class_basename(static::$model) . '\' with given UUID ' . $uuid . ' does not belong to ' .
                'resource \'' . class_basename(static::$parentModel) . '\' with given UUID ' . $parentUuid . '; ');
        }

        $this->authorizeUserAction('update', $resource);

        // Validate the resource data with the updates
        $this->restfulService->validateResourceUpdate($resource, $request->input());

        // Patch model
        $this->restfulService->patch($resource, $request->input());

        // Get updated resource
        $resource = $model::with($model::$localWith)->where($model->getKeyName(), '=', $uuid)->first();

        if ($this->shouldTransform()) {
            $response = $this->response->item($resource, $this->getTransformer());
        } else {
            $response = $resource;
        }

        return $response;
    }