示例#1
0
 /**
  * Test that a Route manages the HTTP methods that it supports
  *
  * Case A: Route initially supports no HTTP methods
  * Case B: Route can set its supported HTTP methods
  * Case C: Route can append supported HTTP methods
  * Case D: Route can test if it supports an HTTP method
  * Case E: Route can lazily declare supported HTTP methods with `via`
  */
 public function testHttpMethods()
 {
     //Case A
     $r = new Slim_Route('/foo', function () {
     });
     $this->assertEmpty($r->getHttpMethods());
     //Case B
     $r->setHttpMethods('GET');
     $this->assertEquals(array('GET'), $r->getHttpMethods());
     //Case C
     $r->appendHttpMethods('POST', 'PUT');
     $this->assertEquals(array('GET', 'POST', 'PUT'), $r->getHttpMethods());
     //Case D
     $this->assertTrue($r->supportsHttpMethod('GET'));
     $this->assertFalse($r->supportsHttpMethod('DELETE'));
     //Case E
     $viaResult = $r->via('DELETE');
     $this->assertTrue($viaResult instanceof Slim_Route);
     $this->assertTrue($r->supportsHttpMethod('DELETE'));
 }
示例#2
0
 /**
  * Map a route to a callback function
  * @param   string      $pattern    The URL pattern (ie. "/books/:id")
  * @param   mixed       $callable   Anything that returns TRUE for is_callable()
  * @return  Slim_Route
  */
 public function map($pattern, $callable)
 {
     $route = new Slim_Route($pattern, $callable);
     $route->setRouter($this);
     $this->routes[] = $route;
     return $route;
 }
 /**
  * Set default route conditions for all instances
  * @param   array $defaultConditions
  * @return  void
  */
 public static function setDefaultConditions(array $defaultConditions)
 {
     self::$defaultConditions = $defaultConditions;
 }
 /**
  * Dispatch route
  *
  * This method invokes the route's callable. If middleware is
  * registered for the route, each callable middleware is invoked in
  * the order specified.
  *
  * This method is smart about trailing slashes on the route pattern.
  * If the route's pattern is defined with a trailing slash, and if the
  * current request URI does not have a trailing slash but otherwise
  * matches the route's pattern, a Slim_Exception_RequestSlash
  * will be thrown triggering an HTTP 301 Permanent Redirect to the same
  * URI _with_ a trailing slash. This Exception is caught in the
  * `Slim::call` loop. If the route's pattern is defined without a
  * trailing slash, and if the current request URI does have a trailing
  * slash, the route will not be matched and a 404 Not Found
  * response will be sent if no subsequent matching routes are found.
  *
  * @param   Slim_Route          $route  The route object
  * @return  bool Was route callable invoked successfully?
  * @throws  Slim_Exception_RequestSlash
  */
 public function dispatch(Slim_Route $route)
 {
     if (substr($route->getPattern(), -1) === '/' && substr($this->resourceUri, -1) !== '/') {
         throw new Slim_Exception_RequestSlash();
     }
     //Invoke middleware
     foreach ($route->getMiddleware() as $mw) {
         if (is_callable($mw)) {
             call_user_func($mw);
         }
     }
     //Invoke callable
     if (is_callable($route->getCallable())) {
         call_user_func_array($route->getCallable(), array_values($route->getParams()));
         return true;
     }
     return false;
 }
