/** * Create new school * * @param Request $r * @return array * @throws InvalidDatabaseOperationException * @throws InvalidParameterException */ public static function apiCreate(Request $r) { self::authenticateRequest($r); Validators::isStringNonEmpty($r["name"], "name"); Validators::isNumber($r["state_id"], "state_id", false); if (!is_null($r["state_id"])) { try { $r["state"] = StatesDAO::getByPK($r["state_id"]); } catch (Exception $e) { throw new InvalidDatabaseOperationException($e); } if (is_null($r["state"])) { throw new InvalidParameterException("parameterNotFound", "state"); } } // Create school object $school = new Schools(array("name" => $r["name"], "state_id" => $r["state_id"])); $school_id = 0; try { $existing = SchoolsDAO::findByName($r["name"]); if (count($existing) > 0) { $school_id = $existing[0]->getSchoolId(); } else { // Save in db SchoolsDAO::save($school); $school_id = $school->getSchoolId(); } } catch (Exception $e) { throw new InvalidDatabaseOperationException($e); } return array("status" => "ok", "school_id" => $school_id); }
/** * */ public function testCreateSchoolDuplicatedName() { $user = UserFactory::createUser(); $r = new Request(array('auth_token' => $this->login($user), 'name' => Utils::CreateRandomString())); // Call api $response = SchoolController::apiCreate($r); $this->assertEquals('ok', $response['status']); $this->assertEquals(1, count(SchoolsDAO::findByName($r['name']))); // Call api again $response = SchoolController::apiCreate($r); $this->assertEquals('ok', $response['status']); $this->assertEquals(1, count(SchoolsDAO::findByName($r['name']))); }