function create_answer()
 {
     Auth::checkLoggedIn();
     $question = Question::fromId(Input::get('questionid'));
     if (!$question->canAnswer(Auth::getUser())) {
         throw new Exception('You are not allowed to answer this question.');
     }
     $answer = QuestionAnswer::create($question, Auth::getUser(), Input::get('text'));
     View::renderJson($answer->getContext(Auth::getUser()));
 }
Esempio n. 2
0
 /**
  * Creates a new question.
  * @param User $creator The asker.
  * @param Entry $entry The entry it belongs to.
  * @param string $title The title for the question being asked.
  * @param string $text The text of the question being asked.
  * @param boolean $private Whether or not this question is private.
  * @throws Exception
  */
 public static function create(User $creator, Entry $entry, $title, $text, $private = false)
 {
     $private = boolval($private);
     // Start the transaction
     Database::connection()->beginTransaction();
     // Do the database insert
     $query = Database::connection()->prepare('INSERT INTO question (entryid, is_private, created_at, title) VALUES (?, ?, ?, ?)');
     $query->bindValue(1, $entry->getEntryId(), PDO::PARAM_INT);
     $query->bindValue(2, $private, PDO::PARAM_BOOL);
     $query->bindValue(3, time(), PDO::PARAM_INT);
     $query->bindValue(4, $title, PDO::PARAM_STR);
     if (!$query->execute()) {
         Database::connection()->rollBack();
         throw new Exception('Question could not be inserted into the database.');
     }
     // Get the question we just made
     $question = self::fromId(Database::connection()->lastInsertId());
     // Now create the first answer to the question
     $answer = null;
     try {
         // Create the answer
         $answer = QuestionAnswer::create($question, $creator, $text);
     } catch (Exception $ex) {
         // If it fails we roll back
         Database::connection()->rollBack();
         throw $ex;
     }
     // Now set the first answer for the question
     $query = Database::connection()->prepare('UPDATE question SET first_answer = ? WHERE questionid = ?');
     $query->bindValue(1, $answer->getAnswerId(), PDO::PARAM_INT);
     $query->bindValue(2, $question->getQuestionId(), PDO::PARAM_INT);
     if (!$query->execute()) {
         Database::connection()->rollBack();
         throw new Exception('Could not set first answer field.');
     }
     // Commit to the database and set the question as changed
     Database::connection()->commit();
     $question->changed();
     // Return the created question
     return $question;
 }