Ejemplo n.º 1
0
 protected function addRoutes(ControllerCollection $c)
 {
     $c->get('/users', 'admin')->bind('users');
     $c->match('/users/edit/{id}', 'edit')->assert('id', '\\d*')->bind('useredit');
     $c->match('/userfirst', 'first')->bind('userfirst');
     $c->post('/user/{action}/{id}', 'modify')->bind('useraction');
     $c->match('/profile', 'profile')->bind('profile');
     $c->get('/roles', 'viewRoles')->bind('roles');
 }
Ejemplo n.º 2
0
 protected function addRoutes(ControllerCollection $c)
 {
     $c->match('/file/edit/{namespace}/{file}', 'edit')->assert('file', '.+')->assert('namespace', '[^/]+')->value('namespace', 'files')->bind('fileedit')->after(function (Request $request, Response $response) {
         if ($request->isMethod('POST')) {
             $response->headers->set('X-XSS-Protection', '0');
         }
     });
     $c->match('/files/{namespace}/{path}', 'manage')->assert('namespace', '[^/]+')->assert('path', '.*')->value('namespace', 'files')->value('path', '')->bind('files');
 }
Ejemplo n.º 3
0
 public function connect(Application $app)
 {
     $post = new ControllerCollection(new Route());
     $post->match('/', "post.controller:index")->method('GET')->bind('listPosts');
     $post->match('/{id}', "post.controller:view")->method('GET|POST')->assert('id', '\\d+');
     $post->match('/new', "post.controller:form")->method('POST|GET')->bind('AddPost');
     $post->match('/update/{id}', "post.controller:update")->method('POST|GET')->bind('UpdatePost');
     $post->match('/destroy/{id}', "post.controller:destroy")->method('GET')->bind('DeletePost');
     return $post;
 }
Ejemplo n.º 4
0
 public function connect(Application $app)
 {
     $user = new ControllerCollection(new Route());
     $user->get('/', "user.controller:show");
     $user->match('/login', "user.controller:login")->method('POST|GET');
     $user->match('/show', "user.controller:show")->method('GET|POST');
     $user->match('/add', "user.controller:add")->method('POST|GET');
     $user->match('/logout', "user.controller:logout")->method('GET');
     return $user;
 }
Ejemplo n.º 5
0
 protected function addRoutes(ControllerCollection $c)
 {
     $c->get('/about', 'about')->bind('about');
     $c->get('/checks', 'checks')->bind('checks');
     $c->get('/clearcache', 'clearCache')->bind('clearcache');
     $c->get('/', 'dashboard')->bind('dashboard');
     $c->get('/omnisearch', 'omnisearch')->bind('omnisearch-results');
     $c->match('/prefill', 'prefill')->bind('prefill');
     $c->match('/tr/{domain}/{tr_locale}', 'translation')->bind('translation')->assert('domain', 'messages|contenttypes|infos')->value('domain', 'messages')->value('tr_locale', $this->app['locale']);
 }
Ejemplo n.º 6
0
 protected function addRoutes(ControllerCollection $c)
 {
     $c->method('GET|POST');
     $c->match('/editcontent/{contenttypeslug}/{id}', 'edit')->bind('editcontent')->assert('id', '\\d*')->value('id', '');
     $c->get('/overview/{contenttypeslug}', 'overview')->bind('overview');
     $c->get('/relatedto/{contenttypeslug}/{id}', 'related')->bind('relatedto')->assert('id', '\\d*');
 }
Ejemplo n.º 7
0
 protected function addRoutes(ControllerCollection $c)
 {
     $c->get('/login', 'getLogin')->bind('login');
     $c->post('/login', 'postLogin')->bind('postLogin');
     $c->match('/logout', 'logout')->bind('logout');
     $c->get('/resetpassword', 'resetPassword')->bind('resetpassword');
 }
Ejemplo n.º 8
0
 public function match($pattern, $to = null)
 {
     if ($this->defaultControllerClass && is_string($to) && method_exists($this->defaultControllerClass, $to)) {
         $to = [$this->defaultControllerClass, $to];
     }
     return parent::match($pattern, $to);
 }
Ejemplo n.º 9
0
 public function connect(Application $app)
 {
     $controllers = new ControllerCollection();
     $controllers->match('/{slug}', function (Application $app, Request $request, $username) {
         return $this->getProcessor($request)->execute()->getResponse();
     });
     return $controllers;
 }
