public function testRegister()
 {
     $app = new Application();
     $app->register(new SessionServiceProvider());
     /**
      * Smoke test
      */
     $defaultStorage = $app['session.storage'];
     $app['session.storage'] = $app->share(function () use($app) {
         return new MockArraySessionStorage();
     });
     $app->get('/login', function () use($app) {
         $app['session']->set('logged_in', true);
         return 'Logged in successfully.';
     });
     $app->get('/account', function () use($app) {
         if (!$app['session']->get('logged_in')) {
             return 'You are not logged in.';
         }
         return 'This is your account.';
     });
     $request = Request::create('/login');
     $response = $app->handle($request);
     $this->assertEquals('Logged in successfully.', $response->getContent());
     $request = Request::create('/account');
     $response = $app->handle($request);
     $this->assertEquals('This is your account.', $response->getContent());
 }
Example #2
0
 /**
  * Dump the given Route into a file
  *
  * @param Route $route
  * @param string $name
  * @param array $parameters
  */
 public function build(Route $route, $name, array $parameters = [])
 {
     $url = $this->app['url_generator']->generate($name, $parameters, UrlGeneratorInterface::ABSOLUTE_URL);
     $request = Request::create($url, 'GET', array_merge(['_format' => $route->getFormat()], $parameters));
     $response = $this->app->handle($request);
     $this->write($this->getFilePath($route, $parameters), $response->getContent(), $request->getFormat($response->headers->get('Content-Type')), $route->getFileName());
 }
Example #3
0
 public function testRegisterAndRender()
 {
     $app = new Application();
     $app->register(new MonologExtension(), array('monolog.class_path' => __DIR__ . '/../../../../vendor/monolog/src'));
     $app['monolog.handler'] = $app->share(function () use($app) {
         return new TestHandler($app['monolog.level']);
     });
     $app->get('/log', function () use($app) {
         $app['monolog']->addDebug('logging a message');
     });
     $app->get('/error', function () {
         throw new \RuntimeException('very bad error');
     });
     $app->error(function (\Exception $e) {
         return 'error handled';
     });
     $this->assertFalse($app['monolog.handler']->hasDebugRecords());
     $this->assertFalse($app['monolog.handler']->hasErrorRecords());
     $request = Request::create('/log');
     $app->handle($request);
     $request = Request::create('/error');
     $app->handle($request);
     $this->assertTrue($app['monolog.handler']->hasDebugRecords());
     $this->assertTrue($app['monolog.handler']->hasErrorRecords());
 }
Example #4
0
 /**
  * Run react.
  *
  * @param int    $port
  * @param string $host
  */
 public function run($port, $host)
 {
     $request_handler = function (Request $request, Response $response) {
         echo $request->getMethod() . ' ' . $request->getPath() . PHP_EOL;
         $sf_request = $this->request_bridge->convertRequest($request);
         $sf_response = $this->app->handle($sf_request);
         $this->app->terminate($sf_request, $sf_response);
         $this->response_bridge->send($response, $sf_response);
     };
     $this->http->on('request', $request_handler);
     $this->socket->listen($port, $host);
     $this->loop->run();
 }
 public function testRegisterAndRender()
 {
     $app = new Application();
     $app['debug'] = true;
     $app->register(new SmartyServiceProvider(), array('smarty.dir' => $this->smartyPath, 'smarty.options' => array('setTemplateDir' => $this->smartyPath . '/demo/templates', 'setCompileDir' => $this->smartyPath . '/demo/templates_c', 'setConfigDir' => $this->smartyPath . '/demo/configs', 'setCacheDir' => $this->smartyPath . '/demo/cache')));
     $app->get('/hello', function () use($app) {
         /** @var \Smarty $smarty  */
         $smarty = $app['smarty'];
         $smarty->debugging = true;
         $smarty->caching = true;
         $smarty->cache_lifetime = 120;
         $smarty->assign("Name", "Fred Irving Johnathan Bradley Peppergill", true);
         $smarty->assign("FirstName", array("John", "Mary", "James", "Henry"));
         $smarty->assign("LastName", array("Doe", "Smith", "Johnson", "Case"));
         $smarty->assign("Class", array(array("A", "B", "C", "D"), array("E", "F", "G", "H"), array("I", "J", "K", "L"), array("M", "N", "O", "P")));
         $smarty->assign("contacts", array(array("phone" => "1", "fax" => "2", "cell" => "3"), array("phone" => "555-4444", "fax" => "555-3333", "cell" => "760-1234")));
         $smarty->assign("option_values", array("NY", "NE", "KS", "IA", "OK", "TX"));
         $smarty->assign("option_output", array("New York", "Nebraska", "Kansas", "Iowa", "Oklahoma", "Texas"));
         $smarty->assign("option_selected", "NE");
         return $smarty->fetch('index.tpl');
     });
     $request = Request::create('/hello');
     $response = $app->handle($request);
     $htmlContent = $response->getContent();
     $this->assertGreaterThan(7000, strlen($htmlContent));
     $this->assertNotRegExp('/Whoops/', $htmlContent);
 }
