/** * Update an existing user * * @param int $id * @param HttpFoundation\Request $request * @return HttpFoundation\JsonResponse|HttpFoundation\Response */ public function putIndex($id, HttpFoundation\Request $request) { $this->log->addDebug(print_r($request, true), ['namespace' => 'HackTheDinos\\Controllers\\User', 'method' => 'putIndex', 'type' => 'request']); //If this request validated then the userId should be in the request. $userId = $request->request->get('userId'); if ($userId === $id) { $user = $this->repo->getById($userId); $this->log->addDebug(print_r($user, true), ['namespace' => 'HackTheDinos\\Controllers\\User', 'method' => 'putIndex', 'type' => 'user']); //It's almost impossible for this to happen but it's good defensive coding. if (!empty($user)) { $user = $this->converter->entityArrayToModel(json_decode($request->getContent(), true), new Models\User()); $user->id = $userId; if (isset($user->password)) { $user->password = password_hash($user->password, PASSWORD_DEFAULT); } if ($this->repo->save($user)) { $this->log->addInfo('Updated user', ['namespace' => 'HackTheDinos\\Controllers\\User', 'method' => 'putIndex', 'user' => (array) $user]); return new HttpFoundation\JsonResponse($user, 200); } //Otherwise we couldn't save the user for some reason $this->log->addWarning('Unable to update user', ['namespace' => 'HackTheDinos\\Controllers\\User', 'method' => 'putIndex', 'request' => $request->getContent(), 'user' => (array) $user]); return new HttpFoundation\Response('Bad Request', 400); } } //We didn't find a user to update. $this->log->addWarning('No user found', ['namespace' => 'HackTheDinos\\Controllers\\User', 'method' => 'putIndex', 'id' => $id, 'userId' => $userId]); return new HttpFoundation\Response('Not Found', 404); }