public function testResolverEvents() { $class = 'Jonsa\\SilexResolver\\Test\\Data\\FooClass'; $count = 1; $this->app->on(ResolverEvents::CLASS_RESOLVED, function (ClassResolvedEvent $event) use($class, &$count) { $this->assertInstanceOf($class, $event->getResolvedObject()); $count++; }); $this->app['make']($class); $this->assertEquals(2, $count); }
/** * {@inheritdoc} */ public function boot(Application $app) { $app->on(KernelEvents::TERMINATE, function (PostResponseEvent $event) use($app) { if ($app['mailer.initialized']) { $app['logger.swift_mailer_handler']->onKernelTerminate($event); } }); }
public function register(Application $app) { $app->on(KernelEvents::CONTROLLER, function (FilterControllerEvent $event) use($app) { $reflectionFunction = new \ReflectionFunction($event->getController()); $parameters = $reflectionFunction->getParameters(); foreach ($parameters as $param) { $class = $param->getClass(); if ($class && array_key_exists($class->name, $this->injectables)) { $event->getRequest()->attributes->set($param->name, $app[$this->injectables[$class->name]]); } } }); }
/** * Registers services on the given app. * * @param Application $app An Application instance */ public function register(Application $app) { $app["security.acl.dbal.provider.options"] = array("class_table_name" => "acl_classes", "entry_table_name" => "acl_entries", "oid_table_name" => "acl_object_identities", "oid_ancestors_table_name" => "acl_object_identity_ancestors", "sid_table_name" => "acl_security_identities"); $app["security.acl.object_identity_retrieval_strategy"] = $app->share(function ($app) { return new ObjectIdentityRetrievalStrategy(); }); $app["security.acl.security_identity_retrieval_strategy"] = $app->share(function ($app) { return new SecurityIdentityRetrievalStrategy($app["security.role_hierarchy"], $app["security.authentication.trust_resolver"]); }); $app["security.acl.permission_granting_strategy"] = $app->share(function ($app) { $service = new PermissionGrantingStrategy(); $service->setAuditLogger($app["security.acl.audit_logger"]); return $service; }); $app["security.acl.permission.map"] = $app->share(function ($app) { return new AclVoter($app["security.acl.provider"], $app["security.acl.object_identity_retrieval_strategy"], $app['security.acl.security_identity_retrieval_strategy'], $app['security.acl.permission.map'], $app["logger"]); }); $app["security.acl.dbal.connection"] = $app->share(function ($app) { return $app["db"]; }); $app["security.acl.dbal.provider"] = $app->share(function ($app) { return new AclProvider($app["security.acl.dbal.connection"], $app["security.acl.permission_granting_strategy"], $app["security.acl.dbal.provider.options"], $app["security.acl.cache"]); }); $app['security.acl.dbal.schema'] = $app->share(function ($app) { return new Schema($app["security.acl.dbal.provider.options"], $app["security.acl.dbal.connection"]); }); $app["security.acl.dbal.schema_listener"] = $app->share(function ($app) { return new AclSchemaListener($app); }); $app["security.acl.provider"] = $app->share(function ($app) { return $app["security.acl.dbal.provider"]; }); $app["security.acl.cache.doctrine"] = $app->share(function ($app) { return new DoctrineAclCache($app['security.acl.cache.doctrine.cache_impl'], $app['security.acl.permission_granting_strategy']); }); $app["security.acl.cache.doctrine.cache_impl"] = $app->share(function ($app) { return $app['"doctrine.orm.default_result_cache"']; }); $app["security.acl.permission.map"] = $app->share(function ($app) { return new BasicPermissionMap(); }); // FR : ajouter la command InitAcl // EN : add InitAclCommand $app->on(ConsoleServiceProvider::INIT, function () use($app) { /* @var $console \Symfony\Component\Console\Application */ $app["console"]->add(new InitAclCommand()); return $console; }); }
public function testCallbacksAsServices() { $app = new Application(); $app['service'] = $app->share(function () { return new self(); }); $app->before('service:beforeApp'); $app->after('service:afterApp'); $app->finish('service:finishApp'); $app->error('service:error'); $app->on('kernel.request', 'service:onRequest'); $app->match('/', 'service:controller')->convert('foo', 'service:convert')->before('service:before')->after('service:after'); $request = Request::create('/'); $response = $app->handle($request); $app->terminate($request, $response); $this->assertEquals(array('CONVERT', 'BEFORE APP', 'ON REQUEST', 'BEFORE', 'ERROR', 'AFTER', 'AFTER APP', 'FINISH APP'), $app['service']->called); }
public function boot(Application $app) { $app->on(KernelEvents::EXCEPTION, [$app['qafoo.listener.convert_exception'], 'onKernelException']); }
default: if ($app['debug']) { $data['exception']['message'] = $e->getMessage(); $data['exception']['code'] = $e->getCode(); } } $data['message'] = $message; return new JsonResponse($data, $code); }); $app->on(KernelEvents::VIEW, function ($event) use($app) { $view = $event->getControllerResult(); var_dump($view); exit; if (is_null($view) || is_string($view)) { return; } $request = $event->getRequest(); if (!$request->attributes->get('failed') && $request->attributes->has('success_handler')) { $handler = $request->attributes->get('success_handler'); $view = $handler($view, $request); if ($view instanceof Response) { $event->setResponse($view); return; } } $view = (object) $view; $response = new \Symfony\Component\HttpFoundation\JsonResponse($view); $event->setResponse($response); }); $app->mount('/users', new UserController()); return $app;
/** * Registers services on the given app. * * This method should only be used to configure services and parameters. * It should not get services. * * @param Application $app */ public function register(Application $app) { $app->on(KernelEvents::CONTROLLER, function (FilterControllerEvent $event) use($app) { $reflectionFunction = new ReflectionFunction($event->getController()); $parameters = $reflectionFunction->getParameters(); foreach ($parameters as $parameter) { $class = $parameter->getClass(); if (!$class) { continue; } if (array_key_exists($class->name, $this->serviceFactoryMap)) { $service = $app[$this->serviceFactoryMap[$class->name]]; } else { $service = new $class->name(); } $event->getRequest()->attributes->set($parameter->name, $service); } }); }
public function testOn() { $app = new Application(); $app['pass'] = false; $app->on('test', function (Event $e) use($app) { $app['pass'] = true; }); $app['dispatcher']->dispatch('test'); $this->assertTrue($app['pass']); }
public function boot(Application $app) { $app->on(KernelEvents::VIEW, [$app['qafoo.listener.view'], 'onKernelView']); }
/** * @inheritdoc */ public function boot(Application $app) { $app->get('/.{_format}', function (Application $app, $_format) { return $app['serializer']->serialize(array('status' => 200, 'message' => 'ok'), $_format); })->bind('index')->value('_format', 'json'); $app->mount('/', $app['controller_note']); $app->mount('/', $app['controller_category']); #handle note relationships $app->on('note_before_index', $app['add_parent_id_to_query']); $app->on('note_before_create', $app['add_parent_id_to_model']); $app->on('note_before_delete', $app['resource_belongs_to_parent_or_throw']); $app->on('note_before_read', $app['resource_belongs_to_parent_or_throw']); $app->on('note_before_update', $app['resource_belongs_to_parent_or_throw']); $app->error($app['rest_error_handler']); }
public function boot(Application $app) { $app->on(KernelEvents::CONTROLLER, [$app['qafoo.listener.param_converter'], 'onKernelController']); }
public function connect(Application $app) { $controllers = $app['controllers_factory']; $controllers->get('/', function () use($app) { return $app['twig']->render('index.html', array()); })->bind('homepage'); $controllers->get('/login', function () use($app) { $username = $app['request']->server->get('PHP_AUTH_USER', false); $password = $app['request']->server->get('PHP_AUTH_PW', false); if ($username && $password || $app['debug']) { $userManager = $app['user.manager']; //Retrieve user information $ldapUser = $app['ldap.manager']->getUserInfo($username); if (null !== $ldapUser) { $user = $userManager->getOrCreate($ldapUser); if (null !== $user) { $isAuthenticated = $app['ldap.manager']->bind($user->getDn(), $password); if ($isAuthenticated) { $app['session']->set('isAuthenticated', $isAuthenticated); $app['session']->set('user', $user); return $app->redirect($app['url_generator']->generate('homepage')); } } } } return $app['login.basic_login_response']; })->bind('login'); $controllers->get('/users', function () use($app) { return $app['twig']->render('users.html', array('users' => $app['ldap.manager']->listUsers())); }); $controllers->get('/show-prototype/{idVm}', function ($idVm) use($app) { return $app['twig']->render('show.html', array('vm' => $app['vm.manager']->load($idVm), 'users' => $app['user_notify.manager']->loadBy(array('vm' => $idVm)))); })->bind('show'); $controllers->get('/enlarge-version/{idVm}', function ($idVm) use($app) { return $app['twig']->render('log.html', array('vm' => $app['vm.manager']->load($idVm))); })->bind('enlarge_version'); $controllers->get('/_ajax_log/{idVm}', function ($idVm) use($app) { $filename = VmLogger::getLogFile($idVm); $lastModified = 0; if (file_exists($filename)) { $lastModified = filemtime($filename); } $data = array(); $data['status'] = 0; //Test if the file has been mofidied since the last 5 min if ($lastModified >= strtotime($app['config']['log.max_time_before_logging'])) { $data['msg'] = $app['twig']->render('_ajax_log.html', array('vm' => $app['vm.manager']->load($idVm))); } else { $data['status'] = 1; } return new JsonResponse($data, 200); })->bind('_ajax_log'); $controllers->get('/create-prototype', function () use($app) { $params = array(); $params['integs'] = $app['integ.manager']->loadAllAvailable(); $params['users'] = $app['ldap.manager']->listUsers(); $params['vmActive'] = $app['vm.manager']->getActive(); $params['vmToStart'] = $app['vm.manager']->getToStart(); return $app['twig']->render('create.html', $params); })->bind('create-prototype'); $controllers->get('/force-start/{idVm}', function ($idVm) use($app) { $vmManager = $app['vm.manager']; $vm = $vmManager->load($idVm); if ($vm->getCreatedBy()->getIdUser() == $app['session']->get('user')->getIdUser()) { $vm->setStatus(Vm::TO_START); $vmManager->flush($vm); $app['session']->set('flash', array('type' => 'success', 'short' => 'The VM has restarted', 'ext' => 'The given VM has been set to start.')); } else { $app['session']->set('flash', array('type' => 'error', 'short' => 'You have no rigth to do this.', 'ext' => 'You can only force the expiration of a VM that you have created.')); } return $app->redirect('/'); })->bind('force-start'); $controllers->get('/force-expire-prototype/{idVm}', function ($idVm) use($app) { $vmManager = $app['vm.manager']; $vm = $vmManager->load($idVm); if ($vm->getCreatedBy()->getIdUser() == $app['session']->get('user')->getIdUser()) { $vm->setExpiredDt(new \DateTime()); $vm->setStatus(Vm::EXPIRED); $vmManager->flush($vm); $app['session']->set('flash', array('type' => 'success', 'short' => 'The VM has expired', 'ext' => 'The given VM has been set to expired. Its slot will be free and could be reuse in some minutes by another person.')); } else { $app['session']->set('flash', array('type' => 'error', 'short' => 'You have no rigth to do this.', 'ext' => 'You can only force the expiration of a VM that you have created.')); } return $app->redirect('/'); })->bind('force-expire-prototype'); $controllers->get('/ask-more-prototype/{idVm}', function ($idVm) use($app) { $vmManager = $app['vm.manager']; /** * @var Vm $vm */ $vm = $vmManager->load($idVm); if ($vm->getCreatedBy()->getIdUser() == $app['session']->get('user')->getIdUser()) { $date = $vm->getExpiredDt(); $date->add(new \DateInterval(sprintf('PT%dH', $app['config']['vm.expired_in_value']))); $day = $date->format('w'); $short = sprintf('%s hours has been added for your VM', $app['config']['vm.expired_in_value']); if ($day == 0 || $day == 6) { // expire on weekend... well add 2 more days then. $date->add(new \DateInterval('P2D')); $short = 'Your VM will expire after the weekend'; } /** * Force the clone because without it doctrine do not detect the change and so it do not update the db */ $vm->setExpiredDt(clone $date); $vm->setStatus(Vm::RUNNING); $vmManager->save($vm); $app['session']->set('flash', array('type' => 'success', 'short' => $short, 'ext' => 'Please don\'t abuse of this feature. Do you really need as much time to test your stuff?')); } else { $app['session']->set('flash', array('type' => 'error', 'short' => 'You have no rigth to do this.', 'ext' => 'You can only add time of a VM that you have created.')); } return $app->redirect('/'); })->bind('ask-more-prototype'); /** * Call on create-prototype page, actually does the creation */ $controllers->post('/launch-prototype', function () use($app) { $users = $app['request']->request->get('users'); //Refactor this please... if ($app['integ.manager']->hasAvailableInteg()) { // Create a VM $vm = new Vm(); $user = $app['user.manager']->getOrCreate($app['session']->get('user')); $vm->setCreatedBy($user); $integ = $app['integ.manager']->load($app['request']->request->get('integ')); $vm->setInteg($integ->getIdInteg()); // Save the vm first $app['vm.manager']->save($vm); foreach ($users as $userName) { $ldapUser = $app['ldap.manager']->getUserInfo($userName); $user = $app['user.manager']->getOrCreate($ldapUser); $userNotify = new \LaFourchette\Entity\UserNotify(); $userNotify->setUser($user); $userNotify->setVm($vm); $app['user_notify.manager']->save($userNotify); } } $app['session']->set('flash', array('type' => 'success', 'short' => 'Your prototype will be ready soon.', 'ext' => 'You will receive an email as soon as it will be ready to be use.')); return $app->redirect('/'); })->bind('launch-prototype'); # Include or render for twig $controllers->get('/_status', function () use($app) { $vms = $app['vm.manager']->loadVm(); return $app['twig']->render('_status.html', array('vms' => $vms, 'default_expiration_delay' => Vm::EXPIRED_AT_DEFAULT_VALUE)); })->bind('_status'); $controllers->post('/_comment', function (Request $request) use($app) { $app['vm.manager']->comment($request->get('id'), $request->get('value')); return $request->get('value'); }); $controllers->get('/logout', function () use($app) { $app['session']->set('isAuthenticated', false); $app['session']->set('user', null); return $app['login.basic_login_response']; })->bind('logout'); $app->error(function (\Exception $e, $code) use($app) { if ($app['debug']) { return; } $page = 404 == $code ? '404.html' : '500.html'; return new Response($app['twig']->render($page, array('code' => $code)), $code); }); // check login $app->on(KernelEvents::REQUEST, function (GetResponseEvent $event) use($app) { $request = $event->getRequest(); if ($request->get('_route') === '_profiler') { return; } if ($request->get('_route') === 'login') { return; } if (!$app['session']->get('isAuthenticated')) { $ret = $app->redirect($app['url_generator']->generate('login')); } else { $ret = null; } if ($ret instanceof Response) { $event->setResponse($ret); } }, 0); return $controllers; }
/** * {@inheritdoc} */ public function boot(Application $app) { $app->on(DefaultController::POST_BEFORE_CREATE, $app['listener.post_before_create']); $app->on(DefaultController::POST_BEFORE_UPDATE, $app['listener.post_before_update']); $app->on(DefaultController::POST_BEFORE_DELETE, $app['listener.post_before_update']); $app->mount('/admin/', $app["crud.controller.post"]); $app->mount('/admin/', $app['crud.controller.user']); $app->mount('/admin/', $app['crud.controller.role']); $app->mount("/", $app["controller.default"]); }
<?php $loader = (require_once __DIR__ . '/../vendor/autoload.php'); use Silex\Application, SilexOpauth\OpauthExtension; $app = new Application(); $app['debug'] = true; $app['opauth'] = array('login' => '/auth/login', 'callback' => '/auth/callback', 'config' => array('security_salt' => '_SECURE_RANDOM_SALT_', 'Strategy' => array('Facebook' => array('app_id' => 'APP_ID', 'app_secret' => 'APP_SECRETE')))); $app->register(new OpauthExtension($app)); // Listen for events $app->on(OpauthExtension::EVENT_ERROR, function ($e) { $this->log->error('Auth error: ' . $e['message'], ['response' => $e->getSubject()]); $e->setArgument('result', $this->redirect('/')); }); $app->on(OpauthExtension::EVENT_SUCCESS, function ($e) { $response = $e->getSubject(); /* find/create a user, oauth response is in $response and it's already validated! store the user in the session */ $e->setArgument('result', $this->redirect('/')); }); $app->run();
public function boot(Application $app) { # ===================================================== # # EVENT LISTENERS # # ===================================================== # $themeActivateListener = new ThemeActivateListener($app); $app->on(ThemeEvents::THEME_ACTIVATE, array($themeActivateListener, 'onThemeActivate')); # ===================================================== # # DEFAULT ROUTES # # ===================================================== # // This was causing issues with homepages defined by df and eg sites // Also, can't redirect to another '/' url or it causes infinite loop // $app->get('/', function() use ($app) { // return $app->redirect($app['url_generator']->generate($app['np.homepage_route'])); // })->bind('np.default'); $app->error(function (\Exception $e, $code) use($app) { // Show error trace for non-404 errors if ($app['debug'] && $code != 404) { return; } $templates = $app['np.theme.manager']->getActiveTheme()->getTemplates(); switch ($code) { case 404: $message = 'Sorry, the page you are looking for could not be found.'; $template = $templates['error']['404']; break; case 500: $message = 'We are sorry, but something went terribly wrong.'; $template = $templates['error']['500']; default: $message = $e->getMessage(); $template = $templates['error']['general']; } // each theme can have its own error.twig, otherwise the default one is used $content = $app['twig']->render($template, array('code' => $code, 'message' => $message)); return new Response($content, $code); }); }