/** * @covers mbarquin\SlimDR\Factory::slim * @todo Implement testSlim(). */ public function testSlimAcceptsSlimAlreadySetted() { $slim = new \Slim\App(); $slim->group('/users', function () { $this->get('/reset-password', function ($request, $response, $args) { // Code here. })->setName('user-password-reset'); }); $oFact = Factory::slim($slim); $slimProcessed = $oFact->withGroup('admin')->getApp(); $container = $slimProcessed->getContainer(); $routes = $container->get('router')->getRoutes(); $rout = array_values($routes); $group = $rout[0]->getGroups(); $group2 = $rout[1]->getGroups(); $this->assertAttributeContains('/users', 'pattern', $group[0]); $this->assertAttributeContains('/admin', 'pattern', $group2[0]); }
$app->group('/api', function () { $this->get('/', function () { echo 'API running'; }); // Get information about board $this->get('/team/{teamHash}', function (\Slim\Http\Request $req, \Slim\Http\Response $res, $args) { try { // TODO: when implemented in Slim-HttpCache, return response immediately See: https://github.com/slimphp/Slim-HttpCache/issues/10 $lastModified = \Sprintboard\Model\Team::where('hash', $args['teamHash'])->firstOrFail()->value('updated_at'); $res = $this->cache->withLastModified($res, \Carbon\Carbon::parse($lastModified)->timestamp); $team = \Sprintboard\Model\Team::with(['sprints' => function ($query) { return $query->orderBy('start_datetime'); }, 'sprints.cards', 'sprints.cards.tasks' => function ($query) { return $query->orderBy('index'); }])->where('hash', $args['teamHash'])->firstOrFail(); return $res->withJson($team); } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) { return $res->withJson(['message' => 'Board not found'], 404); } }); // Get information about sprint $this->get('/team/{teamHash}/{sprintId}', function (\Slim\Http\Request $req, \Slim\Http\Response $res, $args) { try { $team = \Sprintboard\Model\Team::with(['sprints' => function ($query) { return $query->orderBy('start_datetime'); }, 'sprints.cards', 'sprints.cards.tasks' => function ($query) { return $query->orderBy('index'); }])->where('hash', $args['teamHash'])->firstOrFail(); return $res->withJson($team); } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) { return $res->withJson(['message' => 'Board not found'], 404); } }); // Add new card to a board // Example of JSON payload: {"name": "My Example Card"} $this->post('/team/{teamHash}/{sprintId}/card', function (\Slim\Http\Request $req, \Slim\Http\Response $res, $args) { try { $sprint = \Sprintboard\Model\Sprint::findOrFail($args['sprintId']); $card = new \Sprintboard\Model\Card(); $body = $req->getParsedBody(); $name = empty($body['name']) ? null : $body['name']; if (!$name) { return $res->withJson(['message' => 'Missing name parameter'], 400); } $card->name = $name; $sprint->cards()->save($card); return $res->withStatus(201); } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) { return $res->withJson(['message' => 'Sprint not found'], 404); } }); // Rename a card $this->put('/card/{cardId}', function (\Slim\Http\Request $req, \Slim\Http\Response $res, $args) { try { $body = $req->getParsedBody(); if (empty($body['name'])) { return $res->withJson(['message' => 'Missing name parameter'], 400); } $card = \Sprintboard\Model\Card::where('id', $args['cardId'])->firstOrFail(); $card->name = $body['name']; $card->save(); return $res->withStatus(204); } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) { return $res->withJson(['message' => 'Card not found'], 404); } }); // Delete a card from a board $this->delete('/card/{cardId}', function (\Slim\Http\Request $req, \Slim\Http\Response $res, $args) { try { $card = \Sprintboard\Model\Card::where('id', $args['cardId'])->firstOrFail(); $card->delete(); return $res->withStatus(204); } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) { return $res->withJson(['message' => 'Card not found'], 404); } }); // Add new task to a card // Example of JSON payload: {"name": "My Example Task"} $this->post('/card/{cardId}/task', function (\Slim\Http\Request $req, \Slim\Http\Response $res, $args) { $body = $req->getParsedBody(); $name = empty($body['name']) ? null : $body['name']; if (!$name) { return $res->withJson(['message' => 'Missing name parameter'], 400); } try { $card = \Sprintboard\Model\Card::findOrFail($args['cardId']); $task = new \Sprintboard\Model\Task(); $task->name = $name; $task->is_done = false; $maxIndex = $card->tasks()->max('index'); if (!is_null($maxIndex)) { $task->index = $maxIndex + 1; } $card->tasks()->save($task); return $res->withStatus(201); } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) { return $res->withJson(['message' => 'Card not found'], 404); } }); // Mark a task to be done or unmark it $this->map(['PUT', 'DELETE'], '/task/{taskId}/done', function (\Slim\Http\Request $req, \Slim\Http\Response $res, $args) { try { $task = \Sprintboard\Model\Task::findOrFail($args['taskId']); if ($req->isPut()) { $task->is_done = true; } else { if ($req->isDelete()) { $task->is_done = false; } } $task->save(); return $res->withStatus(201); } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) { return $res->withJson(['message' => 'Task not found'], 404); } }); // Delete a task $this->delete('/task/{taskId}', function (\Slim\Http\Request $req, \Slim\Http\Response $res, $args) { try { $task = \Sprintboard\Model\Task::findOrFail($args['taskId']); $task->delete(); return $res->withStatus(204); } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) { return $res->withJson(['message' => 'Task not found'], 404); } }); // Rename a task $this->put('/task/{taskId}', function (\Slim\Http\Request $req, \Slim\Http\Response $res, $args) { $body = $req->getParsedBody(); $name = empty($body['name']) ? null : $body['name']; if (!$name) { return $res->withJson(['message' => 'Missing name parameter'], 400); } try { $task = \Sprintboard\Model\Task::findOrFail($args['taskId']); $task->name = $name; $task->save(); return $res->withStatus(204); } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) { return $res->withJson(['message' => 'Task not found'], 404); } }); $this->put('/card/{cardId}/sort', function (\Slim\Http\Request $req, \Slim\Http\Response $res, $args) { $body = $req->getParsedBody(); try { foreach ($body as $index => $taskId) { $task = \Sprintboard\Model\Task::findOrFail($taskId); $task->index = $index; $task->save(); } return $res->withStatus(204); } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) { return $res->withJson(['message' => 'Task not found'], 404); } }); // Add a new sprint. Copies the undone task from last sprint. Returns the new sprint object $this->post('/team/{teamHash}/sprint', function (\Slim\Http\Request $req, \Slim\Http\Response $res, $args) { $body = $req->getParsedBody(); try { $team = \Sprintboard\Model\Team::with(['sprints' => function ($query) { return $query->orderBy('start_datetime', 'desc'); }, 'sprints.cards.tasks' => function ($query) { return $query->where('is_done', false); // Load only those tasks that are not done }])->where('hash', $args['teamHash'])->firstOrFail(); $sprint = new \Sprintboard\Model\Sprint(); // TODO: validate request data $sprint->name = $body['name']; $sprint->start_datetime = \Carbon\Carbon::parse($body['start_date'])->toDateTimeString(); $sprint->end_datetime = \Carbon\Carbon::parse($body['end_date'])->toDateTimeString(); $lastSprint = $team->sprints->first(); $team->sprints()->save($sprint); foreach ($lastSprint->cards as $card) { $cardModel = new \Sprintboard\Model\Card(); $cardModel->name = $card->name; $sprint->cards()->save($cardModel); foreach ($card->tasks as $task) { $taskModel = new \Sprintboard\Model\Task(); $taskModel->name = $task->name; $taskModel->is_done = false; $cardModel->tasks()->save($taskModel); } } return $res->withJson($sprint); } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) { return $res->withJson(['message' => 'Team not found'], 404); } }); });
require_once '../vendor/autoload.php'; use racoin\backend\controller as Controller; $container = new Slim\Container(); $container['twig'] = function ($container) { $loader = new Twig_Loader_Filesystem('../src/racoin/backend/view'); return new Twig_Environment($loader, array('debug' => true)); }; racoin\app\App::DbConf('../src/racoin/utils/config.ini'); $app = new \Slim\App($container); //Toutes les actions pour le backend $app->group('/', function () use($app) { //Affichage de la liste des annonces non validées $app->get('unvalidated', function () use($app) { $controller = new Controller\AnnonceController($app); return $controller->getUnvalidatedAnnonces(); }); //Récupération d'une annonce $app->get('annonce/{id}', function ($req, $res, $args) use($app) { $id = $args['id']; $controller = new Controller\AnnonceController($app); return $controller->getAnnonceById($id); }); }); //valider une annonce $app->get('/annonce/{id}/validate', function ($req, $res, $args) use($app) { $id = $args['id']; $controller = new Controller\AnnonceController($app); return $controller->validateAnnonceById($id); }); $app->run();
$app->group('/api', function () { //////////////////////////////////////////////////////////////////////////// // /API/MEDIA ///////////////////////////////////////////////////////////// // returns the info on the post and media angular needs in it's views ///// /////////////////////////////////////////////////////////////////////////// $this->get('/media', function ($request, $response, $args) { $db = $this->sql; if ($db) { $result = $db->query('call getPostMedia'); if ($result) { while ($row = $result->fetch()) { $media[] = $row; } if ($media) { $response->getBody()->write(json_encode($media)); return $response->withStatus(200); } } } return $response->withStatus(404); }); /////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// // /API/MEDIA ///////////////////////////////////////////////////////////// // returns the info on the post and media angular needs in it's views ///// /////////////////////////////////////////////////////////////////////////// $this->get('/about', function ($request, $response, $args) { $db = $this->sql; if ($db) { $result = $db->query('call getAbout'); if ($result) { while ($row = $result->fetch()) { $about[] = $row; } if ($about) { $response->getBody()->write(json_encode($about)); return $response->withStatus(200); } } } return $response->withStatus(404); }); /////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// // /API/LOGIN ////////////////////////////////////////////////////////////// // validates the user credentials against the db and creates a $_SESSION /// // don't worry about security just yet so no need to hash & salt the /////// // password //////////////////////////////////////////////////////////////// $this->post('/login', function ($request, $response, $args) { $credentials = $request->getParsedBody(); $db = $this->sql; if ($db) { $result = $db->query('call getMember'); if ($result) { while ($row = $result->fetch()) { $users[] = $row; } if ($users) { foreach ($users as $user) { if ($credentials['username'] === $user['email']) { // valid username if (password_verify($credentials['password'], $user['password'])) { // valid password $session = ['id' => $user['id'], 'user' => ['userId' => $user['id'], 'userName' => $user['username'], 'userRole' => $user['role']]]; $_SESSION['user_state'] = $session; $response->getBody()->write(json_encode($session)); return $response->withStatus(201); } } } $error = ['reason' => 'invalid credentials.']; $response->getBody()->write(json_encode($error)); return $response->withStatus(404); } } } return $response->withStatus(404); }); $this->get('/login', function ($request, $response, $args) { // return the session_state in json format if (!isset($_SESSION['user_state']) && empty($_SESSION['user_state'])) { $session = ['id' => '1', 'user' => ['userId' => '1', 'userName' => '', 'userRole' => 'viewer']]; $_SESSION['user_state'] = $session; } $session = $_SESSION['user_state']; $response->getBody()->write(json_encode($session)); return $response->withStatus(200); }); $this->delete('/login', function ($request, $response, $args) { // default $_SESSION should be this, so when we call delete // we should actually juste update the $_SESSION with those values $session = ['id' => '0', 'user' => ['userId' => '0', 'userName' => '', 'userRole' => 'viewer']]; $_SESSION['user_state'] = $session; $response->getBody()->write(json_encode($session)); return $response->withStatus(200); }); /////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// // /API/USERS ////////////////////////////////////////////////////////////// // returns the list of all users from the db /////////////////////////////// //////////////////////////////////////////////////////////////////////////// $this->get('/users', function ($request, $response, $args) { $db = $this->sql; if ($db) { $result = $db->query('call getMembers'); if ($result) { while ($row = $result->fetch()) { $users[] = $row; } if ($users) { $response->getBody()->write(json_encode($users)); return $response->withStatus(200); } } } return $response->withStatus(404); }); $this->delete('/user{id}', function ($request, $response, $args) { $userId = $args['id']; $db = $this->sql; if ($db) { $result = $db->query('call deleteMember(?)', [$userId]); if ($result) { $response->getBody()->write(json_encode($userId)); return $response->withStatus(200); } } return $response->withStatus(404); }); /////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// // /API/POST /////////////////////////////////////////////////////////////// // takes care of file upload /////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// $this->post('/post', function ($request, $response, $args) { $userId = $_SESSION['user_state']['user']['userId']; $filename = $_FILES['file']['name']; $title = $_POST['title']; $type = $_POST['type']; $medium = $type === 'Film' ? 'Film' : 'Photo'; $spec = $_POST['spec'] === 'null' ? null : $_POST['spec']; $date = $_POST['date'] === 'null' ? null : $_POST['date']; $destination = $spec ? '/src/client/photos/' . $type . '/' . $spec . '/' . $filename : '/src/client/photos/' . $type . '/' . $filename; $db = $this->sql; if ($db) { if ($destination) { try { $media_inserted = $db->query('call setMedia(?)', [$destination]); try { $mediaId = $db->query('call getMediaUrl(?)', [$destination]); while ($row = $mediaId->fetch()) { $id = $row['id']; } $mediaId->free(); $db->next_result(); try { $post_inserted = $db->query('call setPost(?, ?, ?, ?, ?, ?, ?)', [$userId, $id, $medium, $type, $spec, $title, $date]); $success = move_uploaded_file($_FILES['file']['tmp_name'], $_SERVER['DOCUMENT_ROOT'] . $destination); if ($success) { return $response->withStatus(201); } else { return $response->withStatus(404, 'We tried to upload your post, and everything looked fine until we tryed to move that file in our magic \'post folder\' :/ Try again with a different filename?'); } } catch (Exception $e) { return $response->withStatus(409, 'This photo or video has already been published. Hint: if you want to modify an existing photo jsut go to \'Manage Post\''); } } catch (Exception $e) { return $response->withStatus(404, 'Something really, and I mean REALLY weird happened, it seems this post has vanished into the void. o.O'); } } catch (Exception $e) { return $response->withStatus(409, 'This photo or video has already been published. Hint: if you want to modify an existing photo just go to \'Manage Post\''); } } } return $response->withStatus(404, 'Oops! Somehow the server is busy and can\'t proccess this request as of now. Please try again or contact your administrator!'); }); /////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// // /API/COMMENT //////////////////////////////////////////////////////////// // Commenting module ////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// $this->get('/comments', function ($request, $response, $args) { $db = $this->sql; if ($db) { try { $result = $db->query('call getComments'); if (is_null($result)) { throw new Exception(); } while ($row = $result->fetch()) { $comments[] = $row; } if ($comments) { $response->getBody()->write(json_encode($comments)); return $response->withStatus(200); } } catch (Exception $e) { $response->getBody()->write('comments not found'); return $response->withStatus(404); } } return $response->withStatus(404); }); $this->post('/comment', function ($request, $response, $args) { $comment = $request->getParsedBody(); $db = $this->sql; if ($db) { try { $result = $db->insert('comments', ['post_id' => $comment['post_id'], 'mem_id' => $comment['mem_id'], 'content' => $comment['content'], 'comment_date' => $comment['comment_date']]); $comment['id'] = $db->getId($result); $response->getBody()->write(json_encode($comment)); return $response->withStatus(201); } catch (Exception $e) { return $response->withStatus(409, $e->getMessage); } } return $response->withStatus(404, 'Mmmhh... We couldn\'t connect to our server somehow :/ Please try again or contact your administrator.'); }); $this->delete('/comment{id}', function ($request, $response, $args) { $commentId = $args['id']; $db = $this->sql; if ($db) { try { $result = $db->query('call deleteComment(?)', [$commentId]); $response->getBody()->write(json_encode($commentId)); return $response->withStatus(200); } catch (Exception $e) { return $response->withStatus(404, 'Oops! It seems like we couldn\'t delete this comment... strange. Maybe it already has been deleted? Refresh the page to find out!'); } } return $response->withStatus(404, 'Mmmhh... We couldn\'t connect to our server somehow :/ Please try again or contact your administrator.'); }); });
$app->group('/admin/channels/{slug}', function () { $this->get('', function ($request, $response, $args) { $parsedBody = $request->getParsedBody(); $channel = $this->get('tvlistings.channel.repository')->findOneBySlug($args['slug']); $listings = $this->get('tvlistings.listing.repository')->findBy($channel); $this->view->render($response, 'admin/show.html.twig', array('channel' => $channel, 'listings' => $listings)); return $response; })->setName('admin_channel_show'); $this->map(['GET', 'POST'], '/listings/new', function ($request, $response, $args) { $channel = $this->get('tvlistings.channel.repository')->findOneBySlug($args['slug']); if ($request->isPost()) { $parsedBody = $request->getParsedBody(); $listingRepository = $this->get('tvlistings.listing.repository'); $listing = new Listing($channel, $parsedBody['title'], new \DateTime($parsedBody['programDate'])); $listing->programAt($parsedBody['programAt']); $listing->setDescription($parsedBody['description']); $listingRepository->persist($listing); if ($parsedBody['video_source']) { $videoProxyService = $this->get('tvlistings.video_proxy.service'); $videoProxyUuid = $videoProxyService->createFromSource($parsedBody['video_source']); $listing->changeResourceLink($videoProxyUuid); $listingRepository->persist($listing); } $uri = $this->router->pathFor('admin_channel_show', array('slug' => $channel->getSlug())); return $response->withRedirect((string) $uri, 301); } $this->view->render($response, 'admin/Listing/new.html.twig', array('channel' => $channel)); return $response; })->setName('admin_listing_new'); $this->map(['GET', 'POST'], '/edit', function ($request, $response, $args) { $channelRepository = $this->get('tvlistings.channel.repository'); $channel = $channelRepository->findOneBySlug($args['slug']); if ($request->isPost()) { $parsedBody = $request->getParsedBody(); $channel->changeName($parsedBody['name']); $channel->changeLogoPath($parsedBody['logoPath']); $channelRepository->persist($channel); $uri = $this->router->pathFor('admin_homepage', array()); return $response->withRedirect((string) $uri, 301); } $this->view->render($response, 'admin/edit.html.twig', array('channel' => $channel)); return $response; })->setName('admin_channel_edit'); });
$path = $uri->getPath(); if ($path != '/' && substr($path, -1) == '/') { // permanently redirect paths with a trailing slash // to their non-trailing counterpart $uri = $uri->withPath(substr($path, 0, -1)); return $response->withRedirect((string) $uri, 301); } return $next($request, $response); }); $app->group('/api/stryktipset', function () { require 'app/api/cStryktipsetApi.php'; $this->get('', function (Request $request, Response $response) { $response = $response->withHeader('Content-type', 'application/json'); $response->getBody()->write(StryktipsetApi::getThisWeek()); return $response; })->setName('stryktipset'); $this->get('/last', function (Request $request, Response $response) { $response = $response->withHeader('Content-type', 'application/json'); $response->getBody()->write(StryktipsetApi::getRow()); return $response; })->setName('stryktipset-last'); }); $app->group('/api/matches', function () { require 'app/api/cMatchesApi.php'; header("Content-Type: application/json"); $this->get('', function (Request $request, Response $response) { flush(); return MatchesApi::getMatches(); })->setName('matches'); $this->get('/{team}', function (Request $request, Response $response, $args) { $limit = null;
$app->group('/discussion', function () { include "../../requirements/sqli.php"; $sqli = new sqli(array("127.0.0.1", "", "", "test")); $this->get('', function ($request, $response, $args) use($sqli) { echo json_encode($sqli->pull_multiple("select * from diskotioner")->data); }); $this->post('', function ($request, $response, $args) use($sqli) { if (isset($_POST['title'])) { $insert = $sqli->push("insert into diskotioner (title) VALUES (?)", "s", $_POST['title']); if ($insert->affected_rows == 1) { return $response->withStatus(201)->write($insert->insert_id); } return $response->withStatus(400); } return $response->withStatus(400); }); $this->delete('/{id:[0-9]+}', function ($request, $response, $args) use($sqli) { $sqli->push("delete FROM diskotion_kommentar where fk_kommentar = ?", "i", $args['id']); return $response->withStatus($sqli->push("delete FROM diskotioner WHERE id =?", "i", $args['id'])->affected_rows !== 0 ? 204 : 400); }); $this->group('/{id:[0-9]+}', function () use($sqli) { $this->get('', function ($request, $response, $args) use($sqli) { echo json_encode($sqli->pull_multiple("select * from diskotion_kommentar WHERE fk_kommentar =?", "i", $args['id'])->data); }); $this->post('', function ($request, $response, $args) use($sqli) { if (isset($_POST['kommentar'])) { $insert = $sqli->push("insert into diskotion_kommentar ( fk_kommentar, kommentar) VALUES (?, ?)", "is", $args['id'], $_POST['kommentar']); if ($insert->affected_rows == 1) { return $response->withStatus(201)->write($insert->insert_id); } return $response->withStatus(400); } return $response->withStatus(400); }); }); });
require 'system/vendor/autoload.php'; function conf($name) { global $c; return $c[$name]; } require ROOT_DIR . "/system/modules/core/php/BaseHandler.php"; // EOF TODO remove /////////////////////////////////////////////////////////////////// $app = new \Slim\App(); /** * @param $string * @return string */ function mb_ucfirst($string) { return mb_strtoupper(mb_substr($string, 0, 1)) . mb_strtolower(mb_substr($string, 1)); } $isSys = $_GET['sys'] == 'sys'; require ROOT_DIR . '/' . ($isSys ? 'system' : 'custom') . '/modules/' . mb_strtolower($_GET['module']) . '/api/' . mb_ucfirst($_GET['endpoint']) . '.php'; // Define app routes $app->group('/api/' . ($isSys ? 'sys/' : '') . $_GET['module'] . '/' . $_GET['endpoint'], function () { $handler = new EndpointHandler(); $routes = $handler->getRoutes(); foreach ($routes as $httpMethod => $methodRoutes) { foreach ($methodRoutes as $url => $functionName) { call_user_func([$this, mb_strtolower($httpMethod)], $url, [$handler, $functionName]); } } }); // Run app $app->run();
use racoin\api\controller as Controller; $app = new \Slim\App(); //Toutes les actions pour 'catégories' $app->group('/categories', function () use($app) { //Retourne la liste des catégories $app->get('', function ($req, $res) use($app) { $controller = new Controller\CategorieController($req, $res, $app); return $controller->getAllCategories(); }); //Retourne la catégorie demandée $app->get('/{id}', function ($req, $res, $args) use($app) { $id = $args['id']; $controller = new Controller\CategorieController($req, $res, $app); return $controller->getCategorieById($id); }); //Retourne les annonces d'une catégorie $app->get('/{id}/annonces', function ($req, $res, $args) use($app) { $id = $args['id']; $controller = new Controller\AnnonceController($req, $res, $app); return $controller->getAnnonceByCategorie($id); }); //Post d'annonce sur une catégorie $app->post('/{id}/annonce', function ($req, $res, $args) use($app) { $id = $args['id']; $controller = new Controller\AnnonceController($req, $res, $app); return $controller->postAnnonce($id); }); }); //Toutes les actions pour 'annonces' $app->group('/annonces', function () use($app) { //Retourne la liste des annonces
$res->getBody()->write("middleware #1\n"); return $next($req, $res); }); /** * middleware #2 */ $app->add(function (Req $req, Res $res, $next) { $res->getBody()->write("middleware #2\n"); return $next($req, $res); }); /** * normal response */ $app->get('/hello/{name}', function (Req $request, Res $response, $args) { $response->getBody()->write("Hello, " . $args['name']); return $response->withHeader('Content-Type', 'text/plain'); }); /** * group with middleware #G. */ $app->group('/grouped', function () { /** normal response. */ $this->get('', function (Req $req, Res $res) { $res->getBody()->write('grouped top'); return $res->withHeader('Content-Type', 'text/plain'); }); })->add(function (Req $req, Res $res, $next) { $res->getBody()->write("middleware #G\n"); return $next($req, $res); }); $app->run();
<?php require 'vendor/autoload.php'; $app = new \Slim\App(); $app->group('/v1', function () use($app) { // API Endpoint for our postcodes $app->get('/postcodes/{postcode}', function ($request, $response, $args) { $postcodeData = PostcodeDatabase::getPostcodeData($args['postcode']); return $response->write(json_encode($postcodeData))->withHeader('Content-Type', 'application/json'); }); }); // Run app $app->run();
<?php define('HOST_NAME', $_SERVER['HTTP_HOST']); header('Content-Type: application/json'); require 'vendor/autoload.php'; require_once 'lib/Db.class.php'; $app = new Slim\App(); $app->get('/', function () { var_dump($_SERVER); DB::openConnection(); }); $app->group('/app', function () use($app) { $app->get('/hello/{name}', function ($request, $response, $args) { $response->write("Hello, " . $args['name']); return $response; }); $app->group('/user', function () use($app) { $app->post('/login/', function () { var_dump('OK'); }); }); }); $app->run();
$container = new \Slim\Container($configuration); $app = new \Slim\App($container); $container['AuthMiddleware'] = function ($container) { return new AuthMiddleware(); }; $container['HeaderMiddleware'] = function ($container) { return new HeaderMiddleware(); }; // Define the private group */ $app->group('', function () use($app) { $app->get('/test', function ($request, $response, $args) { $response->getBody()->write('{ "result":"passed" }'); return $response; }); $app->get('/version', function ($request, $response, $args) { $response->getBody()->write('{ "version":"v3.5.3-alpha", "major":3, "minor":5, "patch":3, "release":"alpha" }'); return $response; }); include "src/GigRoutes.php"; include "src/VenueRoutes.php"; include "src/AccountRoutes.php"; include "src/ContactRoutes.php"; })->add('AuthMiddleware')->add('HeaderMiddleware'); // Define the public group for options*/ $app->group('', function () use($app) { include "src/OptionRoutes.php"; })->add('HeaderMiddleware'); // Define the control group */ $app->group('/control', function () use($app) { /* AUTH */ $app->options('/login', function ($request, $response, $args) { $id = $request->getAttribute('id');
<?php /** * Created by PhpStorm. * User: Benjaco * Date: 12-01-2016 * Time: 16:36 */ require "../../vendor/autoload.php"; $c = new \Slim\Container(); //Create Your container //Override the default Not Found Handler $c['notFoundHandler'] = function ($c) { return function ($request, $response) use($c) { return $c['response']->withStatus(404)->withHeader('Content-Type', 'text/json')->write('{"status":404}'); }; }; $app = new \Slim\App($c); $app->group('/variabel', function () { $this->get('', function ($request, $response, $args) { echo file_get_contents("variable.txt"); }); $this->put('', function ($request, $response, $args) { echo file_put_contents("variable.txt", $_POST['data']); }); }); $app->run();
$response = $next($request, $response); return $response; }; }; // Throw Slim exception also in case of PHP notice or warning set_error_handler(function ($severity, $message, $file, $line) { if (!(error_reporting() & $severity)) { return; } throw new \ErrorException($message, 0, $severity, $file, $line); }); $app->group('/api', function () use($throttleMiddleware, $authMiddleware) { $this->post('/register', '\\Dullahan\\Controller\\UserController:register'); $this->post('/login', '\\Dullahan\\Controller\\UserController:login')->add($throttleMiddleware('login')); $this->get('/login', '\\Dullahan\\Controller\\UserController:getUserDetails')->add($authMiddleware()); $this->get('/media', '\\Dullahan\\Controller\\MediaController:listMedia')->add($authMiddleware()); $this->delete('/media/{filename}', '\\Dullahan\\Controller\\MediaController:deleteMediaItem')->add($authMiddleware()); $this->get('/media/thumbnail/{filename}', '\\Dullahan\\Controller\\MediaController:getMediaThumbnail'); $this->get('/media/download/{filename}', '\\Dullahan\\Controller\\MediaController:downloadMedia'); $this->post('/media', '\\Dullahan\\Controller\\MediaController:uploadMedia')->add($authMiddleware()); $this->get('/content', '\\Dullahan\\Controller\\ContentController:listContentTypes')->add($authMiddleware()); $this->get('/content/{contentTypeSlug}', '\\Dullahan\\Controller\\ContentController:listContent')->add($authMiddleware()); $this->post('/content/{contentTypeSlug}', '\\Dullahan\\Controller\\ContentController:createContent')->add($authMiddleware()); $this->get('/content/all/{contentId}', '\\Dullahan\\Controller\\ContentController:getSingleContent')->add($authMiddleware()); $this->put('/content/all/{contentId}', '\\Dullahan\\Controller\\ContentController:updateContent')->add($authMiddleware()); $this->get('/content-types/{contentTypeSlug}', '\\Dullahan\\Controller\\ContentController:getContentType')->add($authMiddleware()); $this->get('/component-types/{componentTypeSlug}', '\\Dullahan\\Controller\\ContentController:getComponentType')->add($authMiddleware()); $this->get('/users', '\\Dullahan\\Controller\\UserController:listUsers')->add($authMiddleware()); $this->get('/apps', '\\Dullahan\\Controller\\AppController:listApps')->add($authMiddleware()); }); $app->run();
$app->group('/noter', function () { $this->get('', function ($request, $response, $args) { echo json_encode(array_values(json_decode(file_get_contents("noter.json"), true)['data'])); return $response->withStatus(200); }); $this->post('', function ($request, $response, $args) { if (isset($_POST['title'], $_POST['text'])) { $data = json_decode(file_get_contents("noter.json"), true); $data['id']++; $data['data'][$data['id']] = ['id' => $data['id'], 'title' => utf8_encode($_POST['title']), 'text' => utf8_encode($_POST['text'])]; file_put_contents("noter.json", json_encode($data)); return $response->write($data['id'])->withStatus(201); } else { return $response->withStatus(400); } }); $this->put('/{id}', function ($request, $response, $args) { $data = json_decode(file_get_contents("noter.json"), true); if (isset($data['data'][$args['id']], $_POST['title'], $_POST['text'])) { $data['data'][$args['id']] = ['id' => $args['id'], 'title' => utf8_encode($_POST['title']), 'text' => utf8_encode($_POST['text'])]; file_put_contents("noter.json", json_encode($data)); return $response->withStatus(200); } else { return $response->withStatus(400); } }); $this->delete('/{id}', function ($request, $response, $args) { $data = json_decode(file_get_contents("noter.json"), true); if (isset($data['data'][$args['id']])) { unset($data['data'][$args['id']]); file_put_contents("noter.json", json_encode($data)); return $response->withStatus(204); } else { return $response->withStatus(400); } }); });
$app->group('/api', function () use($app) { $app->group('/v1', function () use($app) { $app->add(new JsonResponse()); /** * */ $app->get('/catalog[/{table}]', function ($req, $res, $args) { $table = isset($args['table']) ? $args['table'] : null; $result = Store::catalog($table); if (!$result) { return $res->withStatus(404)->write(JsonHelper::fail('Tabella inesistente.')); } return $res->write(JsonHelper::success($result)); }); /** * */ $app->post('/autenticazione', function ($req, $res) { $body = $req->getParsedBody(); $codiceFiscale = isset($body['codice_fiscale']) ? $body['codice_fiscale'] : ''; $password = isset($body['password']) ? $body['password'] : ''; $result = Auth::authenticate($codiceFiscale, $password); if (!$result) { return $res->withStatus(403)->write(JsonHelper::fail('Codice Fiscale e/o Password errati.')); } return $res->write(JsonHelper::success($result)); }); /** * */ $app->get('/profilo/{id_utenza:\\d}', function ($req, $res, $args) { $idUtenza = $args['id_utenza']; $tipologia = $args['_tipologia']; $queryParams = $req->getQueryParams(); $incsQuery = isset($queryParams['include']) ? $queryParams['include'] : ''; $result = Store::getProfilo($idUtenza, $tipologia, $incsQuery); $res->write(JsonHelper::success($result)); })->add(new SetACL())->add(new VerifyToken()); /** * */ $app->get('/profilo/me', function ($req, $res, $args) { $queryParams = $req->getQueryParams(); $incsQuery = isset($queryParams['include']) ? $queryParams['include'] : ''; $idUtenza = $args['_id_utenza']; $tipologia = $args['_tipologia']; $result = Store::getProfilo($idUtenza, $tipologia, $incsQuery); $res->write(JsonHelper::success($result)); })->add(new VerifyToken()); /** * /api/v1/sensori/838701426/ambientale (temperatura) * /api/v1/sensori/838701426/ambientale/2 (umidità) * /api/v1/sensori/838701426/ambientale/3 (anidrite carbonica) * /api/v1/sensori/838701426/energia_elettrica (kWh) * /api/v1/sensori/838701426/energia_elettrica/2 (energia elettrica reattiva) */ $app->get('/sensori/{numero_contatore}/{metrica}[/{canale}]', function ($req, $res, $args) { $queryParams = $req->getQueryParams(); $numeroContatore = $args['numero_contatore']; $metrica = $args['metrica']; $canale = isset($args['canale']) ? $args['canale'] : 1; $result = Store::getSensoreDataByNumeroContatore($numeroContatore, $metrica, $canale, $queryParams); if (!$result) { return $res->withStatus(404)->write(JsonHelper::fail('Impossibile recuperare le informazioni dal sensore.')); } return $res->write(JsonHelper::success($result)); })->add(new SetACL())->add(new VerifyToken()); /** * */ $app->get('/meteo', function ($req, $res) { $queryParams = $req->getQueryParams(); $incsQuery = isset($queryParams['include']) ? $queryParams['include'] : ''; $result = Store::getMeteo($incsQuery); if (!$result) { return $res->withStatus(404)->write(JsonHelper::fail('Impossibile recuperare le informazioni meteo.')); } return $res->write(JsonHelper::success($result)); }); }); });
$app->group('/nuovo', function () use($dati) { $this->map(['GET', 'POST'], '/articolo', function ($request, $response, $args) use($dati) { $response = $this->renderer->render($response, 'forum/articoli.php', array('dati' => $dati, 'new' => true)); if (fatto()) { $response = $response->withStatus(301)->withHeader('Location', $this->router->pathFor('articoli')); } return $response; }); $this->map(['GET', 'POST'], '/articolo/:id', function ($request, $response, $args) use($dati) { $response = $this->renderer->render($response, 'forum/articoli.php', array('dati' => $dati, 'new' => true, 'categoria' => $args['id'])); if (fatto()) { $response = $response->withStatus(301)->withHeader('Location', $this->router->pathFor('articoli')); } return $response; }); if (isAdminUserAutenticate()) { $this->map(['GET', 'POST'], '/categoria', function ($request, $response, $args) use($dati) { $response = $this->renderer->render($response, 'forum/categorie.php', array('dati' => $dati, 'new' => true)); if (fatto()) { $response = $response->withStatus(301)->withHeader('Location', $this->router->pathFor('categorie')); } return $response; }); $this->map(['GET', 'POST'], '/categoria/:id', function ($request, $response, $args) use($dati) { $response = $this->renderer->render($response, 'forum/categorie.php', array('dati' => $dati, 'new' => true, 'tipo' => $args['id'])); if (fatto()) { $response = $response->withStatus(301)->withHeader('Location', $this->router->pathFor('categorie')); } return $response; }); $this->map(['GET', 'POST'], '/tipo', function ($request, $response, $args) use($dati) { $response = $this->renderer->render($response, 'forum/tipi.php', array('dati' => $dati, 'new' => true)); if (fatto()) { $response = $response->withStatus(301)->withHeader('Location', $this->router->pathFor('tipi')); } return $response; }); } });
$container = $app->getContainer(); $container['renderer'] = function ($c) { return new Slim\Views\PhpRenderer('site/templates/'); }; $container['docrender'] = function ($c) { return new Slim\Views\PhpRenderer('api/doc/'); }; require 'config.php'; require 'dependencies.php'; function getConnection() { global $server, $database, $user, $password; $dbh = new PDO("mysql:host={$server};dbname={$database}", $user, $password); $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); return $dbh; } $app->group('/', function () use($app) { require 'site/routes/site.php'; }); $app->group('/api', function () use($app) { require 'api/routes/champions.php'; require 'api/routes/teams.php'; require 'api/routes/compos.php'; require 'api/routes/regions.php'; require 'api/routes/bans.php'; require 'api/routes/games.php'; $app->get('/doc/', function ($req, $res, $args) { return $this->docrender->render($res, 'index.html', $args); }); }); $app->run();
}, 'session' => function ($c) { return new \SessionHelper(); }, 'settings' => ['displayErrorDetails' => true], 'view' => function ($c) { $view = new \Slim\Views\Twig('views', ['cache' => false]); $view->addExtension(new \Slim\Views\TwigExtension($c['router'], $c['request']->getUri())); return $view; }])); require 'middlewares.php'; $app->get('/', function ($req, $res, $args) { return $res->write('Hello NTUSC!'); }); $app->group('/api', function () use($app) { include 'routes/api/college.php'; include 'routes/api/committee.php'; include 'routes/api/leave.php'; include 'routes/api/login.php'; include 'routes/api/session.php'; include 'routes/api/sitting.php'; include 'routes/api/student.php'; })->add(function ($req, $res, $next) { $res->withHeader('Content-Type', 'application/json; charset=utf-8'); return $next($req, $res); }); $app->get('/internal/login', function ($req, $res, $args) { return $this->view->render($res, 'internal/login.html'); }); $app->group('/internal', function () use($app) { $app->get('/', function ($req, $res, $args) { return $this->view->render($res, 'internal/index.html', ['active_menu' => 'home', 'title' => "顆顆"]); }); $app->get('/logout', function ($req, $res, $args) {
<?php $container = (require 'Container.php'); $app = new \Slim\App($container); $app->group('/api/v1', function () use($app) { $app->any('/data/{table}[/{id}]', function ($req, $res, $args) { $middleware = $this->get('retrieveData'); return $middleware($req, $res); })->add('parser'); }); $app->run();
$app->group('/useradmin', function () use($app) { // basic user information $app->any('/info/{userId}', function (Request $request, Response $response) { $session = $this->session; $ssp = $this->ssp; $userId = $request->getAttribute('userId'); $admin = new UserAdmin($session, $ssp, $userId); return $response->getBody()->write($admin->displayMisc()); }); // change basic user information $app->any('/chInfo', function (Request $request, Response $response) { $session = $this->session; $ssp = $this->ssp; $userId = $request->getAttribute('userId'); $admin = new UserAdmin($session, $ssp, $userId); return $response->getBody()->write($admin->userMisc(false, true)); }); // change password $app->any('/chPswd', function (Request $request, Response $response) { $session = $this->session; $ssp = $this->ssp; $userId = $request->getAttribute('userId'); $needPassword = $request->getAttribute('needPassword'); $admin = new UserAdmin($session, $ssp, $userId); return $response->getBody()->write($admin->changePassword("", $needPassword, true)); }); // change email $app->any('/chEmail', function (Request $request, Response $response) { $session = $this->session; $ssp = $this->ssp; $userId = $request->getAttribute('userId'); $needPassword = $request->getAttribute('needPassword'); $admin = new UserAdmin($session, $ssp, $userId); return $response->getBody()->write($admin->changeEmail($needPassword, true)); }); // change advanced user information $app->any('/chAdv', function (Request $request, Response $response) { $session = $this->session; $ssp = $this->ssp; $userId = $request->getAttribute('userId'); $admin = new UserAdmin($session, $ssp, $userId); return $response->getBody()->write($admin->changeAdmin()); }); // display advanced user information $app->any('/advInfo', function (Request $request, Response $response) { $session = $this->session; $ssp = $this->ssp; $userId = $request->getAttribute('userId'); $admin = new UserAdmin($session, $ssp, $userId); return $response->getBody()->write($admin->displayAdminInfo()); }); // send a join email $app->any('/joinEmail', function (Request $request, Response $response) { $session = $this->session; $ssp = $this->ssp; $userId = $request->getAttribute('userId'); $admin = new UserAdmin($session, $ssp, $userId); return $response->getBody()->write($admin->sendJoinupEmail()); }); // send an email to a user $app->any('/email', function (Request $request, Response $response) { $session = $this->session; $ssp = $this->ssp; $userId = $request->getAttribute('userId'); $admin = new UserAdmin($session, $ssp, $userId); return $response->getBody()->write($admin->emailUser($userId, $session->userId)); }); })->add(function (Request $request, Response $response, $next) {