Ejemplo n.º 10
0
 protected function addRoutes(ControllerCollection $controllers)
 {
     $controllers->post('/api/users', array($this, 'newAction'));
     $controllers->get('/api/users/{name}', array($this, 'showAction'))->bind('api_users_show');
     $controllers->get('/api/users', array($this, 'listAction'));
     $controllers->put('/api/users/{name}', array($this, 'updateAction'));
     $controllers->delete('/api/users/{name}', array($this, 'deleteAction'));
     $controllers->match('api/users/{name}', array($this, 'updateAction'))->method('PATCH');
 }
Ejemplo n.º 11
0
 /**
  * Register the method $controllerName as controller for the given method and uri.
  *
  * @param \Silex\ControllerCollection $cc
  * @param string                      $controllerName Fully qualified method name of the controller
  * @return \Silex\Controller
  */
 public function process(ControllerCollection $cc, $controllerName)
 {
     $controller = $cc->match($this->uri, $controllerName);
     if ('MATCH' != ($method = strtoupper($this->method))) {
         // limit to configured method(s)
         $controller = $controller->method($method);
     }
     return $controller;
 }
Ejemplo n.º 12
0
 protected function addRoutes(ControllerCollection $c)
 {
     $c->method('GET|POST');
     $c->get('/list/{contenttypeslug}', 'overview')->bind('overview');
     $c->match('/add-edit/{contenttypeslug}/{id}', 'edit')->bind('editcontent')->value('id', '');
     $c->get('/delete/{contenttypeslug}/{id}', 'delete')->bind('deletecontent');
     $c->post('/content-{action}/{contenttypeslug}/{id}', 'modify')->bind('contentaction');
     $c->get('/relatedto/{contenttypeslug}/{id}', 'related')->bind('relatedto');
 }
Ejemplo n.º 13
0
 public function connect(Application $app)
 {
     $controller = new ControllerCollection($app['route_factory']);
     $controller->match('/', function () use($app) {
         if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
             $browsersLocale = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
             if (in_array($browsersLocale, array('en', 'fr'))) {
                 $app['locale'] = $browsersLocale;
             }
         }
         return $app->redirect($app['url_generator']->generate('homepage', array('locale' => $app['locale'])));
     })->bind('home');
     $controller->match('/{locale}/', function () use($app) {
         // Get all reports
         $reports = $app['repository.report']->findAll();
         return $app['twig']->render('Report/list.html.twig', array('reports' => $reports));
     })->bind('homepage');
     return $controller;
 }
 public function match($pattern, $to = null)
 {
     $controller = parent::match($pattern, $to);
     $route = $controller->getRoute();
     if (!$route instanceof CorsRoute) {
         throw new \RuntimeException('The generated route does not have the proper type, did you register the service provider properly?');
     }
     $route->setControllerCollection($this);
     return $controller;
 }
Ejemplo n.º 15
0
 /**
  * This uses default class/method if not provided
  *
  * {@inheritdoc}
  */
 public function match($pattern, $to = null)
 {
     if (!$this->defaultControllerClass) {
         return parent::match($pattern, $to);
     }
     if ($to === null && $this->defaultControllerMethod) {
         $to = [$this->defaultControllerClass, $this->defaultControllerMethod];
     } elseif (is_string($to) && Str::startsWith($to, '::')) {
         $to = [$this->defaultControllerClass, substr($to, 2)];
     }
     return parent::match($pattern, $to);
 }
 public static function connectController(ControllerCollection $ctrlsFactory, $controllerArray)
 {
     $ctrlAccessPath = $controllerArray['Namespace'] . '\\' . $controllerArray['Name'] . '::';
     $prefix = $controllerArray['Prefix'];
     foreach ($controllerArray['Actions'] as $_action) {
         $method = Annots\Method::forUsage($_action['Method']);
         $route = $prefix . $_action['Route'];
         $action = $_action['Name'];
         $binded = Annots\Bind::forUsage($_action['Bind'], $prefix, $_action['Name']);
         /** @var Controller $routeFactored */
         $routeFactored = $ctrlsFactory->match($route, $ctrlAccessPath . $action)->bind($binded)->method($method);
         // TODO : proposer le assert en annot
         //if (strpos($route, '{id}') !== false)
         //    $routeFactored->assert('id', "\d+");
     }
 }
