/**
  * Call
  *
  * This method finds and iterates all route objects that match the current request URI.
  */
 public function call()
 {
     try {
         if (isset($this->environment['slim.flash'])) {
             $this->view()->setData('flash', $this->environment['slim.flash']);
         }
         $this->applyHook('slim.before');
         ob_start();
         $this->applyHook('slim.before.router');
         $dispatched = false;
         $matchedRoutes = $this->router->getMatchedRoutes($this->request->getMethod(), $this->request->getResourceUri());
         foreach ($matchedRoutes as $route) {
             try {
                 $this->applyHook('slim.before.dispatch');
                 $dispatched = $this->router->dispatch($route);
                 $this->applyHook('slim.after.dispatch');
                 if ($dispatched) {
                     break;
                 }
             } catch (\Slim\Exception\Pass $e) {
                 continue;
             }
         }
         if (!$dispatched) {
             $this->notFound();
         }
         $this->applyHook('slim.after.router');
         $this->stop();
     } catch (\Slim\Exception\Stop $e) {
         $this->response()->write(ob_get_clean());
         $this->applyHook('slim.after');
     } catch (\Exception $e) {
         \Log::log_slim_exception($e);
         // Statamic's error logger
         if ($this->config('debug')) {
             throw $e;
         } else {
             try {
                 $this->error($e);
             } catch (\Slim\Exception\Stop $e) {
                 // Do nothing
             }
         }
     }
 }
 public function testMatchValidRequest()
 {
     $this->router->addRoute(new Route('/foo(/:bar)', 'Home', ['GET', 'POST'], 'home'));
     $this->assertCount(1, $this->slimRouter->getNamedRoutes());
     $result = $this->router->match(new ServerRequest([], [], '/foo/bar', 'POST'));
     $this->assertTrue($result->isSuccess());
 }