示例#5
0
 /**
  *
  **/
 public function perform($unconsumed)
 {
     $format = reset(self::$format_guesses);
     if (isset($_SERVER['CONTENT_TYPE'])) {
         foreach (self::$format_guesses as $mime_type => $guessed_format) {
             if ($_SERVER['CONTENT_TYPE'] === $mime_type) {
                 $format = $guessed_format;
             }
         }
     }
     if (preg_match('/\\.(' . implode('|', self::$format_guesses) . ')$/', $unconsumed, $match)) {
         $format = $match[1];
         $unconsumed = substr($unconsumed, 0, -strlen($match[0]));
     }
     // Get id from authorisation (either OAuth or standard)
     try {
         if (OAuth::isSigned()) {
             $user_id = OAuth::verify();
         } elseif (HTTPAuth::isSigned()) {
             $user_id = HTTPAuth::verify();
         } elseif ($GLOBALS['user']->id !== 'nobody') {
             $user_id = $GLOBALS['user']->id;
         }
         if (!$user_id) {
             throw new Exception('Unauthorized', 401);
         }
     } catch (Exception $e) {
         $status = sprintf('HTTP/1.1 %u %s', $e->getCode(), $e->getMessage());
         header($status, true, $e->getCode());
         die($status);
     }
     // Fake user identity
     $user = User::find($user_id);
     $GLOBALS['auth'] = new Seminar_Auth();
     $GLOBALS['auth']->auth = array('uid' => $user->user_id, 'uname' => $user->username, 'perm' => $user->perms);
     $GLOBALS['user'] = new Seminar_User();
     $GLOBALS['user']->fake_user = true;
     $GLOBALS['user']->register_globals = false;
     $GLOBALS['user']->start($user->user_id);
     $GLOBALS['perm'] = new Seminar_Perm();
     $GLOBALS['MAIL_VALIDATE_BOX'] = false;
     setTempLanguage($GLOBALS['user']->id);
     \Slim_Route::setDefaultConditions(array('course_id' => '[0-9a-f]{32}', 'message_id' => '[0-9a-f]{32}', 'range_id' => '[0-9a-f]{32}', 'semester_id' => '[0-9a-f]{32}', 'user_id' => '[0-9a-f]{32}'));
     $template_factory = new Flexi_TemplateFactory($this->dispatcher->plugin->getPluginPath());
     $template = $template_factory->open('app/views/api/' . $format . '.php');
     $router = RestIP\Router::getInstance(null, $template);
     $router->handleErrors();
     if (Studip\ENV === 'development') {
         error_reporting(E_ALL ^ (E_NOTICE | E_WARNING));
     } else {
         error_reporting(0);
     }
     if (Request::option('mode', 'compact') === 'complete') {
         $router->setMode(RestIP\Router::MODE_COMPLETE);
     } else {
         $router->setMode(RestIP\Router::MODE_COMPACT);
     }
     $env = $router->environment();
     $env['PATH_INFO'] = '/' . $unconsumed;
     $router->hook('slim.before.dispatch', function () use($router) {
         $route = reset($router->router()->getMatchedRoutes());
         $pattern = rtrim($route->getPattern(), '?');
         $method = strtolower(reset($route->getHttpMethods()));
         $routes = $router->getRoutes();
         $handler = $routes[$pattern][$method];
         $before = sprintf('%s::before', $handler);
         if (is_callable($before)) {
             call_user_func($before);
         }
     });
     $router->run();
     $router->hook('slim.after.dispatch', function () use($router) {
         $route = reset($router->router()->getMatchedRoutes());
         $pattern = rtrim($route->getPattern(), '?');
         $method = strtolower(reset($route->getHttpMethods()));
         $routes = $router->getRoutes();
         $handler = $routes[$pattern][$method];
         $after = sprintf('%s::after', $handler);
         if (is_callable($after)) {
             call_user_func($after);
         }
     });
     restoreLanguage();
     return new Trails_Response();
 }
示例#6
0
 public function testDispatchWithoutCallable()
 {
     Slim_Environment::mock(array('REQUEST_METHOD' => 'GET', 'REMOTE_ADDR' => '127.0.0.1', 'SCRIPT_NAME' => '', 'PATH_INFO' => '/hello/josh', 'QUERY_STRING' => 'one=1&two=2&three=3', 'SERVER_NAME' => 'slim', 'SERVER_PORT' => 80, 'slim.url_scheme' => 'http', 'slim.input' => '', 'slim.errors' => fopen('php://stderr', 'w'), 'HTTP_HOST' => 'slim'));
     $env = Slim_Environment::getInstance();
     $req = new Slim_Http_Request($env);
     $res = new Slim_Http_Response();
     $router = new Slim_Router($req, $res);
     $route = new Slim_Route('/hello/:name', 'foo');
     $route->setRouter($router);
     $route->matches($req->getResourceUri());
     //<-- Extracts params from resource URI
     $this->assertFalse($route->dispatch());
 }