Ejemplo n.º 17
0
 protected function addRoute(ControllerCollection $ctr, $name, array $config)
 {
     $config = new ArrayCollection($config);
     if (!($path = $config['path'])) {
         return;
     }
     if (!($defaults = $config['defaults'])) {
         return;
     }
     $defaults = new ArrayCollection($defaults);
     if (!($to = $defaults->remove('_controller'))) {
         return;
     }
     $route = $ctr->match($path, $to);
     $before = $defaults->remove('_before') ?: '::before';
     $before = $this->resolveBefore($before);
     $route->before($before);
     $after = $defaults->remove('_after') ?: '::after';
     $after = $this->resolveAfter($after);
     $route->after($after);
     foreach ($defaults as $key => $value) {
         $route->value($key, $value);
     }
     foreach ($config['requirements'] ?: [] as $variable => $callback) {
         $callback = $this->callbackResolver->resolveCallback($callback);
         $requirement = is_callable($callback) ? call_user_func($callback) : $callback;
         $route->assert($variable, $requirement);
     }
     if ($host = $config['host']) {
         $route->getRoute()->setHost($host);
     }
     if ($methods = $config['methods']) {
         $route->getRoute()->setMethods($methods);
     }
     if ($schemes = $config['schemes']) {
         $route->getRoute()->setSchemes($schemes);
     }
     $route->bind($name);
 }
Ejemplo n.º 18
0
 /**
  * {@inheritdoc}
  */
 protected function addRoutes(ControllerCollection $controllers)
 {
     $controllers->get('/adminusers', [$this, 'listAction'])->assert('page', '\\d+')->value('page', 1)->bind('admin_adminuser_list');
     $controllers->match('/adminusers/new', [$this, 'newAction'])->method('GET|POST')->bind('admin_adminuser_new');
     $controllers->match('/adminusers/profile/{id}', [$this, 'profileAction'])->method('GET|POST')->bind('admin_adminuser_profile');
 }
 /**
  * {@inheritdoc}
  */
 protected function registerBackendRoutes(ControllerCollection $collection)
 {
     $collection->match('/extend/my-custom-backend-page-route', [$this, 'exampleBackendPage']);
 }
Ejemplo n.º 20
0
 /**
  * Mapeia uma rota convencional em um controlador.
  *
  * @param Route $route
  * @param \Silex\ControllerCollection $controller
  * @param String $controllerService
  * @param \ReflectionClass $reflectionClass
  * @param \ReflectionMethod $reflectionMethod
  * @param Array $beforeFilters
  * @param Array $afterFilters
  *
  * @throws FrameworkException
  * @throws FrameworkException
  */
 private function mapBasicRoute($route, $controller, $controllerService, $reflectionClass, $reflectionMethod, $beforeFilters, $afterFilters)
 {
     $app = $this->app;
     if ($route->method != null || !empty($route->methods)) {
         $routeMethods = $route->method == null ? $route->methods : array($route->method);
         if ($route->pattern) {
             if ($route->template) {
                 $ctr = $app->match($route->pattern, function (Request $request) use($app, $controllerService, $reflectionMethod, $route) {
                     $method = $reflectionMethod->getName();
                     $params = (array) $app[$controllerService]->{$method}($request);
                     return $app['twig']->render($route->template, $params);
                 })->method(implode('|', $routeMethods));
             } else {
                 $ctr = $app->match($route->pattern, $controllerService . ":" . $reflectionMethod->getName())->method(implode('|', $routeMethods));
             }
         } else {
             $ctr = $controller->match(strtolower($reflectionMethod->getName()), $controllerService . ":" . $reflectionMethod->getName())->method(implode('|', $routeMethods));
         }
         if ($route->name != null) {
             $ctr->bind($route->name);
         }
         if (!empty($beforeFilters)) {
             foreach ($beforeFilters->methods as $method) {
                 $this->addFilter($method, 'before', $ctr, $controllerService, $reflectionClass);
             }
         }
         if (!empty($afterFilters)) {
             foreach ($afterFilters->methods as $method) {
                 $this->addFilter($method, 'after', $ctr, $controllerService, $reflectionClass);
             }
         }
     } else {
         throw FrameworkException::routeMethodNotDefinedError(sprintf("O metodo '%s' do controlador '%s' foi anotado como rota mas nao possui um metodo (post,get,etc) definido", $reflectionMethod->getName(), $reflectionClass->getName()));
     }
 }
 /**
  * @param ControllerCollection $controllers
  */
 private function registerExperienceRoutes(ControllerCollection $controllers)
 {
     $controllers->match('/person/{personId}/experience/create', 'vbee.controller.experience:createAction')->bind('admin_experience_create')->method('GET|POST');
     $controllers->match('/person/{personId}/experience/{experienceId}/edit', 'vbee.controller.experience:editAction')->bind('admin_experience_edit')->method('GET|POST');
     $controllers->match('/person/{personId}/experience/{experienceId}/delete', 'vbee.controller.experience:deleteAction')->bind('admin_experience_delete')->method('GET');
 }