Example #6
0
 public function testLocaleWithBefore()
 {
     $app = new Application();
     $app->before(function (Request $request) use($app) {
         $request->setLocale('fr');
     });
     $app->get('/embed', function (Request $request) {
         return $request->getLocale();
     });
     $app->get('/', function (Request $request) use($app) {
         return $request->getLocale() . $app->handle(Request::create('/embed'), HttpKernelInterface::SUB_REQUEST)->getContent() . $request->getLocale();
     });
     $response = $app->handle(Request::create('/'));
     // locale in sub-request is "en" as the before filter is only executed for the main request
     $this->assertEquals('frenfr', $response->getContent());
 }
 /**
  * Bootstraps the application.
  *
  * This method is called after all services are registered
  * and should be used for "dynamic" configuration (whenever
  * a service must be requested).
  */
 public function boot(Application $app)
 {
     $this->app = $app;
     $app->get($app["documentation.url"] . '/', function () use($app) {
         $subRequest = Request::create($app["documentation.url"], 'GET');
         return $app->handle($subRequest, HttpKernelInterface::SUB_REQUEST);
     });
     $app->get($app["documentation.url"], function () use($app) {
         $home = $app["documentation.dir"] . '/' . $app["documentation.home"] . '.' . $app["documentation.extension"];
         if (is_file($home)) {
             if (is_readable($home)) {
                 $content = file_get_contents($home);
                 return $app["DocumentationRenderer"]->render($content);
             } else {
                 $app->abort("403", "Forbidden");
             }
         } else {
             $app->abort("404", "Documentation Page not Found ");
         }
     });
     $app->get($app["documentation.url"] . "/{pagename}", function (Request $request) use($app) {
         $page = $app["documentation.dir"] . '/' . $request->get('pagename') . '.' . $app["documentation.extension"];
         if (is_file($page)) {
             if (is_readable($page)) {
                 $content = file_get_contents($page);
                 return $app["DocumentationRenderer"]->render($content);
             } else {
                 $app->abort("403", "Forbidden");
             }
         } else {
             $app->abort("404", "Documentation Page not Found ");
         }
     })->assert('pagename', '[a-zA-Z0-9-/]*')->value("pagename", "index");
 }
 protected function checkRouteResponse(Application $app, $path, $expectedContent, $method = 'get', $message = null)
 {
     $app->register(new ServiceControllerServiceProvider());
     $request = Request::create($path, $method);
     $response = $app->handle($request);
     $this->assertEquals($expectedContent, $response->getContent(), $message);
 }
 /**
  *
  * @param  Application $app
  */
 public function register(Application $app)
 {
     /**
      *
      *
      */
     $app['helper.request.clone'] = $app->protect(function ($url, $options = [], $params = []) use($app) {
         $options += ['request' => '', 'method' => ''];
         $params += ['query' => [], 'request' => [], 'attributes' => [], 'cookies' => [], 'files' => [], 'server' => [], 'content' => null];
         if ($options['request'] == '') {
             $options['request'] = $app['request'];
         }
         $request = $options['request'];
         if ($options['method'] == '') {
             $options['method'] = $request->getMethod();
         }
         $params['query'] += $request->query->all();
         $params['request'] += $request->request->all();
         $params['cookies'] += $request->cookies->all();
         $params['files'] += $request->files->all();
         $params['server'] += $request->server->all();
         $subRequest = Request::create($url, $options['method'], [], $params['cookies'], $params['files'], $params['server']);
         if ($request->getSession()) {
             $subRequest->setSession($request->getSession());
         }
         foreach (['query', 'request', 'attributes'] as $p) {
             foreach ($params[$p] as $k => $v) {
                 $subRequest->{$p}->set($k, $v);
             }
         }
         return $subRequest;
     });
     /**
      *
      *
      */
     $app['helper.request.clone.master'] = $app->protect(function ($url, $options = [], $params = []) use($app) {
         return $app->handle($app['helper.request.clone']($url, $options, $params), HttpKernelInterface::MASTER_REQUEST, false);
     });
     /**
      *
      *
      */
     $app['helper.request.clone.sub'] = $app->protect(function ($url, $options = [], $params = []) use($app) {
         return $app->handle($app['helper.request.clone']($url, $options, $params), HttpKernelInterface::SUB_REQUEST, false);
     });
 }
 /**
  * @expectedException \LogicException
  */
 public function testWrongAuthenticationType()
 {
     $app = new Application();
     $app->register(new SecurityServiceProvider(), array('security.firewalls' => array('wrong' => array('foobar' => true, 'users' => array()))));
     $app->get('/', function () {
     });
     $app->handle(Request::create('/'));
 }
