Example #1
0
 /**
  * PUT method: Update information about user
  *
  * @param Request $request
  * @throws Exception
  * @return mixed
  */
 public function put($request)
 {
     switch (count($request->url_elements)) {
         case 2:
             // Guest - throw Exception
             if (Application::isGuest()) {
                 throw new Exception("Unknown request.", 500);
             }
             // Don't have permissions - throw Exception
             if (!Application::isAdmin() && Application::currentUser()->id != $request->url_elements[1]) {
                 throw new Exception("You don't have required permissions to update this user.", 403);
             }
             // Change login to exists one - throw Exception
             if ($request->json->login && count(User::find('all', array('conditions' => array('login=?', $request->json->login)))) > 0) {
                 throw new Exception("Change login failed. User with this login already exists.", 500);
             }
             // Like success - update user information & return
             $user = User::find_by_id($request->url_elements[1]);
             if ($user) {
                 $user->login = $request->json->login ? $request->json->login : $user->login;
                 $user->password = $request->json->password ? Common::getPasswordHash($request->json->password, $request->json->login) : $user->password;
                 $user->save();
                 return json_decode($user->to_json(array('except' => 'password')));
             } else {
                 throw new Exception("User not found.", 404);
             }
         default:
             throw new Exception("Unknown request.", 500);
     }
 }