Ejemplo n.º 22
0
 public function connect(Application $app)
 {
     $app->register(new SecurityServiceProvider());
     $controller = new ControllerCollection($app['route_factory']);
     $app['security.firewalls'] = array('login' => array('pattern' => '^/[a-z]{2}/login$', 'anonymous' => true), 'login_google_openid' => array('pattern' => '^/[a-z]{2}/login/with/google/openid$', 'anonymous' => true), 'login_google_openid' => array('pattern' => '^/[a-z]{2}/login/with/google$', 'anonymous' => true), 'signup' => array('pattern' => '^/[a-z]{2}/signup$', 'anonymous' => true), 'signup_confirmation' => array('pattern' => '^/[a-z]{2}/signup/confirm/[a-zA-Z0-9]+$', 'anonymous' => true), 'secured' => array('pattern' => '^.*$', 'form' => array('login_path' => '/fr/login', 'check_path' => '/login_check'), 'logout' => array('logout_path' => '/logout'), 'users' => $app->share(function () use($app) {
         return new UserProvider($app['db']);
     })));
     $app['security.role_hierarchy'] = array('ROLE_ADMIN' => array('ROLE_USER', 'ROLE_ALLOWED_TO_SWITCH'));
     $app['security.access_rules'] = array(array('^/admin', 'ROLE_ADMIN'));
     /**
      * Route : show login forms
      */
     $controller->match('/{locale}/login', function (Request $request) use($app) {
         $form = $app['form.factory']->createBuilder(new UserLoginType())->getForm();
         $formSSO = $app['form.factory']->createBuilder(new UserLoginOpenIDType())->getForm();
         return $app['twig']->render('Security/login.html.twig', array('form' => $form->createView(), 'formSSO' => $formSSO->createView(), 'error' => $app['security.last_error']($request), 'last_username' => $app['session']->get('_security.last_username')));
     })->bind('route.user.login');
     $controller->match('/logout', function (Request $request) use($app) {
         $app['session']->clear();
     })->bind('route.user.logout');
     /**
      * Route : show signup form
      */
     $controller->get('/{locale}/signup', function (Request $request) use($app) {
         $form = $app['form.factory']->createBuilder(new UserSignupType())->getForm();
         return $app['twig']->render('Security/signup.html.twig', array('form' => $form->createView()));
     })->bind('route.user.signup');
     /**
      * Route : confirmation link to activate an account using token
      */
     $controller->get('/{locale}/signup/confirm/{confirmationToken}', function (Request $request) use($app) {
         $confirmationToken = $app['request']->get('confirmationToken');
         if (!is_null($confirmationToken)) {
             $user = $app['repository.user']->findByConfirmationToken($confirmationToken);
             if ($user && $user->isEnabled() == 0) {
                 $data['enabled'] = 1;
                 $data['confirmation_token'] = null;
                 $app['repository.user']->update($data, array('id' => $user->getId()));
                 $app['monolog']->addDebug(sprintf('Account activated: %s (%d)', $user->getUsername(), $user->getId()));
                 $app['session']->getFlashBag()->add('warning', 'message.user.signup.success_enabling_account');
                 return $app->redirect($app['url_generator']->generate('homepage', array('locale' => $app['locale'])));
             }
         }
         $app['monolog']->addDebug('Account has NOT been enabled or is already enabled');
         $app['session']->getFlashBag()->add('warning', 'message.user.signup.failed_enabling_account');
         return $app->redirect($app['url_generator']->generate('homepage', array('locale' => $app['locale'])));
     })->bind('route.user.register.confirmation');
     $controller->post('/{locale}/signup', function (Request $request) use($app) {
         $form = $app['form.factory']->createBuilder(new UserSignupType())->getForm();
         $form->bind($app['request']);
         $data = $form->getData();
         if ($form->isValid()) {
             $app['monolog']->addDebug('Checking existing user with mail: ' . $data['mail']);
             $userProvider = new UserProvider($app['db']);
             $isUserExist = $this->checkUserExist($userProvider, $data['mail']);
             if ($isUserExist) {
                 $user = $userProvider->loadUserByUsername($data['mail']);
                 if (!$user->isEnabled()) {
                     $app['monolog']->addDebug('User exists but not enabled');
                     $app['session']->getFlashBag()->add('warning', 'message.user.signup.user_already_exist_but_not_validated');
                     return $app['twig']->render('Security/signup.html.twig', array('form' => $form->createView(), 'post' => $data));
                 } else {
                     $app['monolog']->addDebug('User already exists with this mail');
                     $app['session']->getFlashBag()->add('warning', 'message.user.signup.user_already_exist');
                     return $app['twig']->render('Security/signup.html.twig', array('form' => $form->createView(), 'post' => $data));
                 }
             } else {
                 $app['monolog']->addDebug('user doesnt exist');
                 $splittedFullname = explode(' ', $data['fullname'], 2);
                 unset($data['fullname']);
                 $data['firstname'] = isset($splittedFullname[0]) ? ucfirst($splittedFullname[0]) : '';
                 $data['lastname'] = isset($splittedFullname[1]) ? ucfirst($splittedFullname[1]) : '';
                 $data['roles'] = 'ROLE_USER';
                 $data['enabled'] = false;
                 $app['monolog']->addDebug('Adding new user with those values: ' . json_encode($data));
                 $resCreateUser = $this->createUser($app, $data['firstname'], $data['lastname'], $data['roles'], $data['enabled'], $data['mail'], $data['password']);
                 if ($resCreateUser <= 0) {
                     $app['monolog']->addDebug('User cannot be created');
                     $app['session']->getFlashBag()->add('warning', 'Your account has not been created. Please try again.');
                     return $app['twig']->render('Security/signup.html.twig', array('form' => $form->createView(), 'post' => $data));
                 }
             }
             // refresh User with all data from DB
             $user = $userProvider->loadUserByUsername($data['mail']);
             $app['monolog']->addDebug('User created');
             $template = $app['twig']->loadTemplate('Security/Mail/mail/signup.html.twig');
             $mailData = array('message_mail_activate_account' => $app['translator']->trans('message.mail.activate_account'), 'message_mail_intro' => $app['translator']->trans('message.mail.intro'), 'message_mail_ready_to_activate_account' => $app['translator']->trans('message.mail.ready_to_activate_account'), 'message_mail_click_here' => $app['translator']->trans('message.mail.click_here'), 'message_mail_href_validation' => $app['request']->getSchemeAndHttpHost() . $app['url_generator']->generate('route.user.register.confirmation', array('locale' => $app['locale'], 'confirmationToken' => $user->getConfirmationToken())));
             $bodyHtml = $template->renderBlock('body_html', $mailData);
             $bodyText = $template->renderBlock('body_text', $mailData);
             $message = \Swift_Message::newInstance()->setSubject($app['translator']->trans('lbl.mail.subject.account_confirmation'))->setFrom(array($app['mailer.config.from']))->setTo(array($data['mail']))->setBody($bodyText, 'text/plain')->addPart($bodyHtml, 'text/html');
             $app['mailer']->send($message);
             $app['session']->getFlashBag()->add('success', 'message.user.signup_successful');
             $app['session']->getFlashBag()->add('success', $app['translator']->trans('message.user.signup.please_validate_your_account', array('%mail%' => $data['mail'])));
             return $app->redirect($app['url_generator']->generate('homepage', array('locale' => $app['locale'])));
         }
         $app['session']->getFlashBag()->add('warning', 'form.invalid.supply');
         return $app['twig']->render('Security/signup.html.twig', array('form' => $form->createView(), 'post' => $data));
     })->bind('route.user.register');
     $controller->match('/{locale}/login/with/google', function (Request $request) use($app) {
         $formSSO = $app['form.factory']->createBuilder(new UserLoginOpenIDType())->getForm();
         $formSSO->bind($app['request']);
         $data = $formSSO->getData();
         if (!$app['session']->has('username')) {
             $openid = new LightOpenID($_SERVER['SERVER_NAME']);
             if (!$openid->mode) {
                 $openid->identity = $data['openid_identifier'];
                 $openid->required = array('email' => 'contact/email', 'firstname' => 'namePerson/first', 'lastname' => 'namePerson/last');
                 return $app->redirect($openid->authUrl());
             } else {
                 // Provider returns valid data
                 if ($openid->validate()) {
                     $attributes = $openid->getAttributes();
                     $app['monolog']->addDebug('Successfully logged in using openid');
                     $userProvider = new UserProvider($app['db']);
                     $isUserExist = $this->checkUserExist($userProvider, $attributes['contact/email']);
                     if ($isUserExist) {
                         $user = $userProvider->loadUserByUsername($attributes['contact/email']);
                         if (!$user->isEnabled()) {
                             $app['monolog']->addDebug('User exists but not enabled');
                             $app['session']->getFlashBag()->add('warning', 'message.user.signup.user_already_exist_but_not_validated');
                             $app->redirect($app['url_generator']->generate('homepage', array('locale' => $app['locale'])));
                         } else {
                             $token = new UsernamePasswordToken($user, $user->getPassword(), 'secured', $user->getRoles());
                             $app['session']->set('_security_secured', serialize($token));
                             $app['session']->set('username', $user->getUsername());
                         }
                     } else {
                         $data = array();
                         $data['signupProvider'] = 'google';
                         $data['firstname'] = $attributes['namePerson/first'];
                         $data['lastname'] = $attributes['namePerson/last'];
                         $data['roles'] = 'ROLE_USER';
                         $data['mail'] = $attributes['contact/email'];
                         $data['enabled'] = true;
                         $data['password'] = '';
                         $app['monolog']->addDebug('Adding new user with those values: ' . json_encode($data));
                         $resCreateUser = $this->createUser($app, $data['firstname'], $data['lastname'], $data['roles'], $data['enabled'], $data['mail'], $data['password'], $data['signupProvider']);
                         if ($resCreateUser <= 0) {
                             $app['monolog']->addDebug('User cannot be created');
                             $app['session']->getFlashBag()->add('warning', 'message.user.signup.account_has_not_been_created');
                             return $app['twig']->render('Security/login.html.twig', array('form' => $formSSO->createView(), 'post' => $data));
                         }
                         $userProvider = new UserProvider($app['db']);
                         $isUserExist = $this->checkUserExist($userProvider, $attributes['contact/email']);
                         if ($isUserExist) {
                             $user = $userProvider->loadUserByUsername($attributes['contact/email']);
                             $token = new UsernamePasswordToken($user, $user->getPassword(), 'secured', $user->getRoles());
                             $app['session']->set('_security_secured', serialize($token));
                             $app['session']->set('username', $user->getUsername());
                         }
                     }
                 } else {
                     return $app->redirect($openid->authUrl());
                 }
             }
         }
         if (isset($app['auth']) && !$app['auth']($app['session']->get('username'))) {
             $app['monolog']->addDebug('Something got wrong with authentification');
             return new Response($app['twig']->render('500.html.twig'), 403);
         }
         $app['twig']->addGlobal('username', $app['session']->get('username'));
         $app['session']->getFlashBag()->add('success', $app['translator']->trans('message.user.loggedin.as', array('%username%' => $app['session']->get('username'))));
         return $app->redirect($app['url_generator']->generate('homepage', array('locale' => $app['locale'])));
     })->bind('route.user.check_login_sso');
     return $controller;
 }