Example #11
0
 public function testSecure()
 {
     $app = new Application();
     $app['route_class'] = 'Silex\\Tests\\Route\\SecurityRoute';
     $app->register(new SecurityServiceProvider(), array('security.firewalls' => array('default' => array('http' => true, 'users' => array('fabien' => array('ROLE_ADMIN', '5FZ2Z8QIkA7UTZ4BYkoC+GsReLf569mSKDsfods6LYQ8t+a8EW9oaircfMpmaLbPBh4FOBiiFyLfuZmTSUwzZg=='))))));
     $app->get('/', function () {
         return 'foo';
     })->secure('ROLE_ADMIN');
     $request = Request::create('/');
     $response = $app->handle($request);
     $this->assertEquals(401, $response->getStatusCode());
     $request = Request::create('/');
     $request->headers->set('PHP_AUTH_USER', 'fabien');
     $request->headers->set('PHP_AUTH_PW', 'foo');
     $response = $app->handle($request);
     $this->assertEquals(200, $response->getStatusCode());
 }
Example #12
0
 /**
  * @depends testRegister
  */
 public function testFormatDetection(Application $app)
 {
     $app->get('/api/user/{id}', function ($id) use($app) {
         return $app['request']->getRequestFormat();
     });
     $request = Request::create('/api/user/1');
     $request->headers->set('Accept', 'application/json');
     $response = $app->handle($request);
     $this->assertEquals('json', $response->getContent());
 }
 public function testRouteWorks()
 {
     $app = new Application();
     $app->register(new AutoRouteProvider());
     $app['MyTestController'] = $app->share(function () use($app) {
         return new MyTestController($app);
     });
     $request = Request::create('/my-test/test-method');
     $this->assertEquals('ok', $app->handle($request)->getContent());
 }
 public function testRegister()
 {
     $app = new Application();
     $app->register(new StatsDServiceProvider());
     $app->get('/', function () {
     });
     $request = Request::create('/');
     $app->handle($request);
     $this->assertInstanceOf('StatsD\\Client', $app['statsd']);
 }
 public function testSessionStorage()
 {
     $app = new Application();
     $app->register(new SessionServiceProvider(), ['session.test' => true]);
     $app->register(new TagManagerServiceProvider(), ['gtm.options' => ['id' => 'GTM-XXX']]);
     $request = Request::create('/');
     $app->handle($request);
     $this->assertInstanceOf('ShineUnited\\TagManager\\Container', $app['gtm.container']);
     $this->assertInstanceOf('ShineUnited\\TagManager\\DataLayer', $app['gtm.datalayer']);
 }
 public function connect(Application $app)
 {
     $route = $app['controllers_factory'];
     $route->get('{repo}/commits/search', function (Request $request, $repo) use($app) {
         $subRequest = Request::create('/' . $repo . '/commits/master/search', 'POST', array('query' => $request->get('query')));
         return $app->handle($subRequest, \Symfony\Component\HttpKernel\HttpKernelInterface::SUB_REQUEST);
     })->assert('repo', $app['util.routing']->getRepositoryRegex());
     $route->get('{repo}/commits/{commitishPath}', function ($repo, $commitishPath) use($app) {
         $repository = $app['git']->getRepositoryFromName($app['git.repos'], $repo);
         if ($commitishPath === null) {
             $commitishPath = $repository->getHead();
         }
         list($branch, $file) = $app['util.routing']->parseCommitishPathParam($commitishPath, $repo);
         list($branch, $file) = $app['util.repository']->extractRef($repository, $branch, $file);
         $type = $file ? "{$branch} -- \"{$file}\"" : $branch;
         $pager = $app['util.view']->getPager($app['request']->get('page'), $repository->getTotalCommits($type));
         $commits = $repository->getPaginatedCommits($type, $pager['current']);
         $categorized = array();
         foreach ($commits as $commit) {
             $date = $commit->getDate();
             $date = $date->format('Y-m-d');
             $categorized[$date][] = $commit;
         }
         krsort($categorized);
         $template = $app['request']->isXmlHttpRequest() ? 'commits_list.twig' : 'commits.twig';
         return $app['twig']->render($template, array('page' => 'commits', 'pager' => $pager, 'repo' => $repo, 'branch' => $branch, 'branches' => $repository->getBranches(), 'tags' => $repository->getTags(), 'commits' => $categorized, 'file' => $file));
     })->assert('repo', $app['util.routing']->getRepositoryRegex())->assert('commitishPath', $app['util.routing']->getCommitishPathRegex())->value('commitishPath', null)->convert('commitishPath', 'escaper.argument:escape')->bind('commits');
     $route->post('{repo}/commits/{branch}/search', function (Request $request, $repo, $branch = '') use($app) {
         $repository = $app['git']->getRepositoryFromName($app['git.repos'], $repo);
         $query = $request->get('query');
         $commits = $repository->searchCommitLog($request->get('query'));
         $categorized = array();
         foreach ($commits as $commit) {
             $date = $commit->getDate();
             $date = $date->format('Y-m-d');
             $categorized[$date][] = $commit;
         }
         krsort($categorized);
         return $app['twig']->render('searchcommits.twig', array('repo' => $repo, 'branch' => $branch, 'file' => '', 'commits' => $categorized, 'branches' => $repository->getBranches(), 'tags' => $repository->getTags(), 'query' => $query));
     })->assert('repo', $app['util.routing']->getRepositoryRegex())->assert('branch', $app['util.routing']->getBranchRegex())->convert('branch', 'escaper.argument:escape')->bind('searchcommits');
     $route->get('{repo}/commit/{commit}', function ($repo, $commit) use($app) {
         $repository = $app['git']->getRepositoryFromName($app['git.repos'], $repo);
         $commit = $repository->getCommit($commit);
         $branch = $repository->getHead();
         return $app['twig']->render('commit.twig', array('branch' => $branch, 'repo' => $repo, 'commit' => $commit));
     })->assert('repo', $app['util.routing']->getRepositoryRegex())->assert('commit', '[a-f0-9^]+')->bind('commit');
     $route->get('{repo}/blame/{commitishPath}', function ($repo, $commitishPath) use($app) {
         $repository = $app['git']->getRepositoryFromName($app['git.repos'], $repo);
         list($branch, $file) = $app['util.routing']->parseCommitishPathParam($commitishPath, $repo);
         list($branch, $file) = $app['util.repository']->extractRef($repository, $branch, $file);
         $blames = $repository->getBlame("{$branch} -- \"{$file}\"");
         return $app['twig']->render('blame.twig', array('file' => $file, 'repo' => $repo, 'branch' => $branch, 'branches' => $repository->getBranches(), 'tags' => $repository->getTags(), 'blames' => $blames));
     })->assert('repo', $app['util.routing']->getRepositoryRegex())->assert('commitishPath', $app['util.routing']->getCommitishPathRegex())->convert('commitishPath', 'escaper.argument:escape')->bind('blame');
     return $route;
 }
 public function testRegister()
 {
     $app = new Application();
     $app->register(new CorsServiceProvider());
     $app->get('/me', function () {
         return 'Hi!';
     });
     $response = $app->handle(Request::create('/me'));
     $this->assertEquals(200, $response->getStatusCode());
     $this->assertFalse($response->headers->has('Access-Control-Allow-Origin'));
     $this->assertInstanceOf('Euskadi31\\Silex\\Provider\\Cors\\CorsListener', $app['cors.listener']);
     $this->assertEquals(['/me' => ['methods' => ['GET'], 'requirements' => []]], $app['cors.allowed_methods']);
     $request = Request::create('/me', 'OPTIONS');
     $request->headers->set('Origin', 'localhost');
     $response = $app->handle($request);
     $this->assertEquals(204, $response->getStatusCode());
     $this->assertTrue($response->headers->has('Allow'));
     $this->assertEquals('GET', $response->headers->get('Allow'));
     $this->assertTrue($response->headers->has('Access-Control-Allow-Origin'));
 }
 public function testNonExistentClass()
 {
     $request = Request::create('/gonzalo', 'GET');
     $app = new Application();
     $app->register(new InjectorServiceProvider([]));
     $app->get("/{name}", function (Gonzalo $g, $name) {
         return $g->hello($name);
     });
     $response = $app->handle($request);
     $this->assertEquals(500, $response->getStatusCode());
 }
 public function testApi()
 {
     $app = new Application();
     $app->register(new EmbedlyExtension(), array('embedly.class_path' => __DIR__ . '/../../../vendor/embedly-php/src'));
     $app->get('/', function () use($app) {
         $app['embedly'];
     });
     $request = Request::create('/');
     $app->handle($request);
     $this->assertNotEmpty($app['embedly']->oembed('http://www.youtube.com/watch?v=c9BA5e2Of_U'));
 }
 public function testRegisterAndRender()
 {
     $app = new Application();
     $app->register(new TwigServiceProvider(), array('twig.templates' => array('hello' => 'Hello {{ name }}!')));
     $app->get('/hello/{name}', function ($name) use($app) {
         return $app['twig']->render('hello', array('name' => $name));
     });
     $request = Request::create('/hello/john');
     $response = $app->handle($request);
     $this->assertEquals('Hello john!', $response->getContent());
 }
