/** * Tests the notFound * * @issue T169 * @author Nikos Dimopoulos <*****@*****.**> * @since 2012-11-06 */ public function testMicroNotFoundT169() { $this->specify("MVC Micro notFound doesn't work", function () { $handler = new \RestHandler(); $app = new Micro(); $app->get("/api/site", [$handler, "find"]); $app->post("/api/site/save", [$handler, "save"]); $flag = false; $app->notFound(function () use(&$flag) { $flag = true; }); $_SERVER["REQUEST_METHOD"] = "GET"; $_GET["_url"] = "/fourohfour"; $app->handle(); expect($flag)->true(); }); }
} return $response; }); // Add a new robot $app->post('/api/robots', function () use($app) { $robot = $app->request->getJsonRawBody(); $phql = "INSERT INTO Robots (name, type, year) VALUES (:name:, :type:, :year:)"; $status = $app->modelsManager->executeQuery($phql, array('name' => $robot->name, 'type' => $robot->type, 'year' => $robot->year)); // Create a response $response = new Response(); // Check if the insertion was succesful if ($status->success == true) { // Change the HTTP status $response->setStatusCode(201, "Created"); $robot->id = $status->getModel()->id; $response->setJsonContent(array('status' => 'OK', 'data' => $robot)); } else { // Change the HTTP status $response->setStatusCode(409, "Conflict"); // Send errors to the client $errors = array(); foreach ($status->getMessage() as $message) { $errors[] = $message->getMessage(); } $response->setJsonContent(array('status' => 'ERROR', 'messages' => $errors)); } return $response; }); // Updates robots based on primary key $app->put('/api/robots/{id:[0-9]+}', function ($id) use($app) { $robot = $app->request->getJsonRawBody(); $phql = "UPDATE Robots SET name = :name:, type = :type:, year = :year: WHERE id = :id:";
$app->post('/image/metadata/{id:[0-9]+}', function ($id) use($app) { $request = new Phalcon\Http\Request(); $filter = new Phalcon\Filter(); $user = new Users(); $data = $request->getPost('tags', null, false); $image = Images::findFirst("id = '" . $id . "'"); $tags = []; /** * Save each tag * This is done by: * 1) Getting/creating the tag * 2) Creating an imageTag * 3) Saving the imageTag */ foreach ($data as $tagRow) { $name = $filter->sanitize($tagRow['name'], 'string'); //Get tag if it exists already $tag = Tags::findFirst("name = '" . $name . "' AND category_id = '" . $tagRow['category_id'] . "'"); if (!$tag) { $tag = new Tags(); } $tag->name = $name; $tag->category_id = $tagRow['category_id']; //If the tag could not be saved, dump the error messages if (!$tag->save()) { echo 'could not save tag.'; var_dump($tagRow); var_dump($tag->getMessages()); $app->response->setStatusCode('500'); $app->response->send(); } $tag->refresh(); //Create an imageTag for each tag $imagesTags = new ImagesTags(); $imagesTags->tag_id = $tag->id; $imagesTags->image_id = $image->id; $imagesTags->x = $tagRow['x']; $imagesTags->y = $tagRow['y']; $imagesTags->user_id = $user->getFbId(); //If the imageTag could not be saved, dump the error message if (!$imagesTags->save()) { var_dump($imagesTags->getMessages()); $app->response->setStatusCode('500'); $app->response->send(); } $tags[] = $tag; } $image->imagesTags->tags = $tags; //There was an error saving the tags. Dump the error message if (!$image->save()) { var_dump($image->getMessages()); $app->response->setStatusCode('500'); $app->response->send(); } //Return status code 200 if all went well $app->response->setStatusCode('200'); $app->response->setJsonContent([]); $app->response->send(); });
return $response; }); // Adds a new product $app->post('/api/products', function () use($app) { $product = $app->request->getJsonRawBody(); $phql = "INSERT INTO Products (name, price, in_stock) VALUES (:name:, :price:, :in_stock:)"; //table name $status = $app->modelsManager->executeQuery($phql, array('name' => $product->name, 'price' => $product->price, 'in_stock' => $product->in_stock)); // create a response $response = new Response(); // check if insertion was successful if ($status->success() == true) { // change the http status $response->setStatusCode(201, "Created"); $product = $status->getModel()->id; $response->setJsonContent(array('status' => 'OK', 'data' => $product)); } else { // change the http status $response->setStatusCode(409, "Conflict"); // send errors to client $errors = array(); foreach ($status->getMessages() as $message) { $errors[] = $message->getMessage(); } $response->setJsonContent(array('status' => 'ERROR', 'messages' => $errors)); } return $response; }); // Updates products based on primary key $app->put('/api/products/{id:[0-9]+}', function ($id) use($app) { $product = $app->request->getJsonRawBody();
<?php use Phalcon\Mvc\Micro; $app = new Micro(); $app->get('/', function () { echo "<h1>Welcome!</h1>"; }); $app->get('/say/hello/{name}', function ($name) use($app) { echo "<h1>Hello! {$name}</h1>"; echo "Your IP Address is ", $app->request->getClientAddress(); }); $app->post('/store/something', function () use($app) { $name = $app->request->getPost('name'); echo "<h1>Hello! {$name}</h1>"; }); $app->notFound(function () use($app) { $app->response->setStatusCode(404, "Not Found")->sendHeaders(); echo 'This is crazy, but this page was not found!'; }); $app->handle();
return new PdoMysql(array("host" => "localhost", "username" => "root", "password" => "", "dbname" => "new-encounter")); }); $app = new Micro($di); $app->get('/', function () { echo "Singou Encounter Back End API Server"; }); $app->get('/token', function () { return router('User', 'login', func_get_args()); }); $app->delete('/token', function () { return router('User', 'logout', func_get_args()); }); $app->get('/lottery', function () { return router(''); }); $app->post('/lottery', function () { return router(''); }); $app->notFound(function () { return router('Base', 'error', array('0001', 404)); }); $app->handle(); } catch (Exception $e) { echo "Exception: ", $e->getMessage(); } function router($controller, $action, $parameters) { $class_name = $controller . 'Controller'; $controller = new $class_name(); return call_user_func_array(array($controller, $action), $parameters); }
<?php use Phalcon\Mvc\Micro; $app = new Micro(); // Retrieves all robots $app->get('/api/robots', function () { //echo 111; }); // Searches for robots with $name in their name $app->get('/api/robots/search/{name}', function ($name) { }); // Retrieves robots based on primary key $app->get('/api/robots/{id:[0-9]+}', function ($id) { }); // Adds a new robot $app->post('/api/robots', function () { }); // Updates robots based on primary key $app->put('/api/robots/{id:[0-9]+}', function () { }); // Deletes robots based on primary key $app->delete('/api/robots/{id:[0-9]+}', function () { }); //$app->handle()->getContent();
} } else { $app->response->setStatusCode(404, 'Not Found'); $app->response->setJsonContent(array('status' => 'Not Found'))->send(); } }); // Create new source $app->post('/sources', function () use($app) { $post = $app->request->getJsonRawBody(); $newSource = new Tabs\Models\Sources(); $newSource->setData($post->data); $newSource->setType($post->type); $newSource->setName($post->name); if ($newSource->save() == true) { $app->response->setStatusCode(201, "Created"); $app->response->setJsonContent(array('status' => 'OK', 'data' => $newSource->name))->send(); } else { $app->response->setStatusCode(409, "Conflict"); $errors = array(); foreach ($newSource->getMessages() as $message) { $errors[] = $message->getMessage(); } $app->response->setJsonContent(array('status' => 'ERROR', 'messages' => $errors))->send(); } }); // Edit existing source $app->put('/sources/{id}', function ($id) use($app) { $source = Tabs\Models\Sources::findById((string) $id); $put = $app->request->getJsonRawBody(); if ($source) { $source->setData($put->data); $source->setType($put->type);
$response->setJsonContent(array('status' => 'ERROR', 'messages' => array(is_null($err_login) ? "User not logged in" : $err_login))); return $response; } $new_value = bookmark($user_id, $msg_id, false); if ($new_value === false) { $response->setStatusCode(400, 'Error'); $response->setContentType('application/json'); $response->setJsonContent(array('status' => 'ERROR', 'messages' => array(mysql_error()))); } return $response; }); /** * POST /threads */ $app->post('/api/threads', function () use($app) { return api_post($app, 0, 0); }); /** * POST /messages/$id/answers */ $app->post('/api/messages/{id:[0-9]+}/answers', function ($re) use($app) { return api_post($app, intval($re), 0); }); /** * PUT /messages/$id */ $app->put('/api/messages/{id:[0-9]+}', function ($msg_id) use($app) { return api_post($app, 0, intval($msg_id)); }); function api_post($app, $re, $msg_id, $privately = false) {
} return $response; }); // Adds a new Car $app->post('/api/autos', function () use($app) { $car = $app->request->getJsonRawBody(); $phql = "INSERT INTO Cars (Make, Model, Colour, Engine, Year) VALUES (:make:, :model:, :colour:, :engine:, :year:)"; $status = $app->modelsManager->executeQuery($phql, array('make' => $car->make, 'model' => $car->model, 'colour' => $car->colour, 'engine' => $car->engine, 'year' => $car->year)); // Create a response $response = new Response(); // Check if the insertion was successful if ($status->success() == true) { // Change the HTTP status $response->setStatusCode(201, "Created"); $car->id = $status->getModel()->id; $response->setJsonContent(array('status' => 'OK', 'data' => $car)); } else { // Change the HTTP status $response->setStatusCode(409, "Conflict"); // Send errors to the client $errors = array(); foreach ($status->getMessages() as $message) { $errors[] = $message->getMessage(); } $response->setJsonContent(array('status' => 'ERROR', 'messages' => $errors)); } return $response; }); // Updates Car based on primary key $app->put('/api/autos/{id:[0-9]+}', function ($id) use($app) { $car = $app->request->getJsonRawBody(); $phql = "UPDATE Cars SET Make = :make:, Model = :model:, Colour = :colour:, Engine = :engine:, Year = :year: WHERE id = :id:";
<?php use Phalcon\DI\FactoryDefault, Phalcon\Mvc\Micro, Phalcon\Config\Adapter\Ini as IniConfig; $di = new FactoryDefault(); $di->set('config', function () { return new IniConfig("config.ini"); }); $app = new Micro(); $app->setDI($di); $app->get('/', function () use($app) { //Read a setting from the config echo $app->config->app_name; }); $app->post('/contact', function () use($app) { $app->flash->success('Yes!, the contact was made!'); });
}); // Metodo responsavel por validar o usuario e salvar o produto; // Retorna a quantidade de produtos criados $app->post('/create/products/{key}', function ($key) use($app, $di) { $response = new Response(); $response->setHeader('Content-Type', 'application/xml'); $conta = Contas::findFirst(array('conditions' => array('key' => $key))); if ($conta) { $xml = simplexml_load_string($_POST['xml']); setDatabase($di, $conta->host, $conta->database); $erros = array(); $total = 0; foreach ($xml->produto as $key => $value) { $status = setProduto($value); if (!$status) { $erros[] = $status; } else { $total += 1; } } $response->setStatusCode(201, 'Created'); $response->setContent("<?xml version='1.0' encoding='ISO-8859-1'?><response><status>OK</status><mensagem>Foram criados {$total} produtos de um total de " . count($xml) . " de produtos enviados</mensagem></response>"); } else { $response->setStatusCode(401, 'Não autorizado'); $response->setContent("<?xml version='1.0' encoding='ISO-8859-1'?><response><status>ERROR</status><mensagem>Chave inválida</mensagem></response>"); } return $response; }); // Update produto $app->post('/update/product/{key}/{codigo}', function ($key, $codigo) use($app, $di) { $response = new Response();
$app->post("/register", function () use($app) { # Start building the response. $response = new Response(); # Error message to set for the response. $respond = null; # Get the new site information from the JSON object. if ($object = $app->request->getJsonRawBody()) { $first_name = $object->{"first_name"}; $surname = $object->{"surname"}; $email = $object->{"email"}; $password = $object->{"password"}; $confirm_password = $object->{"confirm_password"}; $opac_server_name = $object->{"opac_server_name"}; $intra_server_name = $object->{"intra_server_name"}; } else { $first_name = htmlspecialchars($_POST['firstname']); $surname = htmlspecialchars($_POST['surname']); $email = htmlspecialchars($_POST['email']); $password = htmlspecialchars($_POST['pword']); $confirm_password = htmlspecialchars($_POST['confirmpword']); $opac_server_name = htmlspecialchars($_POST['opacname']); $intra_server_name = htmlspecialchars($_POST['intraname']); } # Check validity of the parameters. if ($password !== $confirm_password && $respond == null) { $respond = "Mismatching passwords"; } if (!filter_var($email, FILTER_VALIDATE_EMAIL) && $respond == null) { $respond = "Invalid email address"; } if (!is_valid_domain_name($opac_server_name) && $respond == null) { $respond = "Invalid OPAC server name"; } if (!is_valid_domain_name($intra_server_name) && $respond == null) { $respond = "Invalid intranet server name"; } # If all of the parameters are valid, continue to send the request. if ($respond == null) { try { $mysqli = new mysqli(HOSTNAME, USERNAME, PASSWORD, DATABASE); ## # Register the Koha site with the registration database. ## if (!($statement = $mysqli->prepare("CALL add_koha_site(?, ?, ?, ?, ?, ?)"))) { throw new Exception("Unable to prepare SQL statement for adding the Koha site (" . $mysqli->errno . "): " . $mysqli->error); } if (!$statement->bind_param("ssssss", $first_name, $surname, $email, $password, $opac_server_name, $intra_server_name)) { throw new Exception("Unable to bind parameters to the statement for adding the Koha site (" . $statement->errno . "): " . $statement->error); } if (!$statement->execute()) { throw new Exception("Unable to execute the statement for getting the Koha site ID (" . $statement->errno . "): " . $statement->error); } ## # If we got to this point, yay! It worked! # Get the Koha site ID from the response. ## $statement->bind_result($id); if ($results = $statement->fetch()) { # Only get the ID and send an "Accepted" reply if we got a result back. # 202 Accepted $response->setStatusCode(202, "Accepted"); $response->setJsonContent(array("id" => $id)); } else { throw new Exception("Unable to get Koha site ID from statement response"); } } catch (Exception $e) { $response->setStatusCode(503, "Internal Server Error"); $response->setJsonContent(array("message" => $e->getMessage())); } } else { $response->setStatusCode(400, "Bad Request"); $response->setJsonContent(array("message" => $respond)); } return $response; });