$app['guzzle'] = $app->share(function () use($app) { return new Guzzle\Http\Client(); }); $app->register(new Silex\Provider\ServiceControllerServiceProvider()); $app->register(new Silex\Provider\ValidatorServiceProvider()); $app['home'] = $app->share(function () use($app) { return new Controllers\Home(); }); $app['versions'] = $app->share(function () use($app) { $versions = new Models\Versions($app['db']); return new Controllers\Versions($versions); }); $app->before(function (Request $request, Silex\Application $app) { if (extension_loaded('newrelic')) { newrelic_name_transaction(current(explode('?', $_SERVER['REQUEST_URI']))); } }); $app->after(function (Request $request, Response $response) { $response->headers->set('Access-Control-Allow-Origin', '*'); $response->headers->set('Access-Control-Allow-Methods', 'GET,POST,HEAD,DELETE,PUT,OPTIONS'); $response->headers->set('Access-Control-Allow-Headers', 'Content-Type'); if ($response->getStatusCode() == 200) { $response->headers->set('Content-Type', 'application/json; charset=UTF-8'); } }); $app->match("{url}", function ($url) use($app) { return "OK"; })->assert('url', '.*')->method("OPTIONS"); $app->get('/projects/{project}/latest', 'versions:latest'); $app->get('/', 'home:index'); $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';
->add('operator', TextType::class) ->add('combined', FileType::class) ->add('directions', FileType::class) ->add('imag', FileType::class) ->add('real', FileType::class) ->add('magnitudes', FileType::class) ->getForm(); // Output request and response $app->after(function (Request $request, Response $response) { if ($response->headers->has('X-No-Logging')) { return; } $protocol = $request->server->get('SERVER_PROTOCOL'); error_log(sprintf("Request\r\n\033[1;33m%s %s %s\e[0;33m\r\n%s\033[0m", $request->getMethod(), $request->getRequestUri(), $protocol, $request->headers)); $color = $response->isSuccessful() ? 32 : 31; error_log(sprintf("Response\r\n\033[1;%dmHTTP/%s %s %s\e[0;%1\$dm\r\n%s[0m", $color, $response->getProtocolVersion(), $response->getStatusCode(), Response::$statusTexts[$response->getStatusCode()], $response->headers)); }); // Routes $app->post('/login', function(Request $request) use($users, $privateKey) { $name = $request->get('name'); $user = $users->findOne(['name' => $name]); $password = $request->get('password'); if (null === $user || $password !== $user['password']) { throw new HttpException(Response::HTTP_FORBIDDEN, 'Invalid username or password.');
$app->register(new FormExtension()); $app->register(new TranslationExtension(), array('translator.messages' => array())); $app->register(new TwigExtension(), array('twig.path' => array(__DIR__ . '/templates', __DIR__ . '/../vendor/Symfony/Bridge/Twig/Resources/views/Form'), 'twig.class_path' => __DIR__ . '/../vendor/silex/vendor/twig/lib')); $app->register(new DoctrineMongoDBExtension(), array('doctrine.odm.mongodb.connection_options' => array('database' => 'springbok-silex', 'host' => 'localhost'), 'doctrine.odm.mongodb.documents' => array(array('type' => 'annotation', 'path' => __DIR__ . '/Document', 'namespace' => 'Document')), 'doctrine.odm.mongodb.metadata_cache' => 'array', 'doctrine.common.class_path' => __DIR__ . '/../vendor/mongodb-odm/lib/vendor/doctrine-common/lib', 'doctrine.mongodb.class_path' => __DIR__ . '/../vendor/mongodb-odm/lib/vendor/doctrine-mongodb/lib', 'doctrine.odm.mongodb.class_path' => __DIR__ . '/../vendor/mongodb-odm/lib')); $app['doctrine.odm.mongodb.hydrators_dir'] = __DIR__ . '/../cache/doctrine/hydrators'; Doctrine\ODM\MongoDB\Mapping\Driver\AnnotationDriver::registerAnnotationClasses(); require_once __DIR__ . '/config.php'; if (!is_dir($app['doctrine.odm.mongodb.hydrators_dir'])) { mkdir($app['doctrine.odm.mongodb.hydrators_dir'], 0777, true); } $app->before(function () use($app) { if (!isset($app['culin.entity'])) { throw new \RuntimeException('Configuration entry "culin.entity" is not set'); } $app['repository'] = $app['doctrine.odm.mongodb.dm']->getRepository($app['culin.entity']); $app['query_builder'] = $app->share(function ($app) { return $app['doctrine.odm.mongodb.dm']->createQueryBuilder($app['culin.entity']); }); $app['form'] = $app->share(function ($app) { return function ($entity = null) use($app) { return $app['form.factory']->create(new $app['culin.form'](), $entity); }; }); $app['twig']->addExtension(new CulinExtension($app)); $app['twig']->addExtension(new \Twig_Extensions_Extension_Debug()); $app['twig']->enableDebug(); }); $app->after(function () use($app) { $app['doctrine.odm.mongodb.dm']->flush(); }); return $app;
if (!isset($data->parameters)) { return new Response('Missing parameters.', 400, array('Content-Type' => 'text/json')); } $procedure = "procedure\\" . ucfirst($procedure); if (!class_exists($procedure)) { return new Response('Invalid procedure.', 400, array('Content-Type' => 'text/json')); } $class = new $procedure(); $result = $class->execute($data->parameters); switch ($result['status']) { case 'success': return new Response(json_encode($result['data']), 200); break; case 'error': return new Response('Error executing procedure', 400, array('Content-Type' => 'text/json')); break; } }); $app->before(function (Request $request) use($app) { if (!$request->headers->has('authorization')) { return new Response('Unauthorized', 401); } require_once __DIR__ . '/configs/clients.php'; if (!in_array($request->headers->get('authorization'), array_keys($clients))) { return new Response('Unauthorized', 401); } }); $app->after(function (Request $request, Response $response) { $response->headers->set('Content-Type', 'text/json'); }); $app->run();
// Would prefer to do this: /*return new Response('', 201, array( 'Access-Control-Allow-Origin: *', 'Access-Control-Allow-Methods: GET, POST, OPTIONS', 'Access-Control-Allow-Headers: content-type, origin, accept', 'Access-Control-Max-Age: 1728000', 'Content-Length: 0', 'Content-Type: text/plain', ));*/ } }); $app->after(function (Request $request, Response $response) { // Add *some* support for JSONP, but we can't toggle services as we have no POST support if ($request->getMethod() === 'GET' && $request->get('callback') !== null) { $response->setContent($request->get('callback') . '(' . $response->getContent() . ')'); } else { // Let our CORS requests work with this app $response->headers->set('Access-Control-Allow-Origin', '*'); } }); if (!$debug) { $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); });
// 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 require_once 'vendor/autoload.php'; require_once 'database.php'; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Security\Core\Exception\UsernameNotFoundException; use Symfony\Component\Security\Core\User\InMemoryUserProvider; use Symfony\Component\Security\Core\User\User; use Security\UserProvider; date_default_timezone_set('America/Araguaina'); setlocale(LC_ALL, 'pt_BR.utf-8'); $app = new Silex\Application(); $app->register(new JDesrosiers\Silex\Provider\CorsServiceProvider(), array("cors.allowOrigin" => "*", "cors.allowMethods" => "GET, HEAD, OPTIONS, POST, PUT, DELETE")); $app->after($app["cors"]); $app['debug'] = true; $app['db'] = Database::open(); /* $app['security.jwt'] = [ 'secret_key' => 'Very_secret_key', 'life_time' => 86400, 'options' => [ 'username_claim' => 'sub', // default name, option specifying claim containing username 'header_name' => 'X-Access-Token', // default null, option for usage normal oauth2 header 'token_prefix' => 'Bearer', ] ]; $app['users'] = function () use ($app) { return new UserProvider($app['db']); };
use Symfony\Component\HttpFoundation\Response; use PhpAmqpLib\Connection\AMQPStreamConnection; use PhpAmqpLib\Message\AMQPMessage; $app = new Silex\Application(); $app['debug'] = getenv('DEBUG'); $app['bookmark.repository'] = function () { return new App\BookmarkRepository(new \PDO(getenv('DSN'))); }; $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()); } }); $app->after(function (Request $request, Response $response) { $response->headers->set('Access-Control-Allow-Origin', '*'); }); $app->get('/', function () use($app) { $resources = $app['bookmark.repository']->findAll(); return json_encode($resources); }); $app->post('/', function (Request $request) use($app) { $bookmark = new App\Bookmark(Uuid::uuid4(), new App\Url($request->request->get('url'))); $app['bookmark.repository']->save($bookmark); $message = json_encode((object) array('event' => 'bookmark_has_been_created', 'uuid' => (string) $bookmark->getUuid(), 'url' => (string) $bookmark->getUrl())); // publish to RabbitMQ $connection = new AMQPStreamConnection('rabbitmq', 5672, 'guest', 'guest'); $channel = $connection->channel(); $channel->queue_declare('bookmark', false, false, false, false); $msg = new AMQPMessage($message); $channel->basic_publish($msg, '', 'bookmark');
$proxies = array($_SERVER['REMOTE_ADDR']); if (is_array($app['proxy'])) { $proxies = $app['proxy']; } Request::setTrustedProxies($proxies); } // Initialize buzz client $client = $app['buzz.client'] ?: new Buzz\Client\FileGetContents(); if ($app['proxy_server.address']) { $client->setProxy($app['proxy_server.address']); } // create Transport API $app['api'] = new Transport\API(new Buzz\Browser($client)); // allow cross-domain requests, enable cache $app->after(function (Request $request, Response $response) { $response->headers->set('Access-Control-Allow-Origin', '*'); $response->headers->set('Cache-Control', 's-maxage=30, public'); }); // Serializer $app['serializer'] = $app->share(function () use($app) { $fields = $app['request']->get('fields') ?: array(); return new Serializer(array(new FieldsNormalizer($fields)), array('json' => new JsonEncoder())); }); // Redis $redis = null; try { if ($app['redis.config']) { $redis = new Predis\Client($app['redis.config']); $redis->connect(); } } catch (Exception $e) { $app['monolog']->addError($e->getMessage());
// enable translations $app['locale'] = 'en_GB'; $app->before(function () use($app) { if ($locale = $app['request']->get('locale')) { $app['locale'] = $locale; $app['session']->set('locale', $locale); } else { if ($locale = $app['session']->get('locale')) { $app['locale'] = $locale; } } }); // do some security stuff $app->after(function (Request $request, Response $response) { $response->headers->set('X-Frame-Options', 'DENY'); $response->headers->set('X-Content-Type-Options', 'nosniff'); $response->headers->set('X-UA-Compatible', 'IE=edge'); }); $app->register(new Silex\Provider\TranslationServiceProvider(), array('locale_fallbacks' => array('en_GB'))); $app['translator'] = $app->share($app->extend('translator', function ($translator, $app) { $translator->addLoader('yaml', new YamlFileLoader()); $translator->addResource('yaml', __DIR__ . '/../translations/en_GB.yml', 'en_GB'); //$translator->addResource('yaml', __DIR__.'/../translations/fi_FI.yml', 'fi_FI'); return $translator; })); $app->register(new Silex\Provider\UrlGeneratorServiceProvider()); $app->register(new Silex\Provider\FormServiceProvider()); // templates $app->register(new Silex\Provider\TwigServiceProvider(), array('twig.path' => __DIR__ . '/../views')); // db $dbOptions = array('db.options' => array('driver' => DB_DRIVER, 'host' => DB_HOST, 'dbname' => DB_NAME, 'user' => DB_USER, 'password' => DB_PASS));
* the controller output array using _template. */ $app->get('/4', function () use($app) { return array('foo' => 'moo', '_template' => 'example4.html'); })->bind('example4'); /** * We can also configure the template in the request attributes. */ $app->get('/5', function (Symfony\Component\HttpFoundation\Request $request) use($app) { $request->attributes->set('_template', 'example5.php'); return array('foo' => 'boo'); })->bind('example5'); /** * Exceptions can be handled as shown below. */ $app->get('/6', function () use($app) { throw new \Exception('Hello this is error'); })->bind('error'); $app->error(function (\Exception $exception, $code) { return new Symfony\Component\HttpFoundation\Response($exception->getMessage(), $code); }); /** * Finally, another middleware intercepts the response and wraps it * with a layout, which is simply another view. */ $app->after(function ($request, $response) use($app) { $footer = $app['view']->create('footer.mustache', array('date' => date(DATE_RFC2822))); $layout = $app['view']->create('layout.twig')->nest($footer, 'footer'); $response->setContent($layout->with(array('content' => $response->getContent()))); }); $app->run();
<?php $loader = (require __DIR__ . '/../vendor/autoload.php'); \Doctrine\Common\Annotations\AnnotationRegistry::registerLoader(array($loader, 'loadClass')); $config = (require __DIR__ . '/../app/config.php'); $app = new \Silex\Application($config['common']); require "bootstrap.php"; $app->get('/', function () use($app) { return $app->redirect($app["url_generator"]->generate("beranda")); }); $app->mount('/', new \Jowy\P2bj\Http\Controller\AppController($app)); $app->after(function () use($app) { if ($app['session']->has('expire') && $app['session']->get('expire')['value'] > time()) { $app['session']->clear(); } }); //$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 \Symfony\Component\HttpFoundation\Response($message); //}); $app->run();
}; $app['google.geocode.factory'] = function ($app) { return new \Jowy\RabbitInternet\Factory\GoogleGeocodeServiceFactory(); }; $app['geocode.service'] = function ($app) { return $app['google.geocode.factory']->create($app['google_auth']); }; $app['sqlite.storage.factory'] = function ($app) { return new \Jowy\RabbitInternet\Factory\SqliteStorageFactory($app); }; $app['sqlite.storage'] = function ($app) { return $app['sqlite.storage.factory']->create(); }; $app['search.service'] = function ($app) { return new \Jowy\RabbitInternet\Services\Search($app['sqlite.storage'], $app['twitter.service'], $app['settings']['cache_ttl']); }; /** * mount controller */ $app->mount('/', new \Jowy\RabbitInternet\Controllers\MainController()); /** * setting middleware to set and retrieve cookie */ $app->after(function (\Symfony\Component\HttpFoundation\Request $request, \Symfony\Component\HttpFoundation\Response $response) { $cookie = $request->cookies; if (!$cookie->has('Jowy-UserId')) { $response->headers->setCookie(new \Symfony\Component\HttpFoundation\Cookie('Jowy-UserId', uniqid('Jowy', false))); } return $response; }); $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(); }
return $twig; })); $app->before(function ($request) use($app) { $app['twig']->addGlobal('active', $request->get('_route')); }); // Swift Mailer // ------------ $app->register(new Silex\Provider\SwiftmailerServiceProvider()); $app['swiftmailer.options'] = array('host' => 'localhost', 'port' => 25, 'username' => '', 'password' => '', 'encryption' => null, 'auth_mode' => null); $app->register(new Silex\Provider\UrlGeneratorServiceProvider()); // CORS Cross-Origin Resource Sharing // ---------------------------------- $http_origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : NULL; if (in_array($http_origin, $app['cors_allowed_origins'])) { $app->register(new JDesrosiers\Silex\Provider\CorsServiceProvider(), array('cors.allowOrigin' => $http_origin)); $app->after($app['cors']); } // Logging // ------- $app->register(new Silex\Provider\MonologServiceProvider(), array('monolog.logfile' => __DIR__ . '/../logs/development.log')); // Logging // ------- $app->register(new Silex\Provider\MonologServiceProvider(), array('monolog.logfile' => __DIR__ . '/../logs/development.log')); // --------------------------------------------------------------------------------------------------------------------- // Routes // --------------------------------------------------------------------------------------------------------------------- $app->get('/', function () use($app) { return $app['twig']->render('master.twig'); })->bind('home'); $app->get('/mail', function () use($app) { return $app['twig']->render('mail.twig');
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\JsonResponse; require_once __DIR__ . "/../vendor/autoload.php"; $app = new Silex\Application(); require_once __DIR__ . "/../resources/config.php"; // Accept and decode JSON data before the call to controllers $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()); } }); // 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');
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\CssSelector\CssSelectorConverter; $app = new Silex\Application(); $app['debug'] = true; // Register the monolog logging service $app->register(new Silex\Provider\MonologServiceProvider(), array('monolog.logfile' => 'php://stderr')); $app->after(function (Request $req, Response $res) { if ($req->get('jsonp_callback') !== null && $req->getMethod() === 'GET') { $contentType = $res->headers->get('Content-Type'); $jsonpContentTypes = array('application/json', 'application/json; charset=utf-8', 'application/javascript'); if (!in_array($contentType, $jsonpContentTypes)) { // Don't touch the response return; } if ($res instanceof JsonResponse) { $res->setCallBack($req->get('jsonp_callback')); } else { $res->setContent($req->get('jsonp_callback') . '(' . $res->getContent() . ');'); } } }); // Our web handlers $app->get('/get-content/', function (Request $req) { $client = new Parser\CurlHttpClient(); $url = urldecode($req->get('url')); $res = $client->get($url); $html = new JsonResponse(array('url' => $url, 'res' => $res['body'])); //$html = json_encode(array('res'=>$res['body'])); //$response = new Response();