$stmt->bindValue("uuid", $uuid); $stmt->bindValue("platform", 'TWITCH'); $stmt->bindValue("access_token", $accessToken); $stmt->bindValue("refresh_token", $refreshToken); $stmt->bindValue("refreshed_date", new DateTime(), 'datetime'); $stmt->bindValue("access_code", $accessCode); $stmt->execute(); $app['monolog']->addInfo("INSERTED NEW TOKEN: {$accessToken} for UUID: {$uuid}"); } else { $stmt = $app['db']->prepare('UPDATE oauth_requests SET uuid=:uuid, platform=:platform, access_token=:access_token, refresh_token=:refresh_token, refreshed_date=:refreshed_date, access_code=:access_code WHERE uuid=:uuid AND platform=:platform'); $stmt->bindValue("uuid", $uuid); $stmt->bindValue("platform", 'TWITCH'); $stmt->bindValue("access_token", $accessToken); $stmt->bindValue("refresh_token", $refreshToken); $stmt->bindValue("refreshed_date", new DateTime(), 'datetime'); $stmt->bindValue("access_code", $accessCode); $stmt->execute(); $app['monolog']->addInfo("UPDATED NEW TOKEN: {$accessToken} for UUID: {$uuid}"); } return $app['twig']->render('displayCode.twig', array('accessCode' => $accessCode)); }); $app->error(function (\Exception $e, $code) use($app) { switch ($code) { case 404: return $app['twig']->render('display404.twig'); break; default: return $app['twig']->render('displayError.twig', array("message" => "We are sorry, an unknown error happened.", "backUrl" => "/")); } }); $app->run();
$whiteLists = (include __DIR__ . '/whiteList.php'); $whiteLists = $request->getMethod() == 'GET' ? $whiteLists['get'] : $whiteLists['post']; $inWhiteList = 0; foreach ($whiteLists as $whiteList) { $path = $request->getPathInfo(); if (preg_match($whiteList, $request->getPathInfo())) { $inWhiteList = 1; break; } } $token = $request->headers->get('Auth-Token', ''); if (!$inWhiteList && empty($token)) { throw createNotFoundException("AuthToken is not exist."); } $userService = ServiceKernel::instance()->createService('User.UserService'); $token = $userService->getToken('mobile_login', $token); if (!$inWhiteList && empty($token['userId'])) { throw createAccessDeniedException("AuthToken is invalid."); } $user = $userService->getUser($token['userId']); // $user = $userService->getUser(1); if (!$inWhiteList && empty($user)) { throw createNotFoundException("Auth user is not found."); } setCurrentUser($user); }); $app->error(function (\Exception $e, $code) { return array('code' => $code, 'message' => $e->getMessage()); }); include __DIR__ . '/config/routing.php'; $app->run();
$app->register(new Silex\Provider\HttpCacheServiceProvider(), array('http_cache.cache_dir' => __DIR__ . '/../app/cache/', 'http_cache.options' => ['default_ttl' => $app['cache_ttl']])); $app->get('/', function () use($app) { return $app['twig']->render('index.html.twig'); })->bind('home'); $app->get('/swagger.json', function () use($app) { return new Symfony\Component\HttpFoundation\Response($app['twig']->render('swagger.json.twig'), 200, ['Content-Type' => 'application/json']); })->bind('swagger'); $app->get('/apis.json', function () use($app) { return new Symfony\Component\HttpFoundation\Response($app['twig']->render('apis.json.twig'), 200, ['Content-Type' => 'application/json']); })->bind('apisjson'); $app->get('/subnet/{ip}/{mask}', function ($ip, $mask) use($app) { $subnet = $ip . '/' . $mask; try { $subnet_info = IPTools\Network::parse($subnet)->info; unset($subnet_info['class']); } catch (Exception $e) { $app->abort(400, $e->getMessage()); } return $app->json($subnet_info, 200, ['Cache-Control' => 's-maxage=' . $app['cache_ttl'] . ', public', 'ETag' => md5($subnet), 'Access-Control-Allow-Origin', '*']); })->assert('ip', '[\\w\\.\\:]+')->assert('mask', '[0-9]+')->bind('api'); $app->after(function (Symfony\Component\HttpFoundation\Request $request, Symfony\Component\HttpFoundation\Response $response) { $response->headers->set('Access-Control-Allow-Origin', '*'); }); $app->error(function (\Exception $e, $code) use($app) { return $app->json(['error' => $e->getMessage()]); }); if ($app['debug']) { $app->run(); } else { $app['http_cache']->run(); }
$app['debug'] = false; break; default: exit('Error: The application environment is not set correctly. Please open the following file and correct this: ' . SELF); } } else { exit('Error: The application environment is not set correctly. Please open the following file and correct this: ' . SELF); } /*-------------------------------------------------------------------- * Error Handling *-------------------------------------------------------------------- */ $app->error(function (\Exception $e, $code) use($app) { if ($app['debug']) { /** @noinspection PhpInconsistentReturnPointsInspection */ return; } return Site\Handler\ErrorHandler::response($e, $code, $app); }); ExceptionHandler::register($app['debug']); /*--------------------------------------------------------------- * APPLICATION FOLDER NAME *--------------------------------------------------------------- * * If you want this front controller to use a different "application" * folder then the default one you can set its name here. The folder * can also be renamed or relocated anywhere on your server. If * you do, use a full server path. * * NO TRAILING SLASH! *
// $app['monolog']->addDebug('logging output.'); // // return $app['twig']->render('warlog.twig'); // }); $app->get('/clanregeln', function () use($app) { $app['monolog']->addDebug('logging output.'); return $app['twig']->render('clanregeln.twig'); }); $app->get('/clanwar', function () use($app) { $app['monolog']->addDebug('logging output.'); return $app['twig']->render('clanwar.twig'); }); $app->get('/impressum', function () use($app) { $app['monolog']->addDebug('logging output.'); return $app['twig']->render('impressum.twig'); }); $app->get('/datenschutz', function () use($app) { $app['monolog']->addDebug('logging output.'); return $app['twig']->render('datenschutz.twig'); }); $app->error(function (\Exception $e, $code) use($app) { switch ($code) { case 404: $message = $app['twig']->render('404.twig'); break; default: $message = 'We are sorry, but something went terribly wrong.'; } return new Response($message); }); $app->run();
// production environment - false; test environment - true $app['debug'] = true; //handling CORS preflight request $app->before(function (Symfony\Component\HttpFoundation\Request $request) { if ($request->getMethod() === "OPTIONS") { $response = new \Symfony\Component\HttpFoundation\ResponseHeaderBag(); $response->headers->set("Access-Control-Allow-Origin", "*"); $response->headers->set("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS"); $response->headers->set("Access-Control-Allow-Headers", "Content-Type"); $response->setStatusCode(200); return $response->send(); } }, \Silex\Application::EARLY_EVENT); //handling CORS respons with right headers $app->after(function (Symfony\Component\HttpFoundation\Request $request, Symfony\Component\HttpFoundation\Response $response) { $response->headers->set("Access-Control-Allow-Origin", "*"); $response->headers->set("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS"); }); // setting up json request data $app->before(function (Symfony\Component\HttpFoundation\Request $request) { if (0 === strpos($request->headers->get('Content-Type'), 'application/json')) { $data = json_decode($request->getContent(), true); $request->request->replace(is_array($data) ? $data : array()); } }); $app->register(new Silex\Provider\ServiceControllerServiceProvider()); $app->register(new Silex\Provider\DoctrineServiceProvider(), $config['db']); $app->error(function (\Exception $e, $code) use($app) { return $app->json(array("error" => $e->getMessage()), $code); }); return $app;
<?php /** * @licence GNU GPL v2+ * @author Jeroen De Dauw < *****@*****.** > */ use Symfony\Component\HttpFoundation\Response; $app = new \Silex\Application(); require __DIR__ . '/config/default-config.php'; if (is_readable(__DIR__ . '/config/config.php')) { require __DIR__ . '/config/config.php'; } $app->register(new Silex\Provider\UrlGeneratorServiceProvider()); $app->register(new Silex\Provider\ValidatorServiceProvider()); $app->register(new Silex\Provider\ServiceControllerServiceProvider()); $app->register(new Silex\Provider\TwigServiceProvider(), ['twig.path' => __DIR__ . '/templates']); $app['twig']->addExtension(new Aptoma\Twig\Extension\MarkdownExtension(new \Aptoma\Twig\Extension\MarkdownEngine\MichelfMarkdownEngine())); $app->error(function (\Exception $e, $code) use($app) { if ($app['debug']) { return; } // 404.html, or 40x.html, or 4xx.html, or error.html $templates = ['errors/' . $code . '.html', 'errors/' . substr($code, 0, 2) . 'x.html', 'errors/' . substr($code, 0, 1) . 'xx.html', 'errors/default.html']; return new Response($app['twig']->resolveTemplate($templates)->render(['code' => $code]), $code); }); return require __DIR__ . '/routes.php';
<?php use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; require_once '../vendor/autoload.php'; $app = new Silex\Application(); $app['debug'] = true; $app['database'] = new PDO("mysql:host=localhost;dbname=mysql", 'root', ''); $app->get('/', function () use($app) { return 'Hello Igor! Your Silex application is up and running. Woot!'; }); $app->post('/', function (Request $request) { $message = $request->get('message'); return new Response('You said: "' . $message . '". Thank you!', 201); }); $app->error(function (\Exception $e, $code) { return new Response('We are sorry, but something went terribly wrong.'); }); $app->run();
<?php $loader = (require_once __DIR__ . "/../vendor/autoload.php"); $loader->add('app', __DIR__ . '/../'); $app = new Silex\Application(); //register providers $app->register(new \Mongo\Silex\Provider\MongoServiceProvider(), ['mongo.connections' => ['default' => ['server' => 'mongodb://localhost:27017', 'options' => ['connect' => true]]]]); $app->error(function (\app\exceptions\ApiException $e, $code) { $errors = ['message' => $e->getMessage(), 'code' => $e->getCode()]; return new \Symfony\Component\HttpFoundation\JsonResponse(['errors' => $errors], $e->getCode()); }); $app->mount('/', new \app\controllers\IndexController()); $app->mount('/firms', new app\controllers\FirmController()); $app->mount('/buildings', new app\controllers\BuildingController()); $app->mount('/rubrics', new app\controllers\RubricsController()); $app->run();
$app->before(function (Request $request) { if (0 === strpos($request->headers->get('Content-Type'), 'application/json')) { $data = json_decode($request->getContent(), true); $request->request->replace(is_array($data) ? $data : array()); } }); // Define a custom encoder for Security/Authentication $app['security.encoder.digest'] = $app->share(function ($app) { // uses the password-compat encryption return new BCryptPasswordEncoder(10); }); // Default error handler $app->error(function (\Exception $e, $code) use($app) { $app['monolog']->addError($e->getMessage()); $message = 'The server encountered an error.'; if ($app['debug'] === true) { $message = $e->getMessage(); } return $app->json($message, 403); }); // General Service Provder for Controllers $app->register(new Silex\Provider\ServiceControllerServiceProvider()); $app['controller.user'] = $app->share(function () use($app) { return new Pfmgr\Controller\User(); }); $app->get('/user/{id}', "controller.user:fetchAction"); $app->post('/user/create', "controller.user:createAction"); $app['controller.account'] = $app->share(function () use($app) { return new Pfmgr\Controller\Account(); }); $app->post('/account/create', "controller.account:createAction"); $app['controller.currency'] = $app->share(function () use($app) {
function getApp() { if (isset($this->_app)) { return $this->_app; } // Initialize out Silex app and let's do it $app = new \Silex\Application(); if ($this->getConfig('twig.debug')) { $app['debug'] = $this->getConfig('twig.debug'); } // Register our session provider $app->register(new \Silex\Provider\SessionServiceProvider()); $app->before(function ($request) use($app) { $app['session']->start(); }); $app['url'] = $this->getConfig('application.url'); $app['uploadPath'] = $this->getConfig('upload.path'); $app['confAirport'] = $this->getConfig('application.airport'); $app['arrival'] = $this->getConfig('application.arrival'); $app['departure'] = $this->getConfig('application.departure'); // Register the Twig provider and lazy-load the global values $app->register(new \Silex\Provider\TwigServiceProvider(), array('twig.path' => APP_DIR . $this->getConfig('twig.template_dir'))); $that = $this; $app['twig'] = $app->share($app->extend('twig', function ($twig, $app) use($that) { $twig->addGlobal('site', array('url' => $that->getConfig('application.url'), 'title' => $that->getConfig('application.title'), 'email' => $that->getConfig('application.email'), 'eventurl' => $that->getConfig('application.eventurl'), 'enddate' => $that->getConfig('application.enddate'))); return $twig; })); // Register our use of the Form Service Provider $app->register(new \Silex\Provider\FormServiceProvider()); $app->register(new \Silex\Provider\ValidatorServiceProvider()); $app->register(new \Silex\Provider\TranslationServiceProvider(), array('translator.messages' => array())); $app['db'] = $this->getDb(); $app['spot'] = $this->getSpot(); $app['purifier'] = $this->getPurifier(); // We're using Sentry, so make it available to app $app['sentry'] = $app->share(function () use($app) { $hasher = new \Cartalyst\Sentry\Hashing\NativeHasher(); $userProvider = new \Cartalyst\Sentry\Users\Eloquent\Provider($hasher); $groupProvider = new \Cartalyst\Sentry\Groups\Eloquent\Provider(); $throttleProvider = new \Cartalyst\Sentry\Throttling\Eloquent\Provider($userProvider); $session = new \OpenCFP\SymfonySentrySession($app['session']); $cookie = new \Cartalyst\Sentry\Cookies\NativeCookie(array()); $sentry = new \Cartalyst\Sentry\Sentry($userProvider, $groupProvider, $throttleProvider, $session, $cookie); \Cartalyst\Sentry\Facades\Native\Sentry::setupDatabaseResolver($app['db']); $throttleProvider->disable(); return $sentry; }); $app['twig'] = $app->share($app->extend('twig', function ($twig, $app) { $twig->addGlobal('user', $app['sentry']->getUser()); return $twig; })); // Configure our flash messages functionality $app->before(function () use($app) { $flash = $app['session']->get('flash'); $app['session']->set('flash', null); if (!empty($flash)) { $app['twig']->addGlobal('flash', $flash); } }); // Add current page global $app->before(function (Request $request) use($app) { $app['twig']->addGlobal('current_page', $request->getRequestUri()); }); // Define error template paths if (!$app['debug']) { $app->error(function (\Exception $e, $code) use($app) { switch ($code) { case 401: $message = $app['twig']->render('error/401.twig'); break; case 403: $message = $app['twig']->render('error/403.twig'); break; case 404: $message = $app['twig']->render('error/404.twig'); break; default: $message = $app['twig']->render('error/500.twig'); } return new Response($message, $code); }); } $app = $this->defineRoutes($app); // Add the starting date for submissions $app['cfpdate'] = $this->getConfig('application.cfpdate'); return $app; }
<?php use Silex\Provider\DoctrineServiceProvider; use Symfony\Component\HttpFoundation\Response; $app = new \Silex\Application(); $app['config'] = (require_once __DIR__ . '/resources/config.php'); $app->register(new Silex\Provider\ServiceControllerServiceProvider()); $app->register(new DoctrineServiceProvider(), array('db.options' => $app['config']['db'])); $app->register(new Silex\Provider\TwigServiceProvider(), array('twig.options' => array('cache' => __DIR__ . '/../var/cache/twig'))); $app->register(new Marmelab\Microrest\MicrorestServiceProvider(), array('microrest.config_file' => __DIR__ . '/resources/api.raml')); $app->get('/', function () use($app) { return new Response("Index page"); }); $app->error(function (\Exception $e) { var_dump($e->getMessage()); var_dump($e->getTraceAsString()); }); return $app;
$app->get("/about", function () { global $me, $tmpl, $view; $me->view = __DIR__ . '/views/v.a.php'; $me->tmpl = __DIR__ . '/templates/t.a.php'; return ""; }); $app->error(function (\Exception $e, $code) { global $me, $tmpl, $view; switch ($code) { case 403: $me->params["err"] = "e403"; $me->view = __DIR__ . '/views/v.err.php'; $me->tmpl = __DIR__ . '/templates/t.err.php'; break; case 404: $me->params["err"] = "e404"; $me->view = __DIR__ . '/views/v.err.php'; $me->tmpl = __DIR__ . '/templates/t.err.php'; break; default: $me->params["err"] = "hz"; $me->view = __DIR__ . '/views/v.err.php'; $me->tmpl = __DIR__ . '/templates/t.err.php'; } return ""; }); $app->before(function () { global $me, $tmpl, $view; }); $app->finish(function () { global $me, $tmpl, $view; });
// 'type' => 'annotation', // 'path' => array( // 'src/Todos/Entities' // ), // 'namespace' => 'Todos\Entities', // 'alias' => 'docs', // ), // ), // // ... // )); // Validator $app->register(new Silex\Provider\ValidatorServiceProvider()); // Exception management. $app->error(function (\Exception $e) use($app) { // 404 - Page not found if ($e instanceof NotFoundHttpException) { return $app->sendFile(dirname(__DIR__) . '/public/404.html', 404); // Other Error - 500 } // elseif ($e instanceof HttpException) { // return new Response($app['twig']->render('500.html.twig', array( // 'meta' => array('title' => 'Internal error - Error 500'), // 'page' => array( // 'title' => 'Internal error - Error 500', // 'content' => 'An internal error occur during page generation.', // ), // )), 500); // } }); return $app; //$app->run();
$arrayOfUsers = array(); foreach ($users as $name => $myarray) { $app['monolog']->addDebug($name); $arrayOfUsers[] = $myarray; } $app['monolog']->addInfo(sizeof($arrayOfUsers)); $output = array_values($arrayOfUsers); return json_encode($output); }); //Find one user from the user array $app->get('/users/{name}', function (Silex\Application $app, $name) use($app, $users) { if ($name) { if (!isset($users[$name])) { $app->abort(404, "Post {$id} does not exist."); } else { $output = json_encode($users[$name]); } } return $output; }); //Hello world. $app->get('/hellojson', function () use($app) { $output = '{"message": "Hello World From Silex"}'; return $output; }); //Exception handelling use Symfony\Component\HttpFoundation\Response; $app->error(function (\Exception $e, $code) { return new Response($e); }); $app->run();
$app['twig']->addGlobal('config', $app['config']); $app['twig']->addGlobal('utils', $app['utils']); $authRequired = !empty($app['config']['authenticate']) && !empty($app['config']['authenticate']['username']) && !empty($app['config']['authenticate']['password']) ? true : false; if (!in_array($app['request']->getRequestUri(), $authPage)) { if ($authRequired) { $currentUser = $app['session']->get($app['config']['prefix'] . 'authed-user'); $userHash = sha1($app['config']['authenticate']['username'] . $app['config']['authenticate']['password']); if (empty($currentUser) || $currentUser !== $userHash) { return $app->redirect($app['uri']->generate('authenticate')); // not logged in, redirect to auth page } } } elseif (!$authRequired) { // redirect visits to the auth pages to the homepage if no auth is required. return $app->redirect('/'); } }); $app->error(function (\Exception $e, $code) use($app) { switch ($code) { case '404': $template = 'PT/pages/404.html'; break; default: $template = 'PT/pages/error.html'; break; } return new Response($app['twig']->render($template, array('message' => $e->getMessage())), $code); }); $app->mount('/_system/', new Prontotype\Controller\SystemController()); $app->mount('/', new Prontotype\Controller\MainController()); return $app;
$user = $app['session']->get('user'); $summary = $app['session']->get($user . '-summary'); return $app['twig']->render('close.twig', array('summary' => Util\Summary::html(count($questions), $summary), 'has_blank' => Util\Summary::hasBlank($summary), 'has_review' => Util\Summary::hasReview($summary))); })->bind('exam.close'); // Shows your result $app->get('/exam/result', function () use($app, $questions) { $user = $app['session']->get('user'); $name = $user->name; if (!$user) { $app->redirect('/'); } $summary = $app['session']->get($user . '-summary'); $result = Util\Summary::result($summary, $questions); Util\Summary::save($user, $result, $summary, $questions); $app['session']->clear(); return $app['twig']->render('result.twig', array('name' => $name, 'result' => $result, 'total' => count($questions))); })->bind('exam.result'); //===================================================== // CONTROLADORES //===================================================== // Basta incluir um arquivo que está na pasta "controllers" //require_once 'usuario.php'; //===================================================== // Possíveis erros HTTP //===================================================== $app->error(function (\Exception $e, $code) use($app) { if (!$app['debug']) { return $app['twig']->render("errors/{$code}.twig", array('error' => $e->getMessage())); } }); return $app;
$twig->addExtension(new \Portfolio\Classes\Twig\Extension\ImgDirExtension($app)); return $twig; })); $app['twig'] = $app->share($app->extend('twig', function ($twig, $app) { $twig->addExtension(new \Portfolio\Classes\Twig\Extension\UserExtension($app)); return $twig; })); $app['twig'] = $app->share($app->extend('twig', function ($twig, $app) { $twig->addExtension(new \Portfolio\Classes\Twig\Extension\DeleteFormExtension($app)); return $twig; })); $app['twig'] = $app->share($app->extend('twig', function ($twig, $app) { $twig->addExtension(new Twig_Extensions_Extension_Text()); return $twig; })); /* Gestion des erreurs */ if (isset($app['debug']) and !$app['debug']) { $app->error(function (\Exception $e, $code) use($app) { switch ($code) { case 403: $message = 'Access denied.'; break; case 404: $message = 'The requested resource could not be found.'; break; default: $message = "Something went wrong."; } return $app['twig']->render('Pages/Error/Error.html.twig', array('message' => $message)); }); }
<?php require_once __DIR__ . '/../vendor/autoload.php'; use Symfony\Component\HttpFoundation\Response; $app = new Silex\Application(); $app->register(new Silex\Provider\DoctrineServiceProvider()); $app->register(new Silex\Provider\FormServiceProvider()); $app->register(new Silex\Provider\TwigServiceProvider()); $app->register(new Silex\Provider\ValidatorServiceProvider()); $app->register(new Silex\Provider\TranslationServiceProvider()); $app->register(new Silex\Provider\MonologServiceProvider()); $app->register(new Silex\Provider\SessionServiceProvider()); $app['storage'] = $app->share(function () use($app) { return new Paste\Storage\Storage($app['db'], $app['monolog']); }); $configReplacements = array('pwd' => __DIR__ . '/../'); $env = getenv('APP_ENV') ?: 'prod'; $app->register(new Igorw\Silex\ConfigServiceProvider(__DIR__ . "/../config/{$env}.json.dist", $configReplacements)); $app->register(new Igorw\Silex\ConfigServiceProvider(__DIR__ . "/../config/{$env}.json", $configReplacements)); $app['twig']->addGlobal('title', $app['pastebin.title']); $app['twig']->addGlobal('theme', $app['pastebin.theme']); $app->error(function (\Exception $ex, $code) use($app) { if ($code !== 404) { return; } $view = $app['twig']->render('error.html', array('error' => $ex->getMessage())); return new Response($view, $code); }); return $app;
<?php require_once __DIR__ . '/../vendor/autoload.php'; use Symfony\Component\HttpFoundation\Response; $app = new Silex\Application(); try { $pdo = new PDO("mysql:host=localhost;dbname=benchmark", "root"); } catch (Exception $e) { echo $e->getMessage(); exit; } $app->get('/', function () use($app, $pdo) { $sth = $pdo->prepare("INSERT INTO product (name) values (:name)"); $sth->bindParam(':name', uniqid("product"), PDO::PARAM_STR); $sth->execute(); return $app->json([id => $pdo->lastInsertId()]); }); $app->error(function ($err) { return new Response($err->getMessage()); }); $app['debug'] = true; $app->run();
// Markdown $app->register(new Nicl\Silex\MarkdownServiceProvider()); // Negotiation $app->register(new KPhoen\Provider\NegotiationServiceProvider(['json' => ['application/hal+json', 'application/json'], 'xml' => ['application/hal+xml', 'application/xml']])); // Document validator $app['document_validator'] = $app->protect(function (Document $document) use($app) { $errors = $app['validator']->validate($document); if (0 < count($errors)) { return new FormErrors($errors); } return true; }); // View $app['view_handler'] = $app->share(function () use($app) { return new ViewHandler($app['serializer'], $app['request'], $app['acceptable_mime_types']); }); // Error handler $app->error(function (\Exception $e, $code) use($app) { if (405 === $code) { return new Response($e->getMessage(), 405, array_merge($e->getHeaders(), ['Content-Type' => 'text/plain'])); } if (406 === $code) { return new Response($e->getMessage(), 406, ['Content-Type' => 'text/plain']); } return $app['view_handler']->handle(new VndErrorRepresentation($e->getMessage()), $code); }); // Model Layer $app['document_repository'] = $app->share(function () { return new PropelDocumentRepository(DocumentQuery::create()); }); return $app;
define('APP_DIR', __DIR__); require_once APP_DIR . '/../vendor/autoload.php'; $app = new Silex\Application(); /** * Register database service */ $app->register(new Silex\Provider\DoctrineServiceProvider(), array('db.options' => array('dbname' => 'mydb', 'user' => 'user', 'password' => 'secret', 'host' => 'localhost', 'driver' => 'pdo_mysql'))); /** * router */ $app->post('/translate', '\\SlackBotService\\Controller\\Translate::translate'); $app->post('/zingmp3', '\\SlackBotService\\Controller\\ZingMp3::post'); $app->post('/meme/generate', '\\SlackBotService\\Controller\\Meme::generate'); $app->post('/meme/list', '\\SlackBotService\\Controller\\Meme::memoList'); $app->post('/quote', '\\SlackBotService\\Controller\\Quote::post'); $app->post('/horoscope', '\\SlackBotService\\Controller\\Horoscope::post'); $app->post('/funnyimage/random', '\\SlackBotService\\Controller\\FunnyImage::post'); $app->get('/public/meme/{filename}', function (Silex\Application $app, $filename) { $filePath = APP_DIR . '/public/meme/' . $filename; if (!file_exists($filePath)) { $app->abort(404, $filePath . ' not found.'); } return $app->sendFile($filePath); }); /** * Error handler */ $app->error(function (\Exception $e, $code) { return new JsonResponse(array('errorCode' => $code, 'message' => $e->getMessage())); }); $app->run();
<?php /** * @licence GNU GPL v2+ * @author Jeroen De Dauw < *****@*****.** > */ use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; /** * These variables need to be in scope when this file is included: * * @var \Queryr\WebApi\ApiFactory $apiFactory */ $app = new \Silex\Application(); $app->after(function (Request $request, Response $response) { $response->headers->set('access-control-allow-origin', '*'); if ($response instanceof JsonResponse) { $response->setEncodingOptions(JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); } return $response; }); $app->error(function (\Exception $e, $code) { return new JsonResponse(['message' => $e->getMessage(), 'code' => $code], $code); }); return require __DIR__ . '/routes.php';
<?php // web/index.php require_once __DIR__ . '/../vendor/autoload.php'; use Symfony\Component\HttpFoundation\Response; $app = new Silex\Application(); $app->register(new Silex\Provider\TwigServiceProvider(), ['twig.path' => __DIR__ . '/../src/views']); $app->error(function (\Exception $e, $code) { return new Response($e->getMessage()); }); $app->get('/', function () use($app) { return $app['twig']->render('index.twig', []); }); $app->run();
// Registers Symfony Validator component extension $app->register(new Silex\Provider\ValidatorServiceProvider()); // Registers Smak Portfolio extension $app->register(new Smak\Portfolio\Silex\Provider\SmakServiceProvider(), array('smak.portfolio.content_path' => __DIR__ . '/../web/content', 'smak.portfolio.public_path' => $app['domain'] . '/content')); // Registers Twig extension $app->register(new Silex\Provider\TwigServiceProvider(), array('twig.path' => array($app['twig.content_path'], $app['smak.portfolio.content_path']), 'twig.options' => array('charset' => 'utf-8', 'strict_variables' => true, 'cache' => $app['cache.path']))); $app['twig.loader.filesystem']->addPath($app['twig.content_path'] . '/frontend', 'frontend'); // Registers Monolog extension $app->register(new Silex\Provider\MonologServiceProvider(), array('monolog.logfile' => __DIR__ . '/../log/portfolio.log', 'monolog.name' => 'portfolio', 'monolog.level' => 300)); // Registers Swiftmailer extension $app->register(new Silex\Provider\SwiftmailerServiceProvider(), array('swiftmailer.class_path' => __DIR__ . '/../vendor/swiftmailer/swiftmailer/lib/classes')); $app['mailer'] = \Swift_Mailer::newInstance(\Swift_MailTransport::newInstance()); // Default cache values $app['cache.defaults'] = array('Cache-Control' => sprintf('public, max-age=%d, s-maxage=%d, must-revalidate, proxy-revalidate', $app['cache.max_age'], $app['cache.max_age']), 'Expires' => date('r', time() + $app['cache.expires'])); // Application error handling $app->error(function (\Exception $e, $code) use($app) { if ($app['debug']) { return; } switch ($code) { case '404': $app['monolog']->addError(sprintf('%s Error on %s', $code, $app['request']->server->get('REQUEST_URI'))); $response = $app['twig']->render('error.html.twig'); break; default: $app['monolog']->addCritical(sprintf('%s Error on %s', $code, $app['request']->server->get('REQUEST_URI'))); $response = $app['twig']->render('error.html.twig'); break; } return new Response($response, $code); });
$app->abort(404, "Post {$id} does not exist."); } $post = $blogPosts[$id]; return "<h1>{$post['title']}</h1>" . "<p>{$post['body']}</p>"; }); use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; $app->post('/feedback', function (Request $request) { $message = $request->get('message'); mail('*****@*****.**', '[YourSite] Feedback', $message); return new Response('Thank you for your feedback!', 201); }); $app->error(function (\Exception $e, $code) { switch ($code) { case 404: $message = 'The requested page could not be found.'; break; default: $message = 'We are sorry, but something went terribly wrong.'; } return new Response($message, $code); }); $app->register(new Silex\Provider\DoctrineServiceProvider(), array('db.options' => array('driver' => 'pdo_sqlite', 'path' => __DIR__ . '/data/app.db'), 'db.dbal.class_path' => __DIR__ . '/vendor/doctrine/doctrine-dbal/lib', 'db.common.class_path' => __DIR__ . '/vendor/doctrine/doctrine-common/lib')); $app->get('/', function () use($app) { }); $app->get('/article/show/{id}', function ($id) use($app) { $sql = "SELECT * FROM article WHERE id = ?"; $post = $app['db']->fetchAssoc($sql, array((int) $id)); return "<h1>{$post['title']}</h1>" . "<p>{$post['content']}</p>"; }); $app->run();
} $log = $client->getLog($logSlug)->load(); $minLogLevel = $request->query->get('m'); $currentLogger = $request->query->get('l'); if ($currentLogger && !$log->getLoggers()->contains($currentLogger)) { return $app->redirect($app['url_generator']->generate('log', array('clientSlug' => $clientSlug, 'logSlug' => $logSlug, 'm' => $minLogLevel, 'l' => $currentLogger))); } } catch (\League\Flysystem\FileNotFoundException $e) { $app->abort(404, "Log file not found"); } return $app['twig']->render('log.html.twig', array('clients' => $clients, 'current_client_slug' => $clientSlug, 'current_log_slug' => $logSlug, 'log' => $log, 'logLevels' => Monolog\Logger::getLevels(), 'min_log_level' => in_array($minLogLevel, Monolog\Logger::getLevels()) ? $minLogLevel : 100, 'loggers' => $log->getLoggers(), 'current_logger' => $currentLogger)); }; $app->get('/logs/{clientSlug}/{logSlug}', $controller_log)->bind("log"); } $app->error(function (\Syonix\LogViewer\Exceptions\ConfigFileMissingException $e, $code) use($app) { return $app['twig']->render('error/config_file_missing.html.twig'); }); $app->error(function (\Syonix\LogViewer\Exceptions\NoLogsConfiguredException $e, $code) use($app) { return $app['twig']->render('error/no_log_files.html.twig'); }); $app->error(function (\Symfony\Component\HttpKernel\Exception\HttpException $e) use($app) { if ($app['debug']) { return; } switch ($e->getStatusCode()) { case 404: $viewer = new Syonix\LogViewer\LogViewer($app['config']['logs']); return $app['twig']->render('error/log_file_not_found.html.twig', array('clients' => $viewer->getClients(), 'current_client_slug' => null, 'current_log_slug' => null, 'error' => $e)); default: try { $viewer = new Syonix\LogViewer\LogViewer($app['config']['logs']);
return $app->redirect($app['url_generator']->generate('about')); } } $data = array('contact_form' => $contact_form->createView()); return $app['twig']->render('pages/about.twig', $data); })->bind('about'); $app->get('/pokemons', function () use($app, $pokemons_model) { $pokemons = $pokemons_model->getAll(); $data = array('pokemons' => $pokemons); return $app['twig']->render('pages/pokemons.twig', $data); })->bind('pokemons'); $app->get('/pokemon/{id}', function ($id) use($app, $pokemons_model, $types_model) { $pokemon = $pokemons_model->getOneById($id); $pokemon->types = $types_model->getAllForPokemonId($pokemon->id); $data = array('pokemon' => $pokemon); return $app['twig']->render('pages/pokemon.twig', $data); })->bind('pokemon'); $app->get('/test', function () use($app) { $url = $app['url_generator']->generate('pokemon', array('id' => 88)); return $app->redirect($url); }); // Error $app->error(function (\Exception $e, $code) use($app) { if ($app['debug']) { return; } $data = array('title' => 'Error'); return $app['twig']->render('pages/error.twig', $data); }); // Run $app->run();
$data = json_decode($request->getContent(), true); $request->request->replace(is_array($data) ? $data : array()); } }); // Add correct headers before it is sent to the client $app->after(function (Request $request, Response $response) { $response->headers->set("Access-Control-Allow-Origin", "*"); $response->headers->set("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS"); }); $app->register(new ServiceControllerServiceProvider()); $connection = new RestApp\Service\PDOConnection($app); $app['todo.repo'] = $app->share(function () use($connection) { return new RestApp\Repository\TodoRepository($connection); }); $app['todo.controller'] = $app->share(function () use($app) { return new RestApp\Controller\TodoController($app['todo.repo']); }); $app['converter.user'] = $app->share(function () use($app) { return new RestApp\Service\UserAuthentication($app['api.validtoken']); }); $api = $app["controllers_factory"]; $api->get('/todo/get', "todo.controller:getAllTodo")->convert('token', 'converter.user:authorize'); $api->post('/todo/save', "todo.controller:saveTodo")->convert('token', 'converter.user:authorize'); $api->put('/todo/update', "todo.controller:updateTodo")->convert('token', 'converter.user:authorize'); $api->delete('/todo/delete', "todo.controller:deleteTodo")->convert('token', 'converter.user:authorize'); $app->mount($app["api.endpoint"] . '/' . $app["api.version"] . '/{token}', $api); // Proper way to handler error in app $app->error(function (\Exception $e, $code) use($app) { return new JsonResponse(array("statusCode" => $code, "message" => $e->getMessage())); }); $app->run();
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Validator\Constraints as Assert; use Doctrine\DBAL\Connection; use Symfony\Component\Debug\ErrorHandler; use Symfony\Component\Debug\ExceptionHandler; ErrorHandler::register(); ExceptionHandler::register()->setHandler(function (\Exception $e) { print 'INTERNAL_ERROR'; }); $app = new \Silex\Application(); $app['debug'] = false; $app->register(new \Silex\Provider\DoctrineServiceProvider(), array('db.options' => array('driver' => 'pdo_mysql', 'host' => '127.0.0.1', 'dbname' => 'lottery', 'user' => 'root', 'password' => '', 'charset' => 'utf8mb4'))); $app->register(new \Silex\Provider\ValidatorServiceProvider()); $app->error(function (\Exception $e, $code) use($app) { if ($code === 404) { return new Response('NOT_FOUND', $code); } return new Response('INTERNAL_ERROR', $code); }); $app->get('/', function (Request $req) use($app) { $params = $req->query->all(); $constraint = new Assert\Collection(array('user' => new Assert\Regex(array('pattern' => '/^[A-Za-z0-9]{5}$/')), 'code' => new Assert\Regex(array('pattern' => '/^[A-Za-z0-9]{5}$/')))); $errors = $app['validator']->validateValue($params, $constraint); if (count($errors) > 0) { return 'CODE_WRONG'; } $app['db']->setTransactionIsolation(Connection::TRANSACTION_READ_COMMITTED); $app['db']->beginTransaction(); try { // find user for update $sql = 'SELECT wins FROM users WHERE name = ? FOR UPDATE'; $user = $app['db']->fetchAssoc($sql, array((string) $params['user']));