示例#7
0
    }
    public function genpass()
    {
        $s = "abcdefghijklmnopqrstuvwxyz";
        $str = "";
        for ($i = 0; $i < 8; $i++) {
            $str .= $s[rand(0, 25)];
        }
        return $str;
    }
}
$app = new gesmail(array('debug' => true));
$app->connectdb();
$_SESSION['asso'] = 'simde';
// FIXME noraml ça ?
Slim_Route::setDefaultConditions(array('id' => '-?\\d+'));
$app->get('/(:id)', function ($id = -1) use($app) {
    if (empty($_SESSION['asso'])) {
        header("Location: login.php");
        die;
    } else {
        $asso = $_SESSION['asso'];
    }
    $box = $app->get_box($id);
    $options = array();
    if ($box['type'] == 'alias') {
        $stmt = $app->db->prepare("SELECT 1 FROM postfix_alias WHERE alias LIKE ? AND destination LIKE ?");
        $stmt->bind_param("ss", $box['name'], $_SESSION['asso']);
        $stmt->execute();
        $stmt->store_result();
        if ($stmt->num_rows == 1) {
示例#8
0
 /**
  * Test route sets and gets middleware
  *
  * Pre-conditions:
  * Route instantiated
  *
  * Post-conditions:
  * Case A: Middleware set as callable, not array
  * Case B: Middleware set after other middleware already set
  * Case C: Middleware set as array of callables
  * Case D: Middleware set as a callable array
  * Case E: Middleware is invalid; throws InvalidArgumentException
  */
 public function testRouteMiddleware()
 {
     $callable1 = function () {
     };
     $callable2 = function () {
     };
     //Case A
     $r1 = new Slim_Route('/foo', function () {
     });
     $r1->setMiddleware($callable1);
     $mw = $r1->getMiddleware();
     $this->assertInternalType('array', $mw);
     $this->assertEquals(1, count($mw));
     //Case B
     $r1->setMiddleware($callable2);
     $mw = $r1->getMiddleware();
     $this->assertEquals(2, count($mw));
     //Case C
     $r2 = new Slim_Route('/foo', function () {
     });
     $r2->setMiddleware(array($callable1, $callable2));
     $mw = $r2->getMiddleware();
     $this->assertInternalType('array', $mw);
     $this->assertEquals(2, count($mw));
     //Case D
     $r3 = new Slim_Route('/foo', function () {
     });
     $r3->setMiddleware(array($this, 'callableTestFunction'));
     $mw = $r3->getMiddleware();
     $this->assertInternalType('array', $mw);
     $this->assertEquals(1, count($mw));
     //Case E
     try {
         $r3->setMiddleware('sdjfsoi788');
         $this->fail('Did not catch InvalidArgumentException when setting invalid route middleware');
     } catch (InvalidArgumentException $e) {
     }
 }
示例#9
0
 /**
  * Map a route to a callback function
  *
  * @param   string  $pattern    The URL pattern (ie. "/books/:id")
  * @param   mixed   $callable   Anything that returns TRUE for is_callable()
  * @param   string  $method     The HTTP request method (GET, POST, PUT, DELETE)
  * @return  Route
  */
 public function map($pattern, $callable, $method)
 {
     $route = new Slim_Route($pattern, $callable);
     $route->setRouter($this);
     $methodKey = $method === Slim_Http_Request::METHOD_HEAD ? Slim_Http_Request::METHOD_GET : $method;
     $this->routes[$methodKey][] = $route;
     return $route;
 }
示例#10
0
文件: RouteTest.php 项目: ntdt/Slim
 /**
  * Test route default conditions
  *
  * Pre-conditions:
  * Route class has default conditions;
  *
  * Post-conditions:
  * Case A: Route instance has default conditions;
  * Case B: Route instance has newly merged conditions;
  */
 public function testRouteDefaultConditions() {
     Slim_Route::setDefaultConditions(array('id' => '\d+'));
     $r = new Slim_Route('/foo', function () {});
     //Case A
     $this->assertEquals($r->getConditions(), Slim_Route::getDefaultConditions());
     //Case B
     $r->conditions(array('name' => '[a-z]{2,5}'));
     $c = $r->getConditions();
     $this->assertArrayHasKey('id', $c);
     $this->assertArrayHasKey('name', $c);
 }