public function enable(Slim $app) { $this->app = $app; $this->config = $this->app->config('api'); $this->factory = new Factory($this->config['resources']); // Middleware $this->app->add(new Database()); $this->app->add(new ApiMiddleware($this->config)); // Routes $this->app->get($this->config['prefix'] . '/:resource/:id', [$this, 'getAction'])->conditions(['id' => '\\d+'])->name('resource_get'); $this->app->get($this->config['prefix'] . '/:resource', [$this, 'listAction'])->name('resource_get_list'); $this->app->put($this->config['prefix'] . '/:resource/:id', [$this, 'putAction'])->conditions(['id' => '\\d+'])->name('resource_put'); $this->app->post($this->config['prefix'] . '/:resource', [$this, 'postAction'])->name('resource_post'); $this->app->delete($this->config['prefix'] . '/:resource/:id', [$this, 'deleteAction'])->conditions(['id' => '\\d+'])->name('resource_delete'); }
public static function slimSetup(\Slim\Slim &$slim, One_Scheme $scheme) { //TODO: read specs from behaviour options or from a file $opt = $scheme->get('behaviorOptions.restable'); $route = $opt['route']; // retrieve $slim->get("/{$route}", function () use($scheme) { One_Controller_Rest::restGetAll($scheme); }); // retrieve one $slim->get("/{$route}/:idOrAlias", function ($idOrAlias) use($scheme) { One_Controller_Rest::restGet($scheme, $idOrAlias); }); // create new $slim->post("/{$route}", function () use($scheme) { One_Controller_Rest::restPost($scheme); }); // update existing $slim->put("/{$route}/:idOrAlias", function ($idOrAlias) use($scheme) { One_Controller_Rest::restPut($scheme, $idOrAlias); }); // delete existing $slim->delete("/{$route}/:idOrAlias", function ($idOrAlias) use($scheme) { One_Controller_Rest::restDelete($scheme, $idOrAlias); }); }
private function addRoutesFromMeta(Slim $application, ClassMetadata $meta, Controller $controller) { $entitiesRoute = $this->getEntitiesRoute($meta); // Fetch entities route $application->get($entitiesRoute, function () use($meta, $controller) { $controller->getEntities($meta); }); // Create entity $application->post($entitiesRoute, function () use($meta, $controller) { $controller->createEntity($meta); }); $entityRoute = $this->getEntityRoute($meta, $entitiesRoute); // Get entity $application->get($entityRoute, function () use($meta, $controller) { $controller->getEntity($meta, func_get_args()); }); // Update entity $application->put($entityRoute, function () use($meta, $controller) { $controller->updateEntity($meta, func_get_args()); }); // Patch entity $application->patch($entityRoute, function () use($meta, $controller) { $controller->patchEntity($meta, func_get_args()); }); // Delete entity $application->delete($entityRoute, function () use($meta, $controller) { $controller->deleteEntity($meta, func_get_args()); }); // Handling associated entities foreach ($meta->getAssociationMappings() as $aName => $aData) { $aTargetClass = $meta->getAssociationTargetClass($aName); $aMeta = $this->getEntityMeta($aTargetClass); $aEntitiesRoute = $entityRoute . '/' . $aName; // Create associated entity // allow to create entity and link source together // POST /articles/1/tags will fetch article 1, create tag entity and // associate it to article 1 $application->post($aEntitiesRoute, function () use($meta, $aMeta, $controller, $aData) { $controller->createEntity($aMeta, $aData['fieldName'], $meta, func_get_args()); }); // List associated entities $application->get($aEntitiesRoute, function () use($meta, $controller, $aData) { $controller->getAssociatedEntities($aData['fieldName'], $meta, func_get_args()); }); // Associate two entities // POST /articles/1/tags/2 will associate article 1 to tag 2 $aEntityRoute = $this->getEntityRoute($aMeta, $aEntitiesRoute); $application->post($aEntityRoute, function () use($meta, $aMeta, $controller, $aData) { $controller->associateEntities($aMeta, $aData['fieldName'], $meta, func_get_args()); }); } return $application; }
private function _initRoutes() { $this->_slim->contentType('application/json'); $this->_slim->get('/basket/', array($this, 'getBaskets')); $this->_slim->get('/product/', array($this, 'getProducts')); $this->_slim->get('/basket/:id', array($this, 'getBasket')); $this->_slim->get('/basket/:id/item/', array($this, 'getBasketItems')); $this->_slim->get('/basket/:id/item/:prodId', array($this, 'getBasketItem')); $this->_slim->post('/basket/:id/item/', array($this, 'postBasketItem')); $this->_slim->put('/basket/:id/item/:prodId', array($this, 'putBasketItem')); $this->_slim->delete('/basket/:id/item/:prodId', array($this, 'deleteBasketItem')); }
function routes(\Slim\Slim $app) { $base = $this->getBasePath(); $app->post($base . '/posts/search', function () use($app) { $app->Posts->search(); }); $app->post($base . '/posts/:id', function ($id) use($app) { $app->Posts->getById($id); }); $app->get($base . '/posts/:id', function ($id) use($app) { $app->Posts->getById($id); }); $app->post($base . '/posts', function () use($app) { $app->Posts->save(); }); $app->delete($base . '/posts/:id', function ($id) use($app) { $app->Posts->delete($id); }); }
private function loadMethodAnnotations(Slim $app, \ReflectionMethod $method, $newInstanceClass, $uri) { $methodAnnotations = $this->getMethodAnnotations($method); $uriMethod = ''; if (isset($methodAnnotations['SlimAnnotation\\Mapping\\Annotation\\Path'])) { $uriMethod = $methodAnnotations['SlimAnnotation\\Mapping\\Annotation\\Path']->uri; } $uri = $this->normalizeURI($uri, $uriMethod); if (isset($methodAnnotations['SlimAnnotation\\Mapping\\Annotation\\POST'])) { $app->post($uri, $method->invoke($newInstanceClass)); } if (isset($methodAnnotations['SlimAnnotation\\Mapping\\Annotation\\GET'])) { $app->get($uri, $method->invoke($newInstanceClass)); } if (isset($methodAnnotations['SlimAnnotation\\Mapping\\Annotation\\DELETE'])) { $app->delete($uri, $method->invoke($newInstanceClass)); } if (isset($methodAnnotations['SlimAnnotation\\Mapping\\Annotation\\PUT'])) { $app->put($uri, $method->invoke($newInstanceClass)); } }
$news->worker('get_post', $id); }); $app->get('/news/edit/:id', function ($id) { require '../news/news.worker.php'; $news = new news(); $news->worker('edit_post', $id); }); $app->put('/news/edit/:id', function () { require '../news/news.worker.php'; $data = json_decode(Slim::getInstance()->request()->getBody(), true); $news = new news(); $news->worker('save_edit', $data); }); $app->delete('/news/:id', function ($id) { require '../news/news.worker.php'; $news = new news(); $news->worker('delete_post', $id); }); $app->get('/featured', function () { require '../news/news.worker.php'; $news = new news(); $news->worker('featured'); }); // ////////////////////////////// // Forum // Get Categories $app->get('/forum/cat', function () { require '../forum/forum.worker.php'; $forum = new forum(); $forum->worker('get_categories'); });
<?php /* Author - Diego Alejandro Ramirez Contact - darasat@gmail.com */ require 'Slim/Slim.php'; use Slim\Slim; Slim::registerAutoloader(); $app = new Slim(); $app->get('/session', 'getSession'); $app->get('/getPhotos', 'getPhotos'); $app->get('/getPhoto/:id', 'getPhoto'); $app->post('/addPhoto', 'addPhoto'); $app->put('/updatePhoto/:id', 'updatePhoto'); $app->delete('/deletePhoto/:id', 'deletePhoto'); $app->run(); // Get Database Connection function getSession() { $db = new DB_Connection(); } function DB_Connection() { $dbhost = "127.0.0.1"; $dbuser = "******"; $dbpass = ""; $dbname = "ino"; $dbh = new PDO("mysql:host={$dbhost};dbname={$dbname}", $dbuser, $dbpass); $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); return $dbh;
require 'config.php'; require 'Slim/Slim.php'; require 'BasicAuth.php'; use Slim\Slim; use Slim\Extras\Middleware\HttpBasicAuth; Slim::registerAutoloader(); $app = new Slim(); if (USE_ADMIN_LOGIN) { $app->add(new BasicAuth(ADMIN_USERNAME, ADMIN_PASSWORD, 'private', array(new Route('DELETE', '/records'), new Route('DELETE', '/explorations'), new Route('PUT', '/explorations'), new Route('POST', '/explorations')))); } //exploration routes $app->get('/explorations/', 'listExplorations'); $app->get('/explorations/:id', 'getExploration'); $app->put('/explorations/:id', 'saveExploration'); $app->post('/explorations/', 'saveExploration'); $app->delete('/explorations/:id', 'deleteExploration'); //record routes $app->get('/records/:arg', 'getRecord'); $app->get('/records/', function () use($app) { $req = $app->request->params('exploration_id'); getRecords($req); }); $app->delete('/records/:arg', 'deleteRecord'); //upload record routes $app->post('/records/submit/', 'submitRecord'); $app->post('/records/upload/', 'uploadRecordFile'); $app->run(); /* Exploration Methods */ function getExploration($arg) { try {
$following = UserService::following($_SESSION['username']); $unfollowUrl = $app->urlFor('social-unfollow', array('userToUnfollow' => null)); $return = array(); foreach ($following as $friend) { $content = array_merge(array('unfollowUrl' => $unfollowUrl), $friend->toArray()); $return[] = $app->view->getInstance()->render('graphs/social/friends-partial', $content); } $app->jsonResponse->build(array('following' => $return)); })->name('social-follow'); // takes current user session and will unfollow :username $app->delete('/unfollow/:userToUnfollow', function ($userToUnfollow) use($app) { UserService::unfollowUser($_SESSION['username'], $userToUnfollow); $following = UserService::following($_SESSION['username']); $unfollowUrl = $app->urlFor('social-unfollow', array('userToUnfollow' => null)); $return = array(); foreach ($following as $friend) { $content = array_merge(array('unfollowUrl' => $unfollowUrl), $friend->toArray()); $return[] = $app->view->getInstance()->render('graphs/social/friends-partial', $content); } $app->jsonResponse->build(array('following' => $return)); })->name('social-unfollow'); //search users by name $app->get('/searchbyusername/:search', function ($search) use($app) { $users = UserService::searchByUsername($search, $_SESSION['username']); $app->jsonResponse->build(array('users' => $users)); })->name('user-search'); // social - show posts $app->get('/posts', $isLoggedIn, function () use($app) { $content = ContentService::getContent($_SESSION['username'], 0); $socialContent = array_slice($content, 0, 3); $moreContent = count($content) >= 4;
require_once dirname(__FILE__) . '/Implementacion/Cargo.php'; require_once dirname(__FILE__) . '/Implementacion/Tarjeta.php'; require_once dirname(__FILE__) . '/Implementacion/Cliente.php'; require_once dirname(__FILE__) . '/Implementacion/Plan.php'; use Slim\Slim; Slim::registerAutoloader(); $app = new Slim(array('debug' => true, 'log.level' => \Slim\Log::DEBUG, 'log.enabled' => true, 'log.writer' => new \Slim\LogWriter(fopen(dirname(__FILE__) . '/log/' . date('Y-M-d') . '.log', 'a')))); $app->get('/v1/monetizador/test', "ping"); //Cargos $app->get('/v1/monetizador/cargos', "cargos"); $app->post('/v1/monetizador/cargos', "cargos"); $app->post('/v1/monetizador/cargos/clientes:/id', "cargos"); //Tarjetas $app->get('/v1/monetizador/tarjetas', "cards"); $app->post('/v1/monetizador/tarjetas', "cardAdd"); $app->delete("/v1/monetizador/tarjetas/:id", "cardDelete"); // Cliente $app->post("/v1/monetizador/clientes", "cliente"); $app->get("/v1/monetizador/clientes", "clienteListar"); $app->get("/v1/monetizador/clientes/:id", "clienteListar"); $app->delete("/v1/monetizador/clientes/:id", "clienteEliminar"); $app->put("/v1/monetizador/clientes/:id", "clienteEditar"); // Cliente - Tarjeta $app->post('/v1/monetizador/tarjetas/clientes/:id', "cardAdd"); $app->get('/v1/monetizador/tarjetas/clientes/:id', "cards"); $app->delete("/v1/monetizador/clientes/:idcliente/tarjetas/:id", "cardDelete"); // Plan $app->post("/v1/monetizador/planes", "plan"); $app->get("/v1/monetizador/planes", "clienteListar"); $app->get("/v1/monetizador/planes/:id", "clienteListar"); $app->delete("/v1/monetizador/planes/:id", "clienteEliminar");
$params = new OdaPrepareInterface(); $params->arrayInput = array("teamA", "colorA", "teamB", "colorB"); $params->modePublic = false; $params->slim = $slim; $INTERFACE = new MatchInterface($params); $INTERFACE->create(); }); $slim->get('/match/:id/report/recap/', function ($id) use($slim) { $params = new OdaPrepareInterface(); $params->slim = $slim; $INTERFACE = new MatchInterface($params); $INTERFACE->getRecapForMatch($id); }); $slim->post('/match/event/', function () use($slim) { $params = new OdaPrepareInterface(); $params->arrayInput = array("matchId", "team"); $params->arrayInputOpt = array("twoMissing" => 0, "twoSuccess" => 0, "treeMissing" => 0, "treeSuccess" => 0, "oneMissing" => 0, "oneSuccess" => 0, "fault" => 0); $params->modePublic = false; $params->slim = $slim; $INTERFACE = new MatchInterface($params); $INTERFACE->createEvent(); }); $slim->delete('/match/:id/event/', function ($id) use($slim) { $params = new OdaPrepareInterface(); $params->modePublic = false; $params->slim = $slim; $INTERFACE = new MatchInterface($params); $INTERFACE->undoEvent($id); }); //-------------------------------------------------------------------------- $slim->run();
$app->get('/logout', 'logout'); // Logout // Backend // User section routes // user Dashboard $app->get('/dashboard/user/:id', 'showAccount'); // Show the account information $app->get('/dashboard/user_details/:id', 'showDetails'); // Show user Details $app->put('/dashboard/update/:id', 'updateDetails'); // Update user Details $app->put('/dashboard/account_type/:id', 'updateAccountType'); // Update user Details $app->put('/dashboard/account_pass/:id', 'updateAccountPass'); // Update user Details $app->delete('/dashboard/update/:id', 'deleteDetails'); // Delete user Details $app->get('/dashboard/user_deposit/:id', 'deposit'); // Show the Deposit Page $app->put('/dashboard/deposit/:id', 'updateDeposit'); // Route to accept the Deposit form $app->get('/dashboard/user_withdrawal/:id', 'withdrawal'); // Show the Withdrawal Page $app->put('/dashboard/withdrawal/:id', 'updateWithdrawal'); // Route to accept the Withdrawal form $app->get('/dashboard/user_history/:id', 'history'); // Show the History page // Admin section routes $app->get('/dashboard/admin/:id', 'listAccounts'); // Show the account information $app->get('/dashboard/add_account/:id', 'addAccount');
$app->get('/contacts/:id', $contentNegotiation, function ($id) use($app) { //This value should be specific to the current resource $lastModifiedTime = gmdate('D, d M Y H:i:s ') . ' GMT'; $app->response()->header('Last-Modified', $lastModifiedTime); $app->status(200); echo $app->render($app->template, ['contact' => ['contact_id' => $id, 'name' => $app->faker->firstName, 'last_name' => $app->faker->lastName]]); }); $app->put('/contacts/:id', $contentNegotiation, function ($id) use($app) { $contactInformation = $app->request()->getBody(); parse_str($contactInformation, $contact); $contact['contact_id'] = $id; if (empty($contact['name'])) { $contact['name'] = $app->faker->firstName; } if (empty($contact['last_name'])) { $contact['last_name'] = $app->faker->lastName; } $lastModifiedTime = time(); $app->lastModified($lastModifiedTime); $app->status(200); echo $app->render($app->template, ['contact' => $contact]); }); $app->delete('/contacts/:id', function ($id) use($app) { //Delete contact here $app->status(204); }); $app->options('/contacts/:id', function ($id) use($app) { $validOptions = ['GET', 'HEAD', 'PUT', 'DELETE', 'OPTIONS']; $app->response()->header('Allow', implode(',', $validOptions)); }); $app->run();
} }); // Put $app->put('/:resource(/(:action)(/))', function ($resource, $subResource = null) use($app) { $resource = Resource::load($app->version, $resource, $subResource); if ($resource === null) { Resource::error(Resource::STATUS_NOT_FOUND, 'Cannot find requested resource.'); } else { $resource->put(); } }); // Delete $app->delete('/:resource(/(:action)(/))', function ($resource, $subResource = null) use($app) { $resource = Resource::load($app->version, $resource, $subResource); if ($resource === null) { Resource::error(Resource::STATUS_NOT_FOUND, 'Cannot find requested resource.'); } else { $resource->delete(); } }); // Options $app->options('/:resource(/(:action)(/))', function ($resource, $subResource = null) use($app) { $resource = Resource::load($app->version, $resource, $subResource); if ($resource === null) { Resource::error(Resource::STATUS_NOT_FOUND, 'Cannot find requested resource.'); } else { $resource->options(); } }); // Not found $app->notFound(function () { Resource::error(Resource::STATUS_NOT_FOUND, 'Cannot find requested resource.');
$app->post('/auth/login', function () use($authController) { $authController->login(); }); $app->get('/auth/logout', $authenticated, function () use($authController) { $authController->logout(); }); $app->get('/emojis', function () use($emojiController) { $emojiController->getAll(); }); $app->post('/emojis', function () use($emojiController) { $emojiController->addEmoji(); }); $app->get('/emojis/:id', function ($id) use($emojiController) { $emojiController->findEmoji($id); }); $app->post('/emojis/:id', function ($id) use($emojiController) { $emojiController->updateEmoji($id); }); $app->patch('/emojis/:id', function ($id) use($emojiController) { $emojiController->updateEmoji($id); }); $app->put('/emojis/:id', function ($id) use($emojiController) { $emojiController->updateEmoji($id); }); $app->delete('/emoji/:id', $authenticated, function ($id) use($emojiController) { $emojiController->deleteEmoji($id); }); $app->get('/', function () { echo "Welcome to Naija Emoji Service"; }); $app->run();
<?php require 'vendor/autoload.php'; use Slim\Slim; $app = new Slim(); // Replace /comphppuebla/guzzle for the path to your http-verbs.php file to try this route. // curl -X GET http://localhost/comphppuebla/guzzle/contacts/1 $app->get('/contacts/:id', function ($id) { echo "Request via GET with ID = {$id}"; }); // Replace /comphppuebla/guzzle for the path to your http-verbs.php file to try this route. // curl -X POST http://localhost/comphppuebla/guzzle/contacts $app->post('/contacts', function () { echo "Request via POST"; }); // Replace /comphppuebla/guzzle for the path to your http-verbs.php file to try this route. // curl -X PUT http://localhost/comphppuebla/guzzle/contacts/2 $app->put('/contacts/:id', function ($id) { echo "Request via PUT with ID = {$id}"; }); // Replace /comphppuebla/guzzle for the path to your http-verbs.php file to try this route. // curl -X DELETE http://localhost/comphppuebla/guzzle/contacts/3 $app->delete('/contacts/:id', function ($id) { echo "Request via DELETE with ID = {$id}"; }); // Replace /comphppuebla/guzzle for the path to your http-verbs.php file to try this route. // curl -X OPTIONS http://localhost/comphppuebla/guzzle/contacts/4 $app->options('/contacts/:id', function ($id) { echo "Request via OPTIONS with ID = {$id}"; }); $app->run();
require_once '../DAL/Entity/Course.php'; require_once '../DAL/DAO/CourseDAO.php'; require_once '../DAL/Database.php'; require_once '../DAL/DAO/EnrollmentDAO.php'; require_once '../DAL/Entity/Enrollment.php'; require_once '../DAL/DAO/UserDAO.php'; require_once '../DAL/Entity/User.php'; use Slim\Slim; use Entity\Employee; use DAO\EmployeeDAO; Slim::registerAutoloader(); $app = new Slim(); $app->post('/employee', 'registerEmployee'); $app->get('/employees', 'getEmployees'); $app->put('/employee', 'updateEmployee'); $app->delete('/employee/:id', 'deleteEmployee'); $app->post('/student', 'registerStudent'); $app->get('/students', 'getStudents'); $app->put('/student', 'updateStudent'); $app->delete('/student/:id', 'deleteStudent'); $app->get('/courses', 'getCourses'); $app->post('/course', 'addCourse'); $app->put('/course', 'updateCourse'); $app->delete('/course/:id', 'deleteCourse'); $app->get('/enrollments', 'getEnrollments'); $app->post('/enrollment', 'addEnrollment'); $app->post('/login', 'login'); $app->get('/login', 'getStatus'); $app->get('/logout', 'logout'); $app->run(); function getEmployees()
/** * Create a Slim WebServices Application * * @param string $appName Application Name * @param string $key V3ctor WareHouse Key */ public function __construct($appName, $key) { $this->_key = $key; $this->_app = $appName; // Load Slim Application \Slim\Slim::registerAutoloader(); // Init Slim Application $this->web = new \Slim\Slim(); // Run WebServices Application $v3ctor = V3WareHouse::getInstance(); if (!$v3ctor->isConnected()) { $msg = array("error" => 'Unable load V3ctor WareHouse'); die(json_encode($msg)); } // Add Default Routes // Welcome $this->web->get('/', function () { $app = \Slim\Slim::getInstance(); $app->response()->header('Content-Type', 'application/json'); $app->response()->status(200); $msg = array("msg" => 'Welcome to V3ctor WareHouse Application ' . $this->_app); echo json_encode($msg); }); // Gets Object by _id $this->web->get('/(:entity)/(:id)', function ($entity, $id) { $app = \Slim\Slim::getInstance(); $v3ctor = V3WareHouse::getInstance(); $this->validateKey($app); $app->response()->header('Content-Type', 'application/json'); $app->response()->status(200); echo json_encode($v3ctor->findObject($entity, $id)); }); // Sets a New Object $this->web->post('/(:entity)', function ($entity) { $app = \Slim\Slim::getInstance(); $v3ctor = V3WareHouse::getInstance(); $this->validateKey($app); try { $body = $app->request->getBody(); $jsonData = json_decode($body); $app->response()->header('Content-Type', 'application/json'); $app->response()->status(200); echo json_encode($v3ctor->newObject($entity, $jsonData)); } catch (ResourceNotFoundException $e) { $app->response()->status(404); } catch (Exception $e) { $app->response()->status(400); $app->response()->header('X-Status-Reason', $e->getMessage()); } }); // Update a Object $this->web->put('/(:entity)/(:id)', function ($entity, $id) { $app = \Slim\Slim::getInstance(); $v3ctor = V3WareHouse::getInstance(); $this->validateKey($app); try { $body = $app->request->getBody(); $jsonData = json_decode($body); $app->response()->header('Content-Type', 'application/json'); $app->response()->status(200); $result = $v3ctor->updateObject($entity, $id, $jsonData); $msgOk = array('msg' => 'OK'); $msgBad = array('msg' => 'ERROR'); if ($result) { echo json_encode($msgOk); } else { echo json_encode($msgBad); } } catch (ResourceNotFoundException $e) { $app->response()->status(404); } catch (Exception $e) { $app->response()->status(400); $app->response()->header('X-Status-Reason', $e->getMessage()); } }); // Delete a Object $this->web->delete('/(:entity)/(:id)', function ($entity, $id) { $app = \Slim\Slim::getInstance(); $v3ctor = V3WareHouse::getInstance(); $this->validateKey($app); $app->response()->header('Content-Type', 'application/json'); $app->response()->status(200); $result = $v3ctor->deleteObject($entity, $id); $msgOk = array('msg' => 'OK'); $msgBad = array('msg' => 'ERROR'); if ($result) { echo json_encode($msgOk); } else { echo json_encode($msgBad); } }); // Find Objects by Query $this->web->post('/query/(:entity)', function ($entity) { $app = \Slim\Slim::getInstance(); $v3ctor = V3WareHouse::getInstance(); $this->validateKey($app); try { $body = $app->request->getBody(); $jsonQuery = json_decode($body); $app->response()->header('Content-Type', 'application/json'); $app->response()->status(200); $jsonQuery = (array) $jsonQuery; echo json_encode($v3ctor->query($entity, $jsonQuery)); } catch (ResourceNotFoundException $e) { $app->response()->status(404); } catch (Exception $e) { $app->response()->status(400); $app->response()->header('X-Status-Reason', $e->getMessage()); } }); // Not Sent Key $this->web->get('/notkey', function () { $app = \Slim\Slim::getInstance(); $app->response()->header('Content-Type', 'application/json'); $app->response()->status(404); $msg = array("error" => "Not Sent Key"); echo json_encode($msg); }); // Not Valid Key $this->web->get('/invalidkey', function () { $app = \Slim\Slim::getInstance(); $app->response()->header('Content-Type', 'application/json'); $app->response()->status(404); $msg = array("error" => "Permission denied"); echo json_encode($msg); }); /************************* JSONP *************************/ // Gets Object by _id $this->web->get('/jsonp/get/(:entity)/(:id)', function ($entity, $id) { $app = \Slim\Slim::getInstance(); $v3ctor = V3WareHouse::getInstance(); $this->validateKey($app); $callback = $app->request()->get('callback'); if (is_null($callback)) { $app->response()->status(400); } else { try { $app->response()->header('Content-type: text/javascript'); $app->response()->status(200); $jsonResult = json_encode($v3ctor->findObject($entity, $id)); echo "{$callback}(" . $jsonResult . ");"; } catch (ResourceNotFoundException $e) { $app->response()->status(404); } catch (Exception $e) { $app->response()->status(400); $app->response()->header('X-Status-Reason', $e->getMessage()); } } }); // Find Objects by Query $this->web->get('/jsonp/query/(:entity)', function ($entity) { $app = \Slim\Slim::getInstance(); $v3ctor = V3WareHouse::getInstance(); $this->validateKey($app); $callback = $app->request()->get('callback'); if (is_null($callback)) { $app->response()->status(400); } else { try { $app->response()->header('Content-type: text/javascript'); $app->response()->status(200); $jsonData = $app->request()->get('data'); $jsonData = json_decode($jsonData); $jsonResult = json_encode($v3ctor->query($entity, $jsonData)); echo "{$callback}(" . $jsonResult . ");"; } catch (ResourceNotFoundException $e) { $app->response()->status(404); } catch (Exception $e) { $app->response()->status(400); $app->response()->header('X-Status-Reason', $e->getMessage()); } } }); // Sets a New Object $this->web->get('/jsonp/new/(:entity)', function ($entity) { $app = \Slim\Slim::getInstance(); $v3ctor = V3WareHouse::getInstance(); $this->validateKey($app); $callback = $app->request()->get('callback'); if (is_null($callback)) { $app->response()->status(400); } else { try { $app->response()->header('Content-type: text/javascript'); $app->response()->status(200); $jsonData = $app->request()->get('data'); $jsonData = json_decode($jsonData); $jsonResult = json_encode($v3ctor->newObject($entity, $jsonData)); echo "{$callback}(" . $jsonResult . ");"; } catch (ResourceNotFoundException $e) { $app->response()->status(404); } catch (Exception $e) { $app->response()->status(400); $app->response()->header('X-Status-Reason', $e->getMessage()); } } }); // Update a Object $this->web->get('/jsonp/upd/(:entity)/(:id)', function ($entity, $id) { $app = \Slim\Slim::getInstance(); $v3ctor = V3WareHouse::getInstance(); $this->validateKey($app); $callback = $app->request()->get('callback'); if (is_null($callback)) { $app->response()->status(400); } else { try { $app->response()->header('Content-type: text/javascript'); $app->response()->status(200); $jsonData = $app->request()->get('data'); $jsonData = json_decode($jsonData); $msgOk = array('msg' => 'OK'); $msgBad = array('msg' => 'ERROR'); $result = $v3ctor->updateObject($entity, $id, $jsonData); if ($result) { $jsonResult = json_encode($msgOk); } else { $jsonResult = json_encode($msgBad); } echo "{$callback}(" . $jsonResult . ");"; } catch (ResourceNotFoundException $e) { $app->response()->status(404); } catch (Exception $e) { $app->response()->status(400); $app->response()->header('X-Status-Reason', $e->getMessage()); } } }); // Delete a Object $this->web->get('/jsonp/del/(:entity)/(:id)', function ($entity, $id) { $app = \Slim\Slim::getInstance(); $v3ctor = V3WareHouse::getInstance(); $this->validateKey($app); $callback = $app->request()->get('callback'); if (is_null($callback)) { $app->response()->status(400); } else { try { $app->response()->header('Content-type: text/javascript'); $app->response()->status(200); $msgOk = array('msg' => 'OK'); $msgBad = array('msg' => 'ERROR'); $result = $v3ctor->deleteObject($entity, $id); if ($result) { $jsonResult = json_encode($msgOk); } else { $jsonResult = json_encode($msgBad); } echo "{$callback}(" . $jsonResult . ");"; } catch (ResourceNotFoundException $e) { $app->response()->status(404); } catch (Exception $e) { $app->response()->status(400); $app->response()->header('X-Status-Reason', $e->getMessage()); } } }); }
}); $app->get('/messages/:id', function ($id) use($predis, $app) { $data = $predis->hget(BULK_HASH, $id); if (!$data) { $app->response->setStatus(404); return; } $result = json_decode($data, true); $result['id'] = $id; $app->response->headers->set('Content-Type', 'application/json'); $app->response->setStatus(200); echo json_encode($result); }); $app->delete('/messages/:id', function ($id) use($predis, $app) { $data = $predis->hget(BULK_HASH, $id); if (!$data) { $app->response->setStatus(404); return; } $predis->hdel(BULK_HASH, $id); $app->response->setStatus(204); }); $app->delete('/messages', function () use($predis, $app) { $data = $predis->hgetall(BULK_HASH); foreach ($data as $id => $message) { $predis->hdel(BULK_HASH, $id); } $app->response->headers->set('Content-Type', 'application/json'); $app->response->setStatus(204); }); $app->run();
function delete($pattern, $controller, $method, $filter = null) { if (!is_callable($filter)) { $filter = function () { }; } return parent::delete($pattern, $filter, function () use($controller, $method) { $instance = new $controller(); $args = func_get_args(); call_user_func_array(array($instance, $method), $args); }); }
<?php require 'Slim/Slim.php'; \Slim\Slim::registerAutoloader(); use Slim\Slim; $app = new Slim(array('debug' => true)); $app->get('/equipments', 'readEquipments'); $app->get('/equipments/:id', 'readEquipment'); $app->post('/equipments', 'createEquipment'); $app->put('/equipments/:id', 'updateEquipment'); $app->delete('/equipments/:id', 'deleteEquipment'); $app->get('/peoples', 'readPeople'); $app->get('/peoples/:id', 'readPerson'); $app->post('/peoples', 'createPerson'); $app->put('/peoples/:id', 'updatePerson'); $app->delete('/peoples/:id', 'deletePerson'); $app->run(); $mongoHost = 'localhost'; function readEquipments() { try { global $mongoHost; $connection = new MongoClient($mongoHost); $db = $connection->Equipments; $collection = $db->equipments; $cursor = $collection->find(); $equipments = []; foreach ($cursor as $obj) { array_push($equipments, $obj); } echo json_encode($equipments);
error_reporting(E_ALL); } date_default_timezone_set("UTC"); // registra Slim::registerAutoloader(); // inicializa e configura as rotas $app = new Slim(array('mode' => ENVIRONMENT == ENVIRONMENT_PROD ? 'production' : 'development')); if (CROSS_ORIGIN_ENABLED) { $app->response()->header('Access-Control-Allow-Origin', ACCESS_CONTROL_ALLOW_ORIGIN); } $app->get('/users/:userId/devices', 'authorize', 'getUserDevices'); $app->get('/users', 'authorize', 'getUsers'); $app->get('/devices', 'authorize', 'getDevices'); $app->post('/devices', 'authorize', 'createDevice'); $app->put('/devices', 'authorize', 'updateDevice'); $app->delete('/devices', 'authorize', 'deleteDevice'); $app->post('/notifications', 'authorize', 'sendNotification'); $app->run(); /** * Busca usuários que possuem dispositivos cadastrados * * Permite paginação através do parâmetros: * - page: página a ser retornada * - limit: quantidade de resultados a serem retornados */ function getUsers() { global $log; $app = Slim::getInstance(); try { $request = $app->request();
$app->halt(409, $result); } } else { if (is_numeric($result)) { $app->redirect($app->urlFor('departmentsList')); } else { $app->flash('error', $result); $app->redirect($app->urlFor('departmentAdd')); } } })->name('departmentAdd'); $app->delete('/admin/departments/delete/:department', function ($departmentID) use($app) { $result = deleteDepartment($app->db, $departmentID); if (empty($result)) { $app->halt(200); } else { $app->halt(500, $result); } $app->halt('500', 'Not implemented yet.'); }); $app->get('/admin/departments/edit/:department', function ($departmentID) use($app) { $app->render('html/editDepartment.html', array('department' => getDepartment($app->db, $departmentID))); })->name('editDepartment'); $app->post('/admin/departments/edit/:department', function ($departmentID) use($app) { $result = editDepartment($app->db, $departmentID, $app->request->post('name')); if ($app->request->post('ajax') === 'true') { if ($result === false) { $app->halt(409, $statement->errorInfo()[2]); } else { $app->halt(200); }
/** * @SWG\Api( * path="/gas-stations/{gasStationId}", * @SWG\Operation( * method="DELETE", * summary="Delete the information of a gas station", * nickname="deleteGasStation", * @SWG\Parameters( * @SWG\Parameter( * name="Accept", * description="The type of response that the web service client expects", * paramType="header", * required=true, * type="string", * enum="['application/json', 'application/xml']" * ), * @SWG\Parameter( * name="gasStationId", * description="ID of gas station that needs to be deleted", * paramType="path", * required=true, * type="integer" * ) * ), * @SWG\ResponseMessage( * code=404, * message="Gas station not found" * ) * ) * ) */ protected function deleteStation() { $this->app->delete('/gas-stations/:id', function ($id) { $this->app->stationController->delete($id); }); }
$app->patch('/emojis/:id', $authenticated, function ($id) use($emojiController) { $emojiController->updateEmoji($id); }); /* | "/emojis" find an emoji by id | POST method */ $app->get('/emojis/:id', function ($id) use($emojiController) { $emojiController->findEmoji($id); }); /* | "/emojis/:id" find and delete an emoji by id | DELETE method */ $app->delete('/emojis/:id', function ($id) use($emojiController) { $emojiController->deleteEmoji($id); }); /* | login */ $app->post('/auth/login', function () use($authController) { $authController->login(); }); /* | logout */ $app->post('/auth/logout', $authenticated, function () use($authController) { $authController->logout(); }); /* | register
/** * @param string $routeName * @param string $tableName * @param callable $customCRUDFunction * @param string $displayName */ public function add($routeName, $customCRUDFunction = null, $tableName = null, $displayName = null) { if ($tableName == null) { $tableName = $routeName; } $this->tableList[$routeName] = $tableName; $this->tableDisplayName[$routeName] = $displayName; $this->routeNameList[] = $routeName; /* * Page Group (ListView, CreateView, EditView) */ $this->slim->group("/" . $this->groupName . "/" . $routeName, function () use($routeName, $customCRUDFunction, $tableName) { $this->slim->get("/", function () use($routeName) { $this->slim->redirectTo("_louisCRUD_" . $routeName); }); /* * ListView */ $this->slim->get("/list(/:p1(/:p2(/:p3(/:p4(/:p5)))))", function ($p1 = null, $p2 = null, $p3 = null, $p4 = null, $p5 = null) use($routeName, $customCRUDFunction, $tableName) { // MUST INIT FIRST $this->init($tableName, $routeName, $p1, $p2, $p3, $p4, $p5); if ($this->configFunction != null) { $function = $this->configFunction; $result = $function(); if ($result === false) { return; } } if ($customCRUDFunction != null) { $result = $customCRUDFunction($p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } if ($this->listviewFunction != null) { $listviewFunction = $this->listviewFunction; $result = $listviewFunction($p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } if ($this->isEnabledListView()) { $this->renderListView(); } })->name("_louisCRUD_" . $routeName); /* * Create */ $this->slim->get("/create(/:p1(/:p2(/:p3(/:p4(/:p5)))))", function ($p1 = null, $p2 = null, $p3 = null, $p4 = null, $p5 = null) use($routeName, $customCRUDFunction, $tableName) { // MUST INIT FIRST $this->init($tableName, $routeName, $p1, $p2, $p3, $p4, $p5); if ($this->configFunction != null) { $function = $this->configFunction; $result = $function(); if ($result === false) { return; } } if ($customCRUDFunction != null) { $result = $customCRUDFunction($p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } if ($this->createFunction != null) { $createFunction = $this->createFunction; $result = $createFunction($p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } // Force Hide ID field $this->field("id")->hide(); if ($this->isEnabledCreate()) { $this->renderCreateView(); } }); /* * Edit */ $this->slim->get("/edit/:id(/:p1(/:p2(/:p3(/:p4(/:p5)))))", function ($id, $p1 = null, $p2 = null, $p3 = null, $p4 = null, $p5 = null) use($routeName, $customCRUDFunction, $tableName) { // MUST INIT FIRST $this->init($tableName, $routeName, $p1, $p2, $p3, $p4, $p5); // Load Bean first $this->loadBean($id); // ID must be hidden $this->field("id")->hide(); if ($this->configFunction != null) { $function = $this->configFunction; $result = $function(); if ($result === false) { return; } } if ($customCRUDFunction != null) { $result = $customCRUDFunction($p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } if ($this->editFunction != null) { $editFunction = $this->editFunction; $result = $editFunction($id, $p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } // If user show the ID field, force set it to readonly $this->field("id")->setReadOnly(true); if ($this->isEnabledEdit()) { $this->renderEditView(); } }); /* * Export Excel */ $this->slim->map("/export(/:p1(/:p2(/:p3(/:p4(/:p5)))))", function ($p1 = null, $p2 = null, $p3 = null, $p4 = null, $p5 = null) use($routeName, $customCRUDFunction, $tableName) { // MUST INIT FIRST $this->init($tableName, $routeName, $p1, $p2, $p3, $p4, $p5); if ($this->configFunction != null) { $function = $this->configFunction; $result = $function(); if ($result === false) { return; } } if ($customCRUDFunction != null) { $result = $customCRUDFunction($p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } if ($this->listviewFunction != null) { $listviewFunction = $this->listviewFunction; $result = $listviewFunction($p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } if ($this->exportFunction != null) { $exportFunction = $this->exportFunction; $result = $exportFunction($p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } // TODO: isEnabledExport(); $this->renderExcel(); })->via('GET', 'POST'); }); /* * API Group, RESTful style. */ $this->slim->group("/" . $this->apiGroupName . "/" . $routeName, function () use($routeName, $customCRUDFunction, $tableName) { /* * JSON for Listview */ $this->slim->map("/list(/:p1(/:p2(/:p3(/:p4(/:p5)))))", function ($p1 = null, $p2 = null, $p3 = null, $p4 = null, $p5 = null) use($routeName, $customCRUDFunction, $tableName) { $this->enableJSONResponse(); // MUST INIT FIRST $this->init($tableName, $routeName, $p1, $p2, $p3, $p4, $p5); if ($this->configFunction != null) { $function = $this->configFunction; $result = $function(); if ($result === false) { return; } } if ($customCRUDFunction != null) { $result = $customCRUDFunction($p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } if ($this->listviewFunction != null) { $listviewFunction = $this->listviewFunction; $result = $listviewFunction($p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } if ($this->isEnabledListView()) { $this->getJSONList(); } return; })->via('GET', 'POST'); /* * For Datatables */ $this->slim->map("/datatables(/:p1(/:p2(/:p3(/:p4(/:p5)))))", function ($p1 = null, $p2 = null, $p3 = null, $p4 = null, $p5 = null) use($routeName, $customCRUDFunction, $tableName) { $this->enableJSONResponse(); // MUST INIT FIRST $this->init($tableName, $routeName, $p1, $p2, $p3, $p4, $p5); if ($this->configFunction != null) { $function = $this->configFunction; $result = $function(); if ($result === false) { return; } } if ($customCRUDFunction != null) { $result = $customCRUDFunction($p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } if ($this->listviewFunction != null) { $listviewFunction = $this->listviewFunction; $result = $listviewFunction($p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } if ($this->isEnabledListView()) { $this->getListViewJSONString(); } return; })->via('GET', 'POST'); /* * View a bean * PUT /api/{tableName}/{id} */ $this->slim->get("/:id(/:p1(/:p2(/:p3(/:p4(/:p5)))))", function ($id, $p1 = null, $p2 = null, $p3 = null, $p4 = null, $p5 = null) use($routeName, $customCRUDFunction, $tableName) { // MUST INIT FIRST $this->init($tableName, $routeName, $p1, $p2, $p3, $p4, $p5); // Load Bean $this->loadBean($id); if ($this->configFunction != null) { $function = $this->configFunction; $result = $function(); if ($result === false) { return; } } // Custom Global Function if ($customCRUDFunction != null) { $result = $customCRUDFunction($p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } // Custom Edit Function if ($this->editFunction != null) { $editFunction = $this->editFunction; $result = $editFunction($id, $p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } // Force hide ID $this->field("id")->hide(); // Insert into database if ($this->isEnabledEdit()) { $json = $this->getJSON(false); $this->enableJSONResponse(); echo $json; } }); /* * Insert a bean * POST /api/{tableName} */ $this->slim->post("(/:p1(/:p2(/:p3(/:p4(/:p5)))))", function ($p1 = null, $p2 = null, $p3 = null, $p4 = null, $p5 = null) use($routeName, $customCRUDFunction, $tableName) { // MUST INIT FIRST $this->init($tableName, $routeName, $p1, $p2, $p3, $p4, $p5); if ($this->configFunction != null) { $function = $this->configFunction; $result = $function(); if ($result === false) { return; } } if ($customCRUDFunction != null) { $result = $customCRUDFunction($p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } // Custom Global Function $result = $customCRUDFunction($p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } // Custom Create Function if ($this->createFunction != null) { $createFunction = $this->createFunction; $result = $createFunction($p1, $p2, $p3, $p4, $p5); } if ($result === false) { return; } // Force hide ID $this->field("id")->hide(); // Insert into database if ($this->isEnabledCreate()) { $jsonObject = $this->insertBean($_POST); $this->enableJSONResponse(); echo json_encode($jsonObject); } else { // TODO: Should be json object echo "No permission"; } }); /* * Update a bean * PUT /crud/{tableName}/{id} */ $this->slim->put("/:id(/:p1(/:p2(/:p3(/:p4(/:p5)))))", function ($id, $p1 = null, $p2 = null, $p3 = null, $p4 = null, $p5 = null) use($routeName, $customCRUDFunction, $tableName) { // MUST INIT FIRST $this->init($tableName, $routeName, $p1, $p2, $p3, $p4, $p5); // Load Bean $this->loadBean($id); if ($this->configFunction != null) { $function = $this->configFunction; $result = $function(); if ($result === false) { return; } } // Custom Global Function if ($customCRUDFunction != null) { $result = $customCRUDFunction($p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } // Custom Create Function if ($this->editFunction != null) { $editFunction = $this->editFunction; $result = $editFunction($id, $p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } // Force hide ID $this->field("id")->hide(); // Insert into database if ($this->isEnabledEdit()) { $jsonObject = $this->updateBean($this->slim->request()->params()); $this->enableJSONResponse(); echo json_encode($jsonObject); } }); /* * Delete a bean * DELETE /crud/{tableName}/{id} */ $this->slim->delete("/:id(/:p1(/:p2(/:p3(/:p4(/:p5)))))", function ($id, $p1 = null, $p2 = null, $p3 = null, $p4 = null, $p5 = null) use($routeName, $customCRUDFunction, $tableName) { // MUST INIT FIRST $this->init($tableName, $routeName, $p1, $p2, $p3, $p4, $p5); $this->enableJSONResponse(); $this->loadBean($id); if ($this->configFunction != null) { $function = $this->configFunction; $result = $function(); if ($result === false) { return; } } // Custom Global Function if ($customCRUDFunction != null) { $result = $customCRUDFunction($p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } // Custom Delete Function if ($this->deleteFunction != null) { $deleteFunction = $this->deleteFunction; $result = $deleteFunction($id, $p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } if ($this->isEnabledDelete()) { $this->deleteBean(); $result = new \stdClass(); $result->status = "succ"; echo json_encode($result); } }); }); }
} } } catch (\PDOException $e) { echo '{"error":{"text":' . $e->getMessage() . '}}'; } }); /** * Route to delete an emoji. */ $app->delete('/emojis/:id', function ($id) use($app) { try { $app->response()->headers("Content-Type", "application/json"); $authHeader = $app->request->headers->get('Authorization'); $decodedToken = Reusable::tokenVerify($authHeader); if ($decodedToken) { $emoji = Emoji::with('user')->where('id', $id)->first(); if ($emoji->user->token !== 1) { echo json_encode(array("status" => "Bad request", "message" => "Log in to delete the emoji!")); } else { Emoji::destroy($id); echo json_encode(array("status" => "success", "message" => "Emoji deleted!")); } } } catch (\PDOException $e) { echo '{"error":{"text":' . $e->getMessage() . '}}'; } }); /** * Run the Slim app. */ $app->run();