Symfony\Component\HttpKernel\Exception\HttpException; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; $app = new Silex\Application(); $app->register(new Silex\Provider\TwigServiceProvider(), array( 'twig.path' => __DIR__.'/../views', 'twig.options' => array('cache' => __DIR__.'/../cache/twig'), )); $app->register(new Silex\Provider\UrlGeneratorServiceProvider()); $app->register(new Predis\Silex\PredisServiceProvider()); $app['app.languages'] = $app->share(function () { $languages = array(); $finder = new Finder(); foreach ($finder->name('*.min.js')->in(__DIR__.'/../web/shjs/lang') as $file) { if (preg_match('#sh_(.+).min.js#', basename($file), $matches)) { $languages[] = $matches[1]; } } return $languages; }); $app->before(function () use ($app) { // set up some template globals $app['twig']->addGlobal('base_path', $app['request']->getBasePath()); $app['twig']->addGlobal('index_url', $app['url_generator']->generate('homepage')); $app['twig']->addGlobal('create_url', $app['url_generator']->generate('create')); $app['twig']->addGlobal('languages', $app['app.languages']); }); $app->get('/', function () use ($app) { $parentPasteId = $app['request']->get('parent'); $parentPaste = null; if ($parentPasteId) { $parentPaste = $app['predis']->hgetall($id); } return $app['twig']->render('index.html', array( 'paste' => $parentPaste, )); }) ->bind('homepage'); $app->get('/create', function () use ($app) { return $app->redirect($app['url_generator']->generate('homepage')); }); $app->post('/create', function (Request $request) use ($app) { $content = $request->get('content', ''); $content = $this->normalizeContent($content); $id = $this->generateId($content); $paste = array( 'content' => $content, ); $language = $request->get('language', ''); if (in_array($language, $this->languages)) { $paste['language'] = $language; } $paste['created_at'] = time(); $errors = array(); if ('' === trim($paste['content'])) { $errors[] = 'you must enter some content'; } if ($errors) { $page = $app['twig']->render('index.html', array( 'errors' => $errors, 'paste' => $paste, )); return new Response($page, 400); } $app['predis']->hmset($id, $paste) return $app->redirect($app['url_generator']->generate('view', array('id' => $id))); }) ->bind('create'); $app->get('/about', function () use ($app) { return $app['twig']->render('about.html'); }); $app->get('/{id}', function ($id) use ($app) { $paste = $app['predis']->hgetall($id); if (!$paste) { throw new NotFoundHttpException('paste not found'); } return $app['twig']->render('view.html', array( 'copy_url' => $app['url_generator']->generate('homepage', array(' 'paste' => $paste, )); }) ->bind('view') ->assert('id', '[0-9a-f]{8}'); $app->error(function (Exception $e) use ($app) { $code = ($e instanceof HttpException) ? $e->getStatusCode() : 500; return new Response($app['twig']->render('error.html', array( 'message' => $e->getMessage(), )), $code); }); $app->run();