Example #21
0
 public function testMount()
 {
     $mounted = new ControllerCollection(new Route());
     $mounted->get('/{name}', function ($name) {
         return new Response($name);
     });
     $app = new Application();
     $app->mount('/hello', $mounted);
     $response = $app->handle(Request::create('/hello/Silex'));
     $this->assertEquals('Silex', $response->getContent());
 }
Example #22
0
 public function createAction(Application $app, Request $request)
 {
     // TODO use validator
     $memo = new Memo();
     $memo->title = $request->get('title');
     $memo->content = $request->get('content');
     $memoDao = new MemoDao($app['db'], $app);
     $memo = $memoDao->insert($memo);
     $subRequest = Request::create($app['url_generator']->generate('api_memo', array('id' => $memo->getId(), 'created' => true)), 'GET');
     return $app->handle($subRequest, HttpKernelInterface::SUB_REQUEST);
 }
 public function testUrlGenerationWithHttps()
 {
     $app = new Application();
     $app->get('/secure', function () {
     })->bind('secure_page')->requireHttps();
     $app->get('/', function () use($app) {
         return $app['url_generator']->generate('secure_page');
     });
     $request = Request::create('http://localhost/');
     $response = $app->handle($request);
     $this->assertEquals('https://localhost/secure', $response->getContent());
 }
