/** * @dataProvider authenticationDataProvider */ public function testRouteAuthentication($requestMethod, $path, $location, $hasIdentity, $identity, $httpStatus) { \Slim\Environment::mock(array('REQUEST_METHOD' => $requestMethod, 'PATH_INFO' => $path)); $this->auth->expects($this->once())->method('hasIdentity')->will($this->returnValue($hasIdentity)); $this->auth->expects($this->once())->method('getIdentity')->will($this->returnValue($identity)); $app = new \Slim\Slim(array('debug' => false)); $app->error(function (\Exception $e) use($app) { // Example of handling Auth Exceptions if ($e instanceof AuthException) { $app->response->setStatus($e->getCode()); $app->response->setBody($e->getMessage()); } }); $app->get('/', function () { }); $app->get('/member', function () { }); $app->delete('/member/photo/:id', function ($id) { }); $app->get('/admin', function () { }); $app->map('/login', function () { })->via('GET', 'POST')->name('login'); $app->add($this->middleware); ob_start(); $app->run(); ob_end_clean(); $this->assertEquals($httpStatus, $app->response->status()); $this->assertEquals($location, $app->response->header('location')); }
} require 'Slim/Slim.php'; \Slim\Slim::registerAutoloader(); /** * Step 2: Instantiate a Slim application * * This example instantiates a Slim application using * its default settings. However, you will usually configure * your Slim application now by passing an associative array * of setting names and values into the application constructor. */ $app = new \Slim\Slim(array('log.level' => \Slim\Log::EMERGENCY, 'debug' => false)); register_shutdown_function('fatalErrorShutdownHandler'); set_exception_handler('exception_handler'); set_error_handler('error_handler'); $app->error('exception_handler'); $app->log->setEnabled(false); error_reporting(~E_NOTICE); $app->response->headers->set('Content-Type', 'application/json'); $headers = $app->request->headers; header('Access-Control-Allow-Origin: ' . $headers['Origin']); header('Access-Control-Allow-Methods: POST, GET, OPTIONS'); header('Access-Control-Allow-Headers: pxp-user, content-type, Php-Auth-User, Php-Auth-Pw'); header('Access-Control-Allow-Credentials: true'); header('Access-Control-Max-Age: 1728000'); // get route /** * Step 3: Define the Slim application routes * * Here we define several Slim application routes that respond * to appropriate HTTP request methods. In this example, the second
//离开群 $request = new OpenimTribeQuitRequest(); $user = new OpenImUser(); $requestBody = json_decode(@file_get_contents('php://input'), true); $user->uid = $requestBody['username']; $user->taobao_account = "false"; $user->app_key = $appKey; $request->setUser(json_encode($user)); $request->setTribeId($requestBody['tribe_id']); $response = $client->execute($request); echo json_encode($response); }); $app->post('/custmsg/push', function () use($client, $appKey) { $request = new OpenimCustmsgPushRequest(); $custmsg = new CustMsg(); $requestBody = json_decode(@file_get_contents('php://input'), true); $custmsg->from_user = $requestBody['from_user']; $custmsg->to_appkey = $appKey; $custmsg->to_users = $requestBody['to_user']; $custmsg->summary = $requestBody['summary']; //消息摘要 $custmsg->data = $requestBody['data']; //自定义消息内容 $request->setCustmsg(json_encode($custmsg)); $response = $client->execute($request); echo json_encode($response); }); $app->error(function (\Exception $e) use($app) { echo json_encode($e); }); $app->run();
MgInitializeWebTier($webConfigPath); require_once dirname(__FILE__) . "/app/util/localizer.php"; require_once dirname(__FILE__) . "/app/util/utils.php"; $config = (require_once dirname(__FILE__) . "/app/config.php"); $logConfig = (require_once dirname(__FILE__) . "/app/log_config.php"); $config = array_merge($config, $logConfig); //Pull in the appropriate string bundle $strings = (require_once dirname(__FILE__) . "/app/res/lang/" . $config["Locale"] . ".php"); $app = new \Slim\Slim($config); //Override error handler for unhandled exceptions $app->error(function ($err) use($app) { $title = $app->localizer->getText("E_UNHANDLED_EXCEPTION"); $mimeType = MgMimeType::Html; //As part of validating the desired representation, this variable will be set, this will tell us //what mime type to shape the response if (isset($app->requestedMimeType)) { $mimeType = $app->requestedMimeType; } $details = $app->localizer->getText("E_PHP_EXCEPTION_DETAILS", $err->getMessage(), $err->getFile(), $err->getLine()); $app->response->header("Content-Type", $mimeType); $app->response->setBody(MgUtils::FormatException($app, "UnhandledError", $title, $details, $err->getTraceAsString(), 500, $mimeType)); }); $app->localizer = new Localizer($strings); //Set server version $ver = explode(".", SITE_ADMINISTRATOR_VERSION, 4); $app->MG_VERSION = array(intval($ver[0]), intval($ver[1]), intval($ver[2]), intval($ver[3])); $app->config("SelfUrl", $app->request->getUrl() . $app->request->getRootUri()); $un = new URL\Normalizer($app->config("SelfUrl") . "/" . $app->config("MapGuide.MapAgentUrl")); $app->config("MapGuide.MapAgentUrl", $un->normalize()); /* var_dump($app->localizer->getText("E_METHOD_NOT_SUPPORTED")); var_dump($app->localizer->getText("E_METHOD_NOT_SUPPORTED", "test"));
<?php error_reporting(E_ALL); require '../vendor/autoload.php'; $app = new \Slim\Slim(); require 'config.php'; require 'rest_dao.php'; require 'ta_mailer.php'; require 'help_classes.php'; $app->config('debug', false); $app->response->headers->set('Content-Type', 'application/json'); $app->error(function ($e) use($app) { echo '{"error":{ "text":"' . $e->getMessage() . '", "file":"' . $e->getFile() . '", "line":"' . $e->getLine() . "\"\n }}\n"; // file_put_contents(__DIR__.'/deb.txt', $deb); }); $app->notFound(function () use($app) { echo '{"error": 404 }'; }); $dao = new RestDAO(); $help = new Helper(); $mailer = new TA_Mailer(); $mailer->setTemplateDirectory('emails'); $auth = function () { $app = \Slim\Slim::getInstance(); $auth = new Auth(); $tokenAuth = $app->request->headers->get('Auth'); if (empty($tokenAuth) or !$auth->tokenOk($tokenAuth)) { $app->response->setStatus(401);
return $r->respond(400, 'BAD REQUEST', true); } $data = R::findOne($tableName, 'id = ?', array($id)); if ($data) { $existingSyncMeta = R::findOne('syncmeta', 'where row_id = ? and tableName = ?', array($id, $tableName)); if ($existingSyncMeta) { $existingSyncMeta->type = 'remove'; $existingSyncMeta->timestamp = date('Y-m-d H:i:s'); R::store($existingSyncMeta); } if ($r->fireHookIfExists($package, $name, 'beforeRemove', $r->unserialize(array($data->export()))[0])) { R::trash($data); $r->fireHookIfExists($package, $name, 'afterRemove', $r->unserialize(array($data->export()))[0]); return $r->respond(200, 'DELETED'); } return $r->respond(403, 'FORBIDDEN:HOOK', true); } return $r->respond(404, 'NOT FOUND', true); }); /* Handle Options Route */ $app->options('/:any+', 'API', function () use($app, $r) { return $r->respond(200); }); /* default 404 and Error Handler */ $app->error('API', function (\Exception $e) use($app) { return $r->respond(500, $e, true); }); $app->notFound('API', function () use($r) { return $r->respond(404, 'NOT FOUND', true); }); $app->run();
<?php /** * Inicia e configura o Slim para lidar com json e reportar erros */ $app = new \Slim\Slim(); $app->config(['debug' => true, 'view' => new WebDevBr\Mvc\View\Json()]); $app->response->headers->set('Access-Control-Allow-Origin', '*'); $app->response->headers->set('Content-Type', 'application/json'); $app->error(function () use($app) { require __DIR__ . '/slim_error.php'; }); $app->notFound(function () use($app) { $app->render(null, [['message' => 'Page Not Found']]); }); /** * Inicia o objeto que carrega os controllers */ $loader = new WebDevBr\Mvc\Loader(); /** * Configura as rotas padrão para os controllers */ $routes_controller = ['controller' => '[a-zA-Z]+', 'id' => '[0-9]+']; $app->get('/:controller', function ($controller) use($app, $loader) { $app->render(null, [$loader->getController($app, $controller, 'viewAll')]); })->conditions($routes_controller); $app->get('/:controller/:id', function ($controller, $id) use($app, $loader) { $app->render(null, [$loader->getController($app, $controller, 'viewOne', $id)]); })->conditions($routes_controller); $app->post('/:controller', function ($controller) use($app, $loader) { $app->render(null, [$loader->getController($app, $controller, 'create')]);
$app->redirect($app->config('static_path')); } else { throw new RuntimeException('メールアドレスまたはパスワードに誤りがあります'); } } catch (RuntimeException $e) { $app->flash('error', $e->getMessage()); $app->redirect($app->config('static_path') . 'login'); } }); $app->map('/logout', function () use($app) { if (isset($_SESSION['user'])) { $app->getLog()->info('ユーザー名「' . $_SESSION['user']['username'] . '」(メールアドレス"' . $_SESSION['user']['email'] . '")がログアウトしました。'); } session_destroy(); session_regenerate_id(true); session_start(); $app->flash('info', 'ログアウトしました。'); $app->redirect($app->config('static_path')); })->via('GET', 'POST'); require_once __DIR__ . '/../app/routes/project.php'; require_once __DIR__ . '/../app/routes/api.php'; }); $app->notFound(function () use($app) { $app->log->debug('Result(404):REQUEST_URI=' . $_SERVER['REQUEST_URI']); $app->render('404.php'); }); $app->error(function () use($app) { $app->log->debug('Error(500):REQUEST_URI=' . $_SERVER['REQUEST_URI']); $app->render('error.php'); }); $app->run();
<?php require_once 'loading.inc'; require_once '../vendor/autoload.php'; $app = new \Slim\Slim(); //OAuth stuff if (session_status() == PHP_SESSION_NONE) { session_start(); } #custom 4xx and 5xx $app->notFound(function () { header("HTTP/1.0 404 Not Found"); include "pages/notfound.inc"; }); $app->error(function () { header("HTTP/1.0 500 Internal Server Error"); include "pages/error.inc"; }); #routing $app->get('/', function () { include 'pages/landing.inc'; }); #api #gameinfo $app->get('/api/gameinfo/name/:name', function ($name) { $return = new Game('name', $name); header('Content-Type: application/json'); echo $return->toJSON(); }); $app->get('/api/gameinfo/id/:name', function ($name) { $return = new Game('id', $name); header('Content-Type: application/json');
if ($file) { $dir = dirname($file->path); $files = scandir($dir); foreach ($files as $file) { if ($file == "." || $file == "..") { continue; } $filePath = $dir . "/" . $file; unlink($filePath); } rmdir($dir); } $app->FileGateway->deleteFile($id); $app->response->redirect("/successRemoval", 303); } else { $app->response->redirect('/', 303); } }); $app->get('/successRemoval', function () use($app) { $app->render('successRemoval.phtml', array('title' => 'Файл удалён')); }); $app->get('/rules', function () use($app) { $app->render('rules.phtml', array('title' => 'Правила', 'maxFileSize' => $app->config('maxFileSize'))); }); $app->notFound(function () use($app) { $app->render('fileNotFound.phtml', array('title' => '404 - Страница не найдена')); }); $app->error(function () use($app) { $app->render('error.phtml', array('title' => "Сервис временно недоступен")); }); $app->run();
<?php require 'vendor/autoload.php'; $app = new \Slim\Slim(['debug' => false]); $apiKeys = fetchAPIKeys(); $twitterAPI = new \twitterFeedApi\library\TwitterAPIExchange($apiKeys); $app->get('/twitter-feed/:screen_name/:count', function ($screen_name, $count) use($twitterAPI) { $url = "https://api.twitter.com/1.1/statuses/user_timeline.json"; $requestMethod = "GET"; $getField = "?screen_name={$screen_name}&count={$count}"; $resultData = $twitterAPI->setGetfields($getField)->buildOauth($url, $requestMethod)->performRequest(); echo $resultData; }); $app->error(function (\Exception $e) use($app) { echo $e->getCode(); echo $e->getMessage(); }); $app->run();
<?php session_cache_limiter(false); session_start(); use Illuminate\Database\Capsule\Manager as Capsule; require '../vendor/autoload.php'; require 'database.php'; $app = new \Slim\Slim(['view' => new \Slim\Views\Twig()]); // Database //$app->container->singleton('db', function() { // return new PDO('mysql:host=localhost:3307;dbname=sqltrainer', 'admini', 'admini'); //}); $app->db = function () { return new Capsule(); }; // Views $view = $app->view(); $view->setTemplatesDirectory('../app/views'); $view->parserExtensions = [new \Slim\Views\TwigExtension()]; require 'routes.php'; $app->error(function (\Exception $e) use($app) { //$app->notFound(function () use ($app) { //$app->redirect('/SqlTrainer/public'); //}); }); $app->run();
<?php require 'Slim/Slim.php'; \Slim\Slim::registerAutoloader(); require 'JsonView.php'; $app = new \Slim\Slim(array('view' => new JsonView(), 'debug' => FALSE)); // All Methods require 'router.php'; // Generic error handler $app->error(function (Exception $e) use($app) { $app->render(array('error' => TRUE, 'alert' => $e->getMessage()), 500); }); // Not found handler (invalid routes, invalid method types) $app->notFound(function () use($app) { $app->render(array('error' => TRUE, 'alert' => 'Invalid route'), 404); }); // Handle Empty response body $app->hook('slim.after.router', function () use($app) { if (strlen($app->response()->body()) == 0) { $app->render(array('error' => TRUE, 'alert' => 'Empty response'), 500); } }); $app->run();
<?php use NwApi\Di; use NwApi\Middlewares\JsonApiMiddleware; $di = Di::getInstance(); if ($di->env === ENV_DEVELOPMENT) { $slimMode = 'development'; $debug = true; } else { $slimMode = 'production'; $debug = false; } $app = new Slim\Slim(['mode' => $slimMode, 'debug' => false, 'templates.path' => $di->templatesPath]); $app->add(new JsonApiMiddleware()); if ($debug === true) { $app->add(new \Slim\Middleware\PrettyExceptions()); $app->error(function (\Exception $e) { throw $e; }); } $app->get('/hello/:name', function ($name) { echo "Hello, {$name}"; }); return $app;
<?php /* * Novo SGA API */ require_once '../../bootstrap.php'; $app = new Slim\Slim(['debug' => false]); $db = \Novosga\Config\DatabaseConfig::getInstance(); $em = $db->createEntityManager(); $server = new \Novosga\Api\OAuth2Server($em); $api = new \Novosga\Api\ApiV1($em); $app->error(function (Exception $e) use($app) { echo json_encode(['error' => $e->getMessage(), 'code' => $e->getCode()]); }); $app->notFound(function () use($app) { echo json_encode(['error' => 'Not found', 'code' => '404']); }); /* * Autentica o usuário retornando o token de acesso. * * POST /token * { * "grant_type": "password", * "username": "******", * "password": "******", * "client_id": "..." * } * < 200 * { * "access_token": "6cdcf2e7a7bbeac1bd76dcbf33cb59b9b7341613", * "expires_in": 3600,
session_start(); require 'vendor/autoload.php'; // ========================================== // INSTANTIATION // ========================================== $app = new \Slim\Slim(array('mode' => 'development', 'templates.path' => 'app/views', 'view' => new \Slim\Views\Twig())); // ========================================== // APP SETTINGS // ========================================== require_once 'app/config/core.php'; require_once 'app/config/db.php'; require_once 'app/config/app.php'; // ========================================== // ROUTES // ========================================== require_once 'app/routes.php'; // ========================================== // ERROR HANDLER // ========================================== $app->error(function (Exception $e) use($app) { $error = new stdClass(); $error->message = $e->getMessage(); $error->file = $e->getFile(); $error->line = $e->getLine(); echo "{'error':" . json_encode($error) . "}"; }); // ========================================== // RUN APP // ========================================== $app->run();
<?php require '../vendor/autoload.php'; use Pkj\Raspberry\PiFace\PiFaceDigital; if (!class_exists('\\Spi')) { die("Spi extension must be installed (https://github.com/frak/php_spi)"); } $app = new \Slim\Slim(array('debug' => false)); // Exception handler (make sure debug is false above) $app->error(function (\Exception $e) use($app) { print json_encode(array('status' => '500', 'exception' => array('code' => $e->getCode(), 'message' => $e->getMessage()))); }); $app->notFound(function () use($app) { print json_encode(array('status' => '404', 'message' => 'Route not found')); }); $pi = PiFaceDigital::create(); // Defining min/max values \Slim\Route::setDefaultConditions(array('input' => '[0-' . (count($pi->getInputPins()) - 1) . ']', 'led' => '[0-' . (count($pi->getLeds()) - 1) . ']', 'output' => '[0-' . (count($pi->getOutputPins()) - 1) . ']', 'relay' => '[0-' . (count($pi->getRelays()) - 1) . ']', 'switch' => '[0-' . (count($pi->getSwitches()) - 1) . ']', 'value' => '[0-1]')); // Begin read only devices // Input $app->get('/input/', function () use($app, $pi) { responseSuccess(outputAll($pi->getInputPins())); }); $app->get('/input/:input', function ($input) use($app, $pi) { responseSuccess($pi->getInputPins()[$input]->getValue()); }); // Switch $app->get('/switch/', function () use($app, $pi) { responseSuccess(outputAll($pi->getSwitches())); }); $app->get('/switch/:switch', function ($switch) use($app, $pi) {
require 'Slim/Slim.php'; // Initialize http://j4mie.github.io/idiormandparis/ if (defined("AMTC_PDOSTRING")) { ORM::configure(AMTC_PDOSTRING); ORM::configure('username', AMTC_DBUSER); ORM::configure('password', AMTC_DBPASS); } // Initialize http://www.slimframework.com/ \Slim\Slim::registerAutoloader(); $app = new \Slim\Slim(); $app->config('debug', false); // false enables custom error handler below $app->response()->header('Content-Type', 'application/json;charset=utf-8'); $app->notFound(function () { echo json_encode(array('error' => 'Not found')); }); $app->error(function (\Exception $e) { echo strlen($e->getMessage()) > 128 ? substr($e->getMessage(), 0, 128) . '...' : $e->getMessage(); }); class SlimUtil { function getSubmit(Slim\Slim $_app, $key) { $ret = null; $data = get_object_vars(json_decode($_app->request()->getBody())); if (isset($data[$key])) { $ret = get_object_vars($data[$key]); } return $ret; } }
/** * Test custom error handler uses existing Response object */ public function testErrorHandlerUsesCurrentResponseObject() { $s = new \Slim\Slim(array('debug' => false)); $s->error(function (\Exception $e) use($s) { $r = $s->response(); $r->status(503); $r->write('Foo'); $r['X-Powered-By'] = 'Slim'; echo 'Bar'; }); $s->get('/bar', function () { throw new \Exception('Foo'); }); $s->call(); list($status, $header, $body) = $s->response()->finalize(); $this->assertEquals(503, $status); $this->assertEquals('FooBar', $body); $this->assertEquals('Slim', $header['X-Powered-By']); }
// --- CONFIG $mailbox = new PhpImap\Mailbox('{10.0.5.3/imap/ssl/novalidate-cert}INBOX', 'test', 'test'); // change this, example: $mailbox = new PhpImap\Mailbox('{mail.server.com:993/imap/ssl}INBOX', 'user123', 'myp4ssw0rd'); date_default_timezone_set('Europe/Paris'); # enable in development mode: #error_reporting(E_ALL); # get hostname from request if possible - or define your own $serverName = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'localhost'; define('DOMAIN', str_replace('www.', '', $serverName)); // URI-Redirector Prefix (leave empty for direct links) define('URI_REDIRECT_PREFIX', "http://www.redirect.am/?"); // --- end of CONFIG // setup slim & twig $app = new \Slim\Slim(array('view' => new \Slim\Views\Twig(), 'templates.path' => 'app/templates', 'slim.url_scheme' => 'https')); $app->error(function (\Exception $e) use($app) { error_log($e->getMessage()); $app->callErrorHandler($e); }); $app->view()->parserOptions = array('cache' => __DIR__ . '/cache'); $app->view()->parserExtensions = array(new \Slim\Views\TwigExtension(), new DisposableEmail\AutoLinkTwigExtension()); // add html2Text filter $app->view()->getInstance()->addFilter(new Twig_SimpleFilter('html2Text', function ($string) { $convert = new \Html2Text\Html2Text($string); return $convert->get_text(); })); // redirect to random address $app->get('/', function () use($app) { $wordLength = rand(3, 8); $container = new PronounceableWord_DependencyInjectionContainer(); $generator = $container->getGenerator(); $word = $generator->generateWordOfGivenLength($wordLength); $nr = rand(51, 91);
date_default_timezone_set('Europe/Paris'); mb_internal_encoding('UTF-8'); ORM::configure('mysql:host=' . MYSQL_HOSTNAME . ';dbname=' . MYSQL_DATABASENAME); ORM::configure('username', MYSQL_USERNAME); ORM::configure('password', MYSQL_PASSWORD); ORM::configure('driver_options', array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8')); ORM::configure('return_result_sets', true); $app = new \Slim\Slim(array('mode' => MODE, 'debug' => MODE != MODE_PROD)); $app->hook('slim.after.router', function () use($app) { header_remove("X-Powered-By"); }); $app->notFound(function () use($app) { echo "404 Not found"; }); $app->error(function (\Exception $e) use($app) { echo "500 Server error"; // var_dump($e); }); $app->group('/services', function () use($app) { $app->get('/data/:id/:in/:out', function ($id, $in, $out) use($app) { $json = array(); if (preg_match("/^[0-9]+\$/", $id) && preg_match("/^[0-9\\-\\ \\:]+\$/", $in) && preg_match("/^[0-9\\-\\ \\:]+\$/", $out)) { $surveys = ORM::ForTable('lime_survey_' . $id)->where_gte('submitdate', $in)->where_lte('submitdate', $out)->order_by_asc('id')->find_many(); foreach ($surveys as $survey) { $date = DateTime::createFromFormat('Y-m-d H:i:s', $survey->submitdate); $survey->submitdts = $date->format('U'); // TODO: should considerate Paris Time array_push($json, $survey->as_array()); } } echo json_encode($json); });
<?php session_start(); require 'config.php'; require 'DB.php'; require 'Slim/Slim.php'; \Slim\Slim::registerAutoloader(); $app = new \Slim\Slim(array('debug' => true)); $app->contentType("application/json"); $app->error(function (Exception $e = null) use($app) { echo '{"error":{"text":"' . $e->getMessage() . '"}}'; }); //GET pode possuir um parametro na URL $app->get('/:controller/:action(/:parameter)', function ($controller, $action, $parameter = null) use($app) { include_once "classes/{$controller}.php"; $classe = new $controller(); $retorno = call_user_func_array(array($classe, "get_" . $action), array($parameter)); echo '{"result":' . json_encode($retorno) . '}'; }); //POST não possui parâmetros na URL, e sim na requisição $app->post('/:controller/:action', function ($controller, $action) use($app) { $request = json_decode(\Slim\Slim::getInstance()->request()->getBody()); include_once "classes/{$controller}.php"; $classe = new $controller(); $retorno = call_user_func_array(array($classe, "post_" . $action), array($request)); echo '{"result":' . json_encode($retorno) . '}'; }); $app->run();
// $view = $app->view(); $app->configureMode('development', function () use($app, $config) { $app->config(array('debug' => true)); $connection_name = 'testing'; include '../app/app.php'; }); $app->configureMode('production', function () use($app, $config) { $app->config(array('debug' => false)); $connection_name = 'default'; include '../app/app.php'; }); $app->get('/', function () use($app, $config) { if ($config['maintenance']) { $app->render('home/maintenance.php', array()); } else { $app->render('home/index.php', array()); } }); $app->get('/setup', function () use($app, $config) { include '../app/functions.setup.php'; setup($config); }); $app->notFound(function () use($app) { $app->render('404.html'); }); $app->error(function (\Exception $e) use($app) { $app->log->error($e->getFile() . ' on ' . $e->getLine() . ' ' . ' because : ' . $e->getMessage()); $app->response->headers->set('Content-Type', 'text/html'); $app->render('500.html'); }); $app->run();
require 'require.php'; // load db settings $settings = decodeJsonOrFail(file_get_contents('../app/db.json')); // set up eloquent use Illuminate\Database\Capsule\Manager as Capsule; $capsule = new Capsule(); $capsule->addConnection($settings); $capsule->setAsGlobal(); $capsule->bootEloquent(); // set up slim $app = new Slim\Slim(array('debug' => true)); $app->response->headers->set('Content-Type', 'application/json'); $app->get('/users', 'listUsers'); $app->get('/users/:id', 'getUser'); $app->put('/users/:id/:password', 'updateUser'); $app->put('/users/:id/status/:password', 'updateStatus'); //$app->post('/users', 'createUser'); $app->post('/login', 'login'); $app->get('/groups', 'listGroups'); $app->get('/groups/:id', 'getGroup'); $app->put('/groups/:id', 'updateGroup'); $app->get('/users/:id/messages', 'listMessagesForUser'); $app->get('/users/:id/messages/:password', 'listMessagesForUser'); $app->post('/users/:id/messages', 'sendMessageToUser'); //$app->get('/groups/:id/messages', 'listMessagesForGroup'); //$app->post('/groups/:id/messages', 'sendMessageToGroup'); $app->get('/statuses', 'listStatuses'); $app->get('/urgencies', 'listUrgencies'); $app->notFound('showNotFound'); $app->error('showError'); $app->run();
// ========== COMPOSER ========== require ROOT_PATH . '/vendor/autoload.php'; // ========== CONFIGURATION ========== $config = (require APP_PATH . '/src/config.php'); // ========== PHP (from configuration) ========== // time zone date_default_timezone_set($config['PHP']['default_timezone']); // errors ini_set('display_errors', $config['PHP']['display_errors']); ini_set('display_startup_errors', $config['PHP']['display_startup_errors']); ini_set('log_errors', $config['PHP']['log_errors']); // session if (true === $config['PHP']['need_session']) { session_cache_limiter(false); session_set_cookie_params(0, '/', '', $config['PHP']['session_cookie_secure'], true); session_start(); } unset($config['PHP']); // ========== SLIM ========== $app = new \Slim\Slim($config['Slim']); $app->config('app', $config['App']); $app->view()->setData('config', $app->config('app')); require APP_PATH . '/src/dependencies.php'; require APP_PATH . '/src/middlewares.php'; require APP_PATH . '/src/routes.php'; // Error handler $app->error(function (\Exception $e) use($app) { $app->getLog()->error($e); $app->render('errors/error.twig'); }); $app->run();
require 'Slim/Slim.php'; \Slim\Slim::registerAutoloader(); /** * Step 2: Instantiate a Slim application * * This example instantiates a Slim application using * its default settings. However, you will usually configure * your Slim application now by passing an associative array * of setting names and values into the application constructor. */ $app = new \Slim\Slim(array('debug' => false)); $app->contentType("application/json"); $app->error(function (Exception $e = null) use($app) { $errObj = new stdClass(); $errObj->message = $e->getMessage(); $errObj->file = $e->getFile(); $errObj->line = $e->getLine(); echo '{"error":{"text":' . json_encode($errObj) . '"}}'; }); /** * Step 3: Define the Slim application routes * * Here we define several Slim application routes that respond * to appropriate HTTP request methods. In this example, the second * argument for `Slim::get`, `Slim::post`, `Slim::put`, `Slim::patch`, and `Slim::delete` * is an anonymous function. */ // GET route $app->get('/:controller/:action(/:parameter)', function ($controller, $action, $parameter = null) use($app) { include_once "rest_service/{$controller}.php"; $classe = new $controller();
} umask($old); $log = new \Monolog\Logger(strtoupper($app->request->getHost())); $log->pushHandler(new \Monolog\Handler\StreamHandler($logfile, \Monolog\Logger::DEBUG, true, 0777)); return $log; }); /** * Register handlers */ \Monolog\ErrorHandler::register($app->log); /** * Error handle */ $app->error(function (\Exception $e) use($app) { $app->applyHook('log.request.info', $e->getMessage()); $app->log->error($e); $app->render('error.php'); }); $app->notFound(function () use($app) { $app->applyHook('log.request.info', 'Page not found'); $app->render('404.php'); }); // throw new \Exception('test error'); /** * Define hooks */ if (file_exists(APPPATH . 'hooks.php')) { require APPPATH . 'hooks.php'; } /** * Define routes
$app->config('debug', false); # config/init template [twig] $app->container->singleton('twig', function () { $twig = new \Slim\Views\Twig(); $twig->parserExtensions = array(new \Slim\Views\TwigExtension()); $templatePath = __DIR__ . '/api/templates'; $twig->setTemplatesDirectory($templatePath); return $twig; }); # 404 handler inside app() $app->notFound(function () use($app) { $app->twig->display('error.php'); }); # Exception handler inside app() $app->error(function (\Exception $e) use($app) { $app->twig->display('error.php'); }); # auth if (!isset($_GET['client-id'])) { # Basic Authentication /vassarapi # use an authenticator() ? github/tuupola/slim-basic-auth $user_array = array("user-acct2" => "user-acct2", "user-acct1" => "user-acct1"); $users = array("users" => $user_array); $app->add(new \Slim\Middleware\HttpBasicAuthentication(["path" => "/vassarapi", "realm" => "Protected", "authenticator" => new ArrayAuthenticator($users)])); } else { if (!sigValidate::validSignature(consumer::$clientId, $_GET['client-signature'], $_GET['timestamp'])) { throw new Exception('invalid login attempt'); } } # # for each valid endpoint
/** * Slim should throw a Slim_Exception_Stop if error callback is not callable */ public function testErrorHandlerIfNotCallable() { $this->setExpectedException('\\Slim\\Exception\\Stop'); $s = new \Slim\Slim(array("log.enabled" => false)); $errCallback = 'foo'; $s->error($errCallback); }
$app->redirect("/".$app->request->getRootUri()); }else{ $app->render("front/error/500.twig"); } */ }); $app->get("/user/social/login/twitter/callback", function () use($app, $util) { $app->render("front/error/500.twig"); }); $app->get("/user/captcha", function () use($app, $util) { $captcha = new SimpleCaptcha(); $captcha->wordsFile = 'words/en.php'; $captcha->session_var = 'secretword'; $captcha->imageFormat = 'png'; $captcha->lineWidth = 3; $captcha->scale = 3; $captcha->blur = true; $captcha->resourcesPath = "../app/util/captcha"; $app->contentType("image/png"); $im = $captcha->CreateImage(); echo $im; }); //#################################################### ERROR #################################################### $app->notFound(function () use($app) { $app->render("front/error/404.twig"); }); $app->error(function (\Exception $e) use($app) { $app->render("front/error/500.twig"); }); /******************************************* RUN THE APP *******************************************************/ $app->run();