Example #1
0
 /**
  * Adds a choice.
  *
  * Called when this component receives an HTTP POST request to
  * (/$preChoice(/$preForm(/$preExercise)))/choice(/).
  *
  * @param int $preForm A optional prefix for the Form table.
  * @param int $preExercise A optional prefix for the Exercise table.
  * @param int $choiceid The id of the choice.
  */
 public function addChoice($preChoice = '', $preForm = '', $preExercise = '')
 {
     $this->loadConfig($preChoice, $preForm, $preExercise);
     $preChoice = ($preChoice === '' ? '' : '_') . $preChoice;
     $preForm = ($preForm === '' ? '' : '_') . $preForm;
     $preExercise = ($preExercise === '' ? '' : '_') . $preExercise;
     Logger::Log('starts POST AddChoice', LogLevel::DEBUG);
     $preChoice = DBJson::mysql_real_escape_string($preChoice);
     $preForm = DBJson::mysql_real_escape_string($preForm);
     $preExercise = DBJson::mysql_real_escape_string($preExercise);
     // decode the received choice data, as an object
     $insert = Choice::decodeChoice($this->_app->request->getBody());
     // always been an array
     $arr = true;
     if (!is_array($insert)) {
         $insert = array($insert);
         $arr = false;
     }
     // this array contains the indices of the inserted objects
     $res = array();
     foreach ($insert as $in) {
         // starts a query, by using a given file
         $result = DBRequest::getRoutedSqlFile($this->query, dirname(__FILE__) . '/Sql/AddChoice.sql', array('object' => $in, 'preChoice' => $preChoice, 'preForm' => $preForm, 'preExercise' => $preExercise));
         // checks the correctness of the query
         if ($result['status'] >= 200 && $result['status'] <= 299) {
             $queryResult = Query::decodeQuery($result['content']);
             // sets the new auto-increment id
             $obj = new Choice();
             $course = Course::ExtractCourse($queryResult[count($queryResult) - 1]->getResponse(), true);
             $obj->setChoiceId($course->getId() . '_' . $queryResult[count($queryResult) - 2]->getInsertId());
             $res[] = $obj;
             $this->_app->response->setStatus(201);
             if (isset($result['headers']['Content-Type'])) {
                 $this->_app->response->headers->set('Content-Type', $result['headers']['Content-Type']);
             }
         } else {
             Logger::Log('POST AddChoice failed', LogLevel::ERROR);
             $this->_app->response->setStatus(isset($result['status']) ? $result['status'] : 409);
             $this->_app->response->setBody(Choice::encodeChoice($res));
             $this->_app->stop();
         }
     }
     if (!$arr && count($res) == 1) {
         $this->_app->response->setBody(Choice::encodeChoice($res[0]));
     } else {
         $this->_app->response->setBody(Choice::encodeChoice($res));
     }
 }