Example #24
0
 /**
  * test model service is available
  */
 public function testModelManagerServiceIsAvailable()
 {
     $app = new Application();
     $app->register(new ModelProvider(), array('model.finder.namespace' => 'Fake\\NameSpace', 'model.finder.path' => '/tmp/fake'));
     $mockStorage = $this->getMock('Skip\\Model\\ModelStorageHandlerInterface');
     $app['model.storage.handlers'] = array('mock.storage' => $mockStorage);
     $modelManager = $app['model'];
     $this->assertInstanceOf('Skip\\Model\\Manager', $modelManager);
     $request = Request::createFromGlobals();
     $response = $app->handle($request);
     $app->terminate($request, $response);
 }
 public function testRegisterRoutesNull()
 {
     file_put_contents('routes.json', json_encode(array('test' => array('pattern' => '/test/{id}', 'defaults' => array('_controller' => 'Herrera\\Wise\\Test\\Controller::action')))));
     file_put_contents('routes_test.json', json_encode(array('imports' => array(array('resource' => 'routes.json')), 'test' => null)));
     $this->app['wise.options']['mode'] = 'test';
     WiseServiceProvider::registerRoutes($this->app);
     $this->app->boot();
     $request = Request::create('/test/123');
     /** @var Response $response */
     $response = $this->app->handle($request);
     $this->assertRegExp('/could not be found/', $response->getContent());
 }
 public function testRouteWorks()
 {
     $app = new Application();
     $app->register(new AutoRouteProvider());
     $app->register(new AutoTemplateProvider());
     $app->register(new TwigServiceProvider(), array('twig.path' => array(__DIR__ . '/../../template')));
     $app['MyTestController'] = $app->share(function () use($app) {
         return new MyTestController($app);
     });
     $request = Request::create('/my-test/test-template');
     $this->assertEquals('test is ok', $app->handle($request)->getContent());
 }
 public function testApi()
 {
     $app = new Application();
     $app->register(new EmbedlyExtension(), array('embedly.class_path' => __DIR__ . '/../../../vendor/embedly-php/src'));
     $app->get('/', function () use($app) {
         $app['embedly'];
     });
     $request = Request::create('/');
     $app->handle($request);
     $data = $app['embedly']->oembed('http://www.youtube.com/watch?v=c9BA5e2Of_U');
     $this->assertNotEmpty($data);
     $this->assertEquals($data->title, "Rick Astley - Never Gonna Give You Up (Live 2005)");
 }
 public function testRegister()
 {
     $app = new Application();
     $app->register(new ViewServiceProvider(), array('view.class_path' => __DIR__ . '/../../../vendor'));
     $app->get('/', function () use($app) {
         return $app['view']->render(__DIR__ . '/../../view.phtml', array('name' => 'Foo'));
     });
     $request = Request::create('/');
     $response = $app->handle($request);
     $this->assertInstanceOf('Symfony\\Component\\Templating\\PhpEngine', $app['view']);
     $this->assertTrue($app['view']->has('slots'));
     $this->assertEquals($response->getContent(), 'Hello, Foo!');
 }
 public function testSetAndGetMemcached()
 {
     $app = new Application();
     $app->register(new MemcacheExtension(), array('memcache.library' => 'memcached', 'memcache.server' => array(array('localhost', 11211))));
     $app->get('/', function () use($app) {
         $app['memcache'];
     });
     $request = Request::create('/');
     $app->handle($request);
     $testvalue = 'my_test_value';
     $app['memcache']->set('my_test_key', $testvalue);
     $this->assertSame($testvalue, $app['memcache']->get('my_test_key'));
 }
 public function testSetAndGet()
 {
     $app = new Application();
     $app->register(new PredisExtension(), array('predis.class_path' => __DIR__ . '/../../../vendor/predis/lib', 'predis.config' => array('prefix' => 'predis__')));
     $app->get('/', function () use($app) {
         $app['predis'];
     });
     $request = Request::create('/');
     $app->handle($request);
     $testvalue = 'my_test_value';
     $app['predis']->set('my_test_key', $testvalue);
     $this->assertSame($testvalue, $app['predis']->get('my_test_key'));
 }