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()); }
private function bootstrapApp() { $app = new Application(); $app['debug'] = true; $app->register(new TwigServiceProvider(), array('twig.templates' => array('main' => '{{ knp_menu_render("my_menu", {"compressed": true}, renderer) }}'))); $app->register(new KnpMenuServiceProvider(), array('knp_menu.menus' => array('my_menu' => 'test.menu.my'))); $app->register(new UrlGeneratorServiceProvider()); $app['test.menu.my'] = function (Application $app) { /** @var $factory \Knp\Menu\FactoryInterface */ $factory = $app['knp_menu.factory']; $root = $factory->createItem('root', array('childrenAttributes' => array('class' => 'nav'))); $root->addChild('home', array('route' => 'homepage', 'label' => 'Home')); $root->addChild('KnpLabs', array('uri' => 'http://knplabs.com', 'extras' => array('routes' => 'other_route'))); return $root; }; $app['test.voter'] = $app->share(function (Application $app) { $voter = new RouteVoter(); $voter->setRequest($app['request']); return $voter; }); $app['knp_menu.matcher.configure'] = $app->protect(function (Matcher $matcher) use($app) { $matcher->addVoter($app['test.voter']); }); $app->get('/twig', function (Application $app) { return $app['twig']->render('main', array('renderer' => 'twig')); })->bind('homepage'); $app->get('/other-twig', function (Application $app) { return $app['twig']->render('main', array('renderer' => 'twig')); })->bind('other_route'); $app->get('/list', function (Application $app) { return $app['twig']->render('main', array('renderer' => 'list')); })->bind('list'); return $app; }
/** * 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"); }
/** * Create a resource and all its sub-resources. * * @param array $resourceConfig * @param array $parentUris * @throws \RuntimeException */ public function createResource(array $resourceConfig, array $parentUris = array()) { if (empty($resourceConfig['uri']) || empty($resourceConfig['ctl'])) { throw new \RuntimeException('Invalid resource config encountered. Config must contain uri and ctl keys'); } if ($resourceConfig['ctl'] instanceof \Closure) { //registers controller factory inline $controllerName = $this->registerController($resourceConfig['uri'], $resourceConfig['ctl'], $parentUris); } elseif (is_string($resourceConfig['ctl'])) { $controllerName = $resourceConfig['ctl']; } else { throw new \RuntimeException('Ctl must be a factory (Closure) or existing service (string name)'); } //setup routes $this->app->get($this->createRouteUri($resourceConfig['uri'], $parentUris, true), sprintf('%s:get', $controllerName)); $this->app->get($this->createRouteUri($resourceConfig['uri'], $parentUris, false), sprintf('%s:cget', $controllerName)); $this->app->post($this->createRouteUri($resourceConfig['uri'], $parentUris, false), sprintf('%s:post', $controllerName)); $this->app->put($this->createRouteUri($resourceConfig['uri'], $parentUris, true), sprintf('%s:put', $controllerName)); $this->app->patch($this->createRouteUri($resourceConfig['uri'], $parentUris, true), sprintf('%s:patch', $controllerName)); $this->app->delete($this->createRouteUri($resourceConfig['uri'], $parentUris, true), sprintf('%s:delete', $controllerName)); //handle sub resources if (!empty($resourceConfig['sub'])) { if (!is_array($resourceConfig['sub'])) { throw new \RuntimeException('sub config must contain array of sub resources'); } //append current uri as parent $parentUris[] = $resourceConfig['uri']; foreach ($resourceConfig['sub'] as $subResource) { $this->createResource($subResource, $parentUris); } } }
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()); }
protected function setUp() { $this->app = new Application(['debug' => 'true']); $this->app->get('/', function () { return new Response('', 200); }); }
public function boot(Application $app) { $app->get('/vendor/{vendor}/{project}/{file}', function ($vendor, $project, $file) use($app) { return $app['public-vendor.response']($app['public-vendor']->resolve($vendor, $file, $project)); })->assert('file', '.*'); $app->get('/vendor/{alias}/{file}', function ($alias, $file) use($app) { return $app['public-vendor.response']($app['public-vendor']->resolve($alias, $file)); }); }
/** * @param RequestContext $context * * @return SilexRouter */ protected function getRouter(RequestContext $context) { $app = new Application(); $app->register(new RoutingServiceProvider()); $app->get('/hello', 'test')->bind('hello1'); $app->get('/hello2', 'test')->bind('hello2'); $app->flush(); $app['request_context'] = $context; return new SilexRouter($app); }
private function loadCall() { $this->application->get('/api/' . $this->version . '/click2call.json', function (Application $application) { $controller = new Click2Call($application); return $controller->getAll(); }); $this->application->get('/api/' . $this->version . '/click2call/call/{name}/{phone}', function (Application $application, $name, $phone) { $controller = new Click2Call($application); return $controller->call($name, $phone); }); }
public function testResolveController() { $resolver = new ControllerResolver($this->app); $class = 'Jonsa\\SilexResolver\\Test\\Data\\IndexController'; $method = "{$class}::index"; $request = Request::create('/'); $request->attributes->set('_controller', $method); $this->app->get('/', $method); $callable = $resolver->getController($request); $this->assertInstanceOf($class, $callable[0]); }
/** * Add routes to the swagger UI documentation browser * * @param Application $app */ public function boot(Application $app) { preg_match('/(\\/.*)\\/.*|(\\/)/', $app['swaggerui.path'], $matches); $assetsPath = count($matches) ? array_pop($matches) : $app['swaggerui.path']; // Index route $app->get($app['swaggerui.path'], array($this, 'getIndex')); // Asset in the root directory $app->get($assetsPath . '/{asset}', array($this, 'getAsset')); // Assets in a folder $app->get($assetsPath . '/{directory}/{asset}', array($this, 'getAssetFromDirectory')); }
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()); }
private function createApplication() { $app = new Application(); unset($app['exception_handler']); $app->register(new EkinoNewRelicServiceProvider(), array('new_relic.enabled' => true)); $app['new_relic.interactor.real'] = $this->getMock('Ekino\\Bundle\\NewRelicBundle\\NewRelic\\NewRelicInteractor'); $app->get('/page', function () { return 'OK'; })->bind('my_page'); $app->get('/error', function () { throw new \RuntimeException('Test Exception'); })->bind('my_error'); return $app; }
public static function init(Application $app) { $app->register(new ServiceControllerServiceProvider()); $app['locations.controller'] = $app->share(function () use($app) { return new LocationsController($app, $app['locations.service']); }); $app['locations.service'] = $app->share(function () use($app) { return new LocationsService(); }); $app->get('/', function () { return "API is UP"; }); $app->get('/locations/{mediaId}', "locations.controller:getLocation"); }
protected function configureApplication(Application $app) { $app['logger'] = $this->getMockLogger(); $app->register(new \Silex\Provider\SessionServiceProvider()); $app->register(new \Silex\Provider\SecurityServiceProvider()); $app->register(new \Renegare\Scoauth\OAuthClientServiceProvider()); $app['security.firewalls'] = ['healthcheck' => ['pattern' => '^/healthcheck', 'anonymous' => true, 'stateless' => true], 'app' => ['pattern' => '^/', 'scoauth' => true]]; $app->get('/healthcheck', function () { return 'All Good!'; }); $app->get('/proteted-uri', function () { return 'All Good!'; }); }
public function testBind() { $app = new Application(); $app->get('/', function () { return 'hello'; })->bind('homepage'); $app->get('/foo', function () { return 'foo'; })->bind('foo_abc'); $app->flush(); $routes = $app['routes']; $this->assertInstanceOf('Symfony\\Component\\Routing\\Route', $routes->get('homepage')); $this->assertInstanceOf('Symfony\\Component\\Routing\\Route', $routes->get('foo_abc')); }
public function testRenderFunction() { $app = new Application(); $app->register(new TwigServiceProvider(), array('twig.templates' => array('hello' => '{{ render("/foo") }}', 'foo' => 'foo'))); $app->get('/hello', function () use($app) { return $app['twig']->render('hello'); }); $app->get('/foo', function () use($app) { return $app['twig']->render('foo'); }); $request = Request::create('/hello'); $response = $app->handle($request); $this->assertEquals('foo', $response->getContent()); }
/** * Add routes to the app that generate swagger documentation based on your annotations * * @param Application $app */ public function boot(Application $app) { AnnotationRegistry::registerAutoloadNamespace("Swagger\\Annotations", $app["swagger.srcDir"]); if ($app["logger"]) { $logger = Logger::getInstance(); $originalLog = $logger->log; $logger->log = function ($entry, $type) use($app, $originalLog) { $app["logger"]->notice($entry); $originalLog($entry, $type); }; } $app->get($app["swagger.apiDocPath"], new ResourceListController()); $app->get("{$app["swagger.apiDocPath"]}/{service}", new ResourceDefinitionController()); }
public function testRenderFunction() { $app = new Application(); $app->register(new HttpFragmentServiceProvider()); $app->register(new HttpCacheServiceProvider(), array('http_cache.cache_dir' => sys_get_temp_dir())); $app->register(new TwigServiceProvider(), array('twig.templates' => array('hello' => '{{ render("/foo") }}{{ render_esi("/foo") }}{{ render_hinclude("/foo") }}', 'foo' => 'foo'))); $app->get('/hello', function () use($app) { return $app['twig']->render('hello'); }); $app->get('/foo', function () use($app) { return $app['twig']->render('foo'); }); $response = $app['http_cache']->handle(Request::create('/hello')); $this->assertEquals('foofoo<hx:include src="/foo"></hx:include>', $response->getContent()); }
/** * @return \Silex\Application */ public function createApplication() { $app = new Application(); $app['debug'] = true; $callback = function () use($app) { $subRequestHandler = new SubRequestHandler($app); return $subRequestHandler->handleSubRequest(new Request(), self::URL_SUB_REQUEST); }; $app->get(self::URL_MASTER_REQUEST, $callback); $app->post(self::URL_MASTER_REQUEST, $callback); $app->get(self::URL_SUB_REQUEST, function () use($app) { return new RedirectResponse(self::URL_SUB_REQUEST); }); return $app; }
public function boot(Application $app) { /** * Respond with a JSON array of the repositories owned by owner query parameter */ $app->get('/repositories', function (Request $request) use($app) { $owner = $request->query->get('owner'); return $app->json($app['store']->getAll($owner)); }); /** * return the information for the named repository */ $app->get('/repositories/{vendor}/{library}', function (Request $request, $vendor, $library) use($app) { return $app->json($app['store']->get("{$vendor}/{$library}")); }); }
/** * {@inheritDoc} */ public function register(SilexApplication $app) { $app['controller.index'] = $app->share(function () use($app) { return new IndexController($app['payum.root_dir']); }); $app->get('/', 'controller.index:indexAction'); }
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()); }
public function createApplication() { $app = new Application(); $app['debug'] = true; $app['session.test'] = true; $app['monolog.logfile'] = __DIR__ . '/../build/logs/dev.monolog.log'; $app['session.storage'] = new MockFileSessionStorage(); $app->register(new Provider\TwigServiceProvider()); $app->register(new Provider\ServiceControllerServiceProvider()); $app->register(new Provider\SecurityServiceProvider()); $app->register(new Provider\SessionServiceProvider()); $app->register(new Provider\UrlGeneratorServiceProvider()); $app->register(new Provider\MonologServiceProvider()); // Mock services $app->register(new MockSmsHandlerProvider()); $app['user.manager'] = $app->share(function () { return new MockUserProvider(); }); $smsLoginProvider = new SmsLoginProvider(); $app->register($smsLoginProvider); $app->mount('', $smsLoginProvider); $app->get('/', function () use($app) { return $app['twig']->render('home.twig', ['message' => 'Testing']); }); $app['security.firewalls'] = array('login' => array('pattern' => '^/login$'), 'secured_area' => array('pattern' => '^.*$', 'sms' => true, 'logout' => ['logout_path' => '/logout'], 'users' => $app->share(function ($app) { return $app['user.manager']; }))); $app['twig.templates'] = ['login.twig' => '<form action="{{ form_action }}" method="POST">{% if mobile is defined %}<p class="number">{{ mobile }}</p>' . '<input type="hidden" name="mobile" value="{{ mobile }}" />{% endif %}' . '<input type="password" placeholder="Secret code" name="code" />' . '<button class="btn btn-positive btn-block" name="submit">Login</button></form>', 'home.twig' => 'Homepage {{ message }}']; unset($app['exception_handler']); return $app; }
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); }
/** * Setup the application. * * @param Application $app */ public function boot(Application $app) { // the direct api route $app->get('/api.js', function (Application $app) { return $app['direct.api']->getApi(); })->bind('directapi'); // the direct api route remoting description $app->get('/remoting.js', function (Application $app) { return $app['direct.api']->getRemoting(); }); // the direct router route $app->post('/route', function (Application $app) { // handle the route return $app['direct.router']->route(); }); }
protected function configureApplication(Application $app) { $app->register(new \Silex\Provider\ServiceControllerServiceProvider()); $app->register(new \Silex\Provider\SecurityServiceProvider()); $provider = new OAuthControllerServiceProvider(); $app->register($provider); $app->mount('/auth', $provider); $app['security.firewalls'] = ['healthcheck' => ['pattern' => '^/healthcheck', 'anonymous' => true, 'stateless' => true], 'auth' => ['pattern' => '^/auth', 'anonymous' => true, 'stateless' => true], 'api' => ['pattern' => '^/', 'soauth' => true, 'stateless' => true]]; $app->get('/healthcheck', function () { return 'All Good!'; }); $app->get('/api', function () { return 'Access Granted'; }); $app['logger'] = $this->getMockLogger(); }
public function boot(Application $app) { $app['dispatcher']->addListener(KernelEvents::RESPONSE, [$this, 'onKernelResponse'], -1000); $app->get($app['debug_bar.path'] . '/{path}', function ($path) use($app) { return $app->sendFile($app['debug_bar']->getJavascriptRenderer()->getBasePath() . '/' . $path, 200, ['Content-Type' => 'text/css']); })->assert('path', '.+'); }
/** * @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('/')); }
public function testDropIn() { $app = new Application(); $app->register(new RoutingServiceProvider()); $app->get('/fake', null); $this->assertSame($app['router']->getRouteCollection(), $app['routes']); $this->assertCount(1, $app['routes']); }