Example #3
0
 /**
  * Get the relative URL for a given route name.
  *
  * @param string $route
  * @param array $params
  * @param array $query
  *
  * @return string
  */
 public function uriFor($route, array $params = [], array $query = [])
 {
     if (!$route) {
         return '';
     }
     return $this->router->relativePathFor($route, $params, $query);
 }
 /**
  * Generate a URI from the named route.
  *
  * Takes the named route and any substitutions, and attempts to generate a
  * URI from it.
  *
  * @see https://github.com/auraphp/Aura.Router#generating-a-route-path
  * @see http://framework.zend.com/manual/current/en/modules/zend.mvc.routing.html
  * @param string $name
  * @param array $substitutions
  * @return string
  * @throws Exception\RuntimeException if unable to generate the given URI.
  */
 public function generateUri($name, array $substitutions = [])
 {
     if (!$this->router->hasNamedRoute($name)) {
         throw new Exception\RuntimeException(sprintf('Cannot generate URI based on route "%s"; route not found', $name));
     }
     return $this->router->urlFor($name, $substitutions);
 }
 /**
  * @param \Slim\App $slimInstance
  * @param string|string[] $controllerDirs
  * @param string $cacheDir
  * @throws \Exception
  */
 public function __construct(\Slim\App $slimInstance, $controllerDirs, $cacheDir, RouteParser $parser = null, DataGenerator $generator = null)
 {
     parent::__construct($parser, $generator);
     // We save current Slim instance
     self::$_slimInstance = $slimInstance;
     // We save controller dirs
     if (is_string($controllerDirs)) {
         $controllerDirs = [$controllerDirs];
     }
     if (!is_array($controllerDirs)) {
         throw new \InvalidArgumentException('Controllers directory must be either string or array');
     }
     $this->_controllerDirs = [];
     foreach ($controllerDirs as $d) {
         $realPath = realPath($d);
         if ($realPath !== false) {
             $this->_controllerDirs[] = $realPath;
         }
     }
     // We save the cache dir
     if (!is_dir($cacheDir)) {
         $result = @mkdir($cacheDir, 0777, true);
         if ($result === false) {
             throw new \RuntimeException('Can\'t create cache directory');
         }
     }
     if (!is_writable($cacheDir)) {
         throw new \RuntimeException('Cache directory must be writable by web server');
     }
     $this->_cacheDir = rtrim($cacheDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
     $this->_generateRoutes();
 }
 public function __invoke(ServerRequestInterface $request, ResponseInterface $response)
 {
     $post = $request->getParsedBody();
     $gReCaptcha = empty($post['g-recaptcha-response']) ? null : $post['g-recaptcha-response'];
     $secret = empty($post['secret']) ? null : $post['secret'];
     $author = empty($post['author']) ? 'anonymous' : $post['author'];
     if (empty($post['comment'])) {
         return $response->withStatus(400, 'you have to post something...');
     }
     // validate w/ google
     if (!$this->recaptcha->IsVerified($gReCaptcha)) {
         return $response->withStatus(400, 'You did not pass re-captcha');
     }
     $comment = Comment::factory($author, $post['comment'], $secret);
     $this->entityManager->persist($comment);
     $this->entityManager->flush();
     return $response->withStatus(302, 'comment posted')->withHeader('Location', $this->router->pathFor('home'));
 }
 /**
  *
  * @param Request $request            
  * @param Response $response            
  * @param unknown $args            
  */
 public function resultsdelete(Request $request, Response $response, $args)
 {
     $id = $args['id'];
     $record = R::load(USER, $id);
     if ($record) {
         R::trash($record);
     }
     return $response->withRedirect($this->router->pathFor('results'));
 }
Example #8
0
 /**
  * Call
  *
  * This method finds and iterates all route objects that match the current request URI.
  */
 public function call()
 {
     try {
         if (isset($this->environment['slim.flash'])) {
             $this->view()->setData('flash', $this->environment['slim.flash']);
         }
         $this->applyHook('slim.before');
         ob_start();
         $this->applyHook('slim.before.router');
         $dispatched = false;
         $httpMethodsAllowed = array();
         $this->router->setResourceUri($this->request->getResourceUri());
         $this->router->getMatchedRoutes();
         foreach ($this->router as $route) {
             if ($route->supportsHttpMethod($this->environment['REQUEST_METHOD'])) {
                 try {
                     $this->applyHook('slim.before.dispatch');
                     $dispatched = $this->router->dispatch($route);
                     $this->applyHook('slim.after.dispatch');
                     if ($dispatched) {
                         break;
                     }
                 } catch (\Slim\Exception\Pass $e) {
                     continue;
                 }
             } else {
                 $httpMethodsAllowed = array_merge($httpMethodsAllowed, $route->getHttpMethods());
             }
         }
         if (!$dispatched) {
             if ($httpMethodsAllowed) {
                 $this->response['Allow'] = implode(' ', $httpMethodsAllowed);
                 $this->halt(405, 'HTTP method not allowed for the requested resource. Use one of these instead: ' . implode(', ', $httpMethodsAllowed));
             } else {
                 $this->notFound();
             }
         }
         $this->applyHook('slim.after.router');
         $this->stop();
     } catch (\Slim\Exception\Stop $e) {
         $this->response()->write(ob_get_clean());
         $this->applyHook('slim.after');
     } catch (\Slim\Exception\RequestSlash $e) {
         $this->response->redirect($this->request->getPath() . '/', 301);
     } catch (\Exception $e) {
         if ($this->config('debug')) {
             throw $e;
         } else {
             try {
                 $this->error($e);
             } catch (\Slim\Exception\Stop $e) {
                 // Do nothing
             }
         }
     }
 }
 public function testSetDispatcher()
 {
     $this->router->setDispatcher(\FastRoute\simpleDispatcher(function ($r) {
         $r->addRoute('GET', '/', function () {
         });
     }));
     $class = new \ReflectionClass($this->router);
     $prop = $class->getProperty('dispatcher');
     $prop->setAccessible(true);
     $this->assertInstanceOf('\\FastRoute\\Dispatcher', $prop->getValue($this->router));
 }
Example #10
0
 /**
  * @expectedException \RuntimeException
  */
 public function testPathForRouteNotExists()
 {
     $methods = ['GET'];
     $pattern = '/hello/{first}/{last}';
     $callable = function ($request, $response, $args) {
         echo sprintf('Hello %s %s', $args['first'], $args['last']);
     };
     $route = $this->router->map($methods, $pattern, $callable);
     $route->setName('foo');
     $this->router->pathFor('bar', ['first' => 'josh', 'last' => 'lockhart']);
 }
 /**
  * {@inheritDoc}
  */
 public function collect()
 {
     $routeInfo = $this->router->dispatch($this->request);
     $route = isset($routeInfo[1]) ? $this->router->lookupRoute($routeInfo[1]) : null;
     return $route ? $this->getRouteInformation($route) : null;
 }
Example #12
0
 /**
  * Constructor
  *
  * @param \Spore\Spore $app
  */
 public function __construct(Spore $app)
 {
     parent::__construct();
     $this->app = $app;
 }
 /**
  * Create new router
  * 
  * @param RouteParser $parser
  * @param AclInterface $acl
  */
 public function __construct(RouteParser $parser = null, &$acl = null)
 {
     $this->acl =& $acl;
     parent::__construct($parser);
 }
 public function results(Request $request, Response $response, $args)
 {
     return $response->withRedirect($this->router->pathFor('results'));
 }
 /**
  * @param string $routeName
  * @param array $arguments
  * @return string
  */
 public function urlFor($routeName, array $arguments = [])
 {
     return sprintf('%s%s', $this->request->getRootUri(), $this->router->urlFor($routeName, $arguments));
 }
Example #16
0
 /**
  * {@inheritdoc}
  *
  * This method override just fixes the wrong return type "self" instead of "$this"
  *
  * @return $this
  */
 public function setCacheFile($cacheFile)
 {
     parent::setCacheFile($cacheFile);
     return $this;
 }
Example #17
0
 /**
  * This function registers the default services that Slim needs to work.
  *
  * All services are shared - that is, they are registered such that the
  * same instance is returned on subsequent calls.
  *
  * @param array $userSettings Associative array of application settings
  *
  * @return void
  */
 private function registerDefaultServices($userSettings)
 {
     $defaultSettings = $this->defaultSettings;
     /**
      * This service MUST return an array or an
      * instance of \ArrayAccess.
      *
      * @param Container $c
      *
      * @return array|\ArrayAccess
      */
     $this['settings'] = function ($c) use($userSettings, $defaultSettings) {
         return array_merge($defaultSettings, $userSettings);
     };
     /**
      * This service MUST return a shared instance
      * of \Slim\Interfaces\Http\EnvironmentInterface.
      *
      * @param Container $c
      *
      * @return EnvironmentInterface
      */
     if (!isset($this['environment'])) {
         $this['environment'] = function ($c) {
             return new Environment($_SERVER);
         };
     }
     /**
      * PSR-7 Request object
      *
      * @param Container $c
      *
      * @return ServerRequestInterface
      */
     if (!isset($this['request'])) {
         $this['request'] = function ($c) {
             return Request::createFromEnvironment($c['environment']);
         };
     }
     /**
      * PSR-7 Response object
      *
      * @param Container $c
      *
      * @return ResponseInterface
      */
     if (!isset($this['response'])) {
         $this['response'] = function ($c) {
             $headers = new Headers(['Content-Type' => 'text/html']);
             $response = new Response(200, $headers);
             return $response->withProtocolVersion($c['settings']['httpVersion']);
         };
     }
     /**
      * This service MUST return a SHARED instance
      * of \Slim\Interfaces\RouterInterface.
      *
      * @param Container $c
      *
      * @return RouterInterface
      */
     if (!isset($this['router'])) {
         $this['router'] = function ($c) {
             $router = new Router();
             $uri = $c['request']->getUri();
             if (is_callable([$uri, 'getBasePath'])) {
                 $router->setBasePath($uri->getBasePath());
             }
             return $router;
         };
     }
     /**
      * This service MUST return a SHARED instance
      * of \Slim\Interfaces\InvocationStrategyInterface.
      *
      * @param Container $c
      *
      * @return InvocationStrategyInterface
      */
     if (!isset($this['foundHandler'])) {
         $this['foundHandler'] = function ($c) {
             return new RequestResponse();
         };
     }
     /**
      * This service MUST return a callable
      * that accepts three arguments:
      *
      * 1. Instance of \Psr\Http\Message\ServerRequestInterface
      * 2. Instance of \Psr\Http\Message\ResponseInterface
      * 3. Instance of \Exception
      *
      * The callable MUST return an instance of
      * \Psr\Http\Message\ResponseInterface.
      *
      * @param Container $c
      *
      * @return callable
      */
     if (!isset($this['errorHandler'])) {
         $this['errorHandler'] = function ($c) {
             return new Error();
         };
     }
     /**
      * This service MUST return a callable
      * that accepts two arguments:
      *
      * 1. Instance of \Psr\Http\Message\ServerRequestInterface
      * 2. Instance of \Psr\Http\Message\ResponseInterface
      *
      * The callable MUST return an instance of
      * \Psr\Http\Message\ResponseInterface.
      *
      * @param Container $c
      *
      * @return callable
      */
     if (!isset($this['notFoundHandler'])) {
         $this['notFoundHandler'] = function ($c) {
             return new NotFound();
         };
     }
     /**
      * This service MUST return a callable
      * that accepts three arguments:
      *
      * 1. Instance of \Psr\Http\Message\ServerRequestInterface
      * 2. Instance of \Psr\Http\Message\ResponseInterface
      * 3. Array of allowed HTTP methods
      *
      * The callable MUST return an instance of
      * \Psr\Http\Message\ResponseInterface.
      *
      * @param Container $c
      *
      * @return callable
      */
     if (!isset($this['notAllowedHandler'])) {
         $this['notAllowedHandler'] = function ($c) {
             return new NotAllowed();
         };
     }
     /**
      * Instance of \Slim\Interfaces\CallableResolverInterface
      *
      * @param Container $c
      *
      * @return CallableResolverInterface
      */
     if (!isset($this['callableResolver'])) {
         $this['callableResolver'] = function ($c) {
             return new CallableResolver($c);
         };
     }
 }
 /**
  * @expectedException \InvalidArgumentException
  */
 public function testSettingInvalidBasePath()
 {
     $this->router->setBasePath(['invalid']);
 }
Example #19
0
 public function getMatchedRoutes($httpMethod, $resourceUri, $reload = false)
 {
     // Force a reload of all matched routes
     return parent::getMatchedRoutes($httpMethod, $resourceUri, true);
 }