Ejemplo n.º 23
0
 public function match($pattern, $to)
 {
     $wrapped = $this->wrapController($to);
     return parent::match($pattern, $wrapped);
 }
 public function testAfter()
 {
     $controllers = new ControllerCollection(new Route());
     $controllers->after('mid1');
     $controller = $controllers->match('/{id}/{name}/{extra}', function () {
     })->after('mid2');
     $controllers->after('mid3');
     $this->assertEquals(array('mid1', 'mid2', 'mid3'), $controller->getRoute()->getOption('_after_middlewares'));
 }
Ejemplo n.º 25
0
Archivo: Upload.php Proyecto: bolt/bolt
 protected function addRoutes(ControllerCollection $c)
 {
     $c->match('/{namespace}', 'uploadNamespace')->before([$this, 'before'])->value('namespace', 'files')->bind('upload');
     return $c;
 }
Ejemplo n.º 26
0
 public function connect(Application $app)
 {
     $controllers = new ControllerCollection();
     $triggers = $app['config']['triggers'];
     $controllers->match('/' . $triggers['login'], function (Request $request) use($app, $triggers) {
         $user_id = $request->get('user');
         if (!$user_id) {
             $user = true;
         } else {
             $user = $app['data']->find('users.' . $user_id);
             $user = $user ? $user : true;
         }
         $app['store']->set('user', $user);
         if ($request->get('redirect')) {
             return $app->redirect($request->get('redirect'));
         } else {
             return $app->redirect('/');
             // redirect to homepage
         }
     })->method('GET|POST')->bind('do_login');
     $controllers->get('/' . $triggers['logout'], function (Request $request) use($app, $triggers) {
         $app['store']->clear('user');
         if ($request->get('redirect')) {
             return $app->redirect($request->get('redirect'));
         } else {
             return $app->redirect('/');
             // redirect to homepage
         }
     })->bind('do_logout');
     $controllers->get('/' . $triggers['assets'] . '/{asset_path}.{format}', function ($asset_path, $format) use($app) {
         if (!($output = $app['assets']->convert($format, $asset_path . '.' . $format))) {
             $app->abort(404);
         }
         return new Response($output, 200, array('Content-Type' => $app['assets']->contentType($format)));
     })->assert('asset_path', '.+')->value('asset_path', '')->bind('get_assets');
     $controllers->get('/' . $triggers['data'] . '/{data_path}', function ($data_path) use($app) {
         // TODO: get JSON representation of data
         $result = $app['data']->find(str_replace('/', '.', $data_path));
         if (!$result) {
             $app->abort(404);
         } else {
             return json_encode($result);
         }
     })->assert('data_path', '.+')->value('data_path', '')->bind('get_json_data');
     $controllers->get('/' . $triggers['shorturl'] . '/{page_id}', function ($page_id) use($app) {
         if (!($page = $app['pagetree']->getPageById($page_id))) {
             $app->abort(404);
         }
         return $app->redirect($page->nice_url, 301);
     })->bind('short_url');
     // everything else...
     $controllers->get('/{route}', function ($route) use($app) {
         // lets see if we need to do any checking of custom routes
         $routes = $app['config']['routes'] ? $app['config']['routes'] : array();
         $replacements = array();
         if (count($routes)) {
             foreach ($routes as $routeSpec => $endRoute) {
                 // see if there are any page ID placeholders that need parsing out
                 if (preg_match('/\\(:id=([^\\)]*)\\)/', $routeSpec, $matches)) {
                     if ($routePage = $app['pagetree']->getPageById($matches[1])) {
                         $replacements[] = trim(str_replace($app['config']['index'], '', $routePage->nice_url), '/');
                         $routeSpec = str_replace(array($matches[0], $app['config']['index']), array($routePage->nice_url, ''), $routeSpec);
                     } else {
                         continue;
                     }
                 }
                 $routeSpec = trim($routeSpec, '/');
                 // replace helper placeholders
                 $routeSpec = str_replace(array('(:any)', '(:num)', '(:all)', '/'), array('([^/]*)', '(\\d*)', '(.*)', '\\/'), $routeSpec);
                 $routeSpec = '/^' . $routeSpec . '$/';
                 if (preg_match($routeSpec, $route, $matches)) {
                     // we have a match!
                     for ($i = 0; $i < count($matches); $i++) {
                         if ($i !== 0) {
                             $replacements[] = $matches[$i];
                         }
                     }
                     $route = $endRoute;
                     break;
                 }
             }
             // replace and reference tokens in the route
             // '(:id=test)/hello': '$1'
             $replacementTokens = array();
             for ($j = 0; $j < count($replacements); $j++) {
                 $replacementTokens['$' . ($j + 1)] = $replacements[$j];
             }
             $route = str_replace(array_keys($replacementTokens), array_values($replacementTokens), $route);
             // replace any page ID placeholders in the route itself
             if (preg_match('/\\(:id=(.*)\\)/', $route, $matches)) {
                 $routePage = $app['pagetree']->getPageById($matches[1]);
                 $route = str_replace(array($matches[0], $app['config']['index']), array($routePage->nice_url, ''), $route);
             }
         }
         if (!($page = $app['pagetree']->getPage($route))) {
             $app->abort(404);
         }
         if ($user = $app['store']->get('user')) {
             $app['twig']->addGlobal('user', $user);
         }
         try {
             return $app['twig']->render($page->fs_path, array());
         } catch (\Exception $e) {
             return $app['twig']->render('PT/pages/error.html', array('message' => $e->getMessage()));
         }
     })->assert('route', '.+')->value('route', '');
     return $controllers;
 }
Ejemplo n.º 27
0
 /**
  * @param string $path
  * @param string $name
  * @param string $service
  *
  * @return \Silex\Controller
  */
 protected function getController($path, $name, $service)
 {
     $controller = $this->controllerCollection->match($path, $service)->bind($name);
     return $controller;
 }
Ejemplo n.º 28
0
 public function testNestedCollectionRouteCallbacks()
 {
     $cl1 = new ControllerCollection(new MyRoute1());
     $cl2 = new ControllerCollection(new MyRoute1());
     $c1 = $cl2->match('/c1', function () {
     });
     $cl1->mount('/foo', $cl2);
     $c2 = $cl2->match('/c2', function () {
     });
     $cl1->before('before');
     $c3 = $cl2->match('/c3', function () {
     });
     $cl1->flush();
     $this->assertEquals(array('before'), $c1->getRoute()->getOption('_before_middlewares'));
     $this->assertEquals(array('before'), $c2->getRoute()->getOption('_before_middlewares'));
     $this->assertEquals(array('before'), $c3->getRoute()->getOption('_before_middlewares'));
 }
Ejemplo n.º 29
0
 protected function addRoute(ControllerCollection $ctr, $name, array $config)
 {
     $config = new ArrayCollection($config);
     if (!($path = $config['path'])) {
         return;
     }
     if (!($defaults = $config['defaults'])) {
         return;
     }
     $defaults = new ArrayCollection($defaults);
     if (!($to = $defaults->remove('_controller'))) {
         return;
     }
     $cls = null;
     if (strpos($to, '::') > 0) {
         $parts = explode('::', $to);
         $cls = reset($parts);
     }
     $route = $ctr->match($path, $to);
     $before = $defaults->remove('_before') ?: '::before';
     if (substr($before, 0, 2) === '::' && $cls) {
         $before = array($cls, substr($before, 2));
     }
     $route->before(function (Request $request, Application $app) use($before) {
         if (!is_callable($before)) {
             return null;
         }
         if (is_array($before)) {
             list($class, $method) = $before;
             if (!class_exists($class)) {
                 throw new \InvalidArgumentException(sprintf('Class "%s" does not exist.', $class));
             }
             $before = array(new $class(), $method);
         }
         return call_user_func($before, $request, $app);
     });
     $after = $defaults->remove('_after') ?: '::after';
     if (substr($after, 0, 2) === '::' && $cls) {
         $after = array($cls, substr($after, 2));
     }
     $route->after(function (Request $request, Response $response, Application $app) use($after) {
         if (!is_callable($after)) {
             return null;
         }
         if (is_array($after)) {
             list($class, $method) = $after;
             if (!class_exists($class)) {
                 throw new \InvalidArgumentException(sprintf('Class "%s" does not exist.', $class));
             }
             $after = array(new $class(), $method);
         }
         return call_user_func($after, $request, $response, $app);
     });
     foreach ($defaults as $key => $value) {
         $route->value($key, $value);
     }
     foreach ($config['requirements'] ?: array() as $variable => $regexp) {
         $properRegexp = $this->getProperRegexp($regexp);
         $route->assert($variable, $properRegexp);
     }
     if ($host = $config['host']) {
         $route->setHost($host);
     }
     if ($methods = $config['methods']) {
         $route->setMethods($methods);
     }
     $route->bind($name);
 }
Ejemplo n.º 30
0
 /**
  * {@inheritdoc}
  */
 protected function registerBackendRoutes(ControllerCollection $collection)
 {
     $collection->match('foobar', [$this, 'fooBar']);
 }