public function test_when_with_a_callable_class_within_a_route() { $router = new Router(); $routine = new WhenAlwaysTrue(); $router->get('/', function () { return 'route'; })->by($routine); // By does not affect the output of the route. $this->assertEquals($expected = 'route', (string) $router->dispatch('GET', '/')); $this->assertAttributeEquals($expected = true, 'invoked', $routine, 'Routine was not invoked!'); }
/** * @covers Respect\Rest\Routes\Error::getReflection * @covers Respect\Rest\Routes\Error::runTarget * @covers Respect\Rest\Router::errorRoute */ public function testMagicConstuctorCanCreateRoutesToErrors() { $router = new Router(); $called = false; $phpUnit = $this; $router->errorRoute(function ($err) use(&$called, $phpUnit) { $called = true; $phpUnit->assertContains('Oops', $err[0], 'The error message should be available in the error route'); return 'There has been an error.'; }); $router->get('/', function () { trigger_error('Oops', E_USER_WARNING); }); $response = (string) $router->dispatch('GET', '/')->response(); $this->assertTrue($called, 'The error route must have been called'); $this->assertEquals('There has been an error.', $response, 'An error should be caught by the router and forwarded'); }
/** * @covers Respect\Rest\Routes\Exception::getReflection * @covers Respect\Rest\Routes\Exception::runTarget * @covers Respect\Rest\Router::exceptionRoute */ public function testMagicConstuctorCanCreateRoutesToExceptions() { $router = new Router(); $called = false; $phpUnit = $this; $router->exceptionRoute('RuntimeException', function ($e) use(&$called, $phpUnit) { $called = true; $phpUnit->assertEquals('Oops', $e->getMessage(), 'The exception message should be available in the exception route'); return 'There has been a runtime error.'; }); $router->get('/', function () { throw new \RuntimeException('Oops'); }); $response = (string) $router->dispatch('GET', '/')->response(); $this->assertTrue($called, 'The exception route must have been called'); $this->assertEquals('There has been a runtime error.', $response, 'An exception should be caught by the router and forwarded'); }
/** * @covers Respect\Rest\Routes\AbstractRoute::match * @dataProvider extensions_provider */ public function testIgnoreFileExtensions($with, $without) { $_SERVER['HTTP_ACCEPT'] = '*'; $_SERVER['REQUEST_URI'] = '/'; $r = new Router(); $r->get('/route1/*', function ($match) { return $match; }); $r->get('/route2/*', function ($match) { return $match; })->accept(array('.json-home' => function ($data) { return factory::respond(E2M::mediaType('.json-home'), $data); }, "*" => function ($data) { return "{$data}.accepted"; })); $response = $r->dispatch('get', "/route1/{$with}")->response(); $this->assertEquals($with, $response); $response = $r->dispatch('get', "/route2/{$with}")->response(); $this->assertEquals("{$without}.accepted", $response); }
function bootstrap(RespectMapper $mapper, RespectRouter $router, RespectContainer $config) { Model\Model::setConn($mapper); $router->any('/**', 'Application\\Helper\\Mvc\\Router'); /** * Seta o retorno de todas as rotas como resposta em JSON; */ $rotas[''] = $router->always('Accept', array('application/json' => function ($data) { header('Content-type: application/json'); if (v::string()->validate($data)) { $data = array($data); } return json_encode($data, true); })); /** * Rota caso ocorra algum erro */ $router->errorRoute(function ($e) { var_dump($e); }); /** * Rota caso ocorra alguma excessão */ $router->exceptionRoute(function ($e) { var_dump($e); }); /** * Rotas Configuradas pelo config.ini */ if (empty($config->routes)) { return; } foreach ($config->routes as $route) { $url = $route->url; $class_controller = $route->controller; $params = isset($route->params) ? $route->params : array(); $router->get($url, $class_controller, $params); } }
<?php require 'vendor/autoload.php'; include 'vendor/notorm/notorm/NotORM.php'; $dsn = 'sqlite:' . realpath('./data/db.sqlite'); $db = new NotORM(new PDO($dsn)); use Respect\Rest\Router; $r3 = new Router(); $r3->get('/', function () { echo '<h1>Hello Respect World</h1>'; }); $r3->get('/hello', function () { return 'Hello from Path'; }); $r3->get('/users/*', function ($screenName) { echo "User {$screenName}"; }); $r3->get('/users/*/lists/*', function ($user, $list) { return "List {$list} from user {$user}."; }); $r3->get('/posts/*/*/*', function ($year, $month = null, $day = null) { //list posts, month and day are optional }); $r3->get('/books', function () use($db) { $books = array(); foreach ($db->books() as $book) { $books[] = array('id' => $book['id'], 'title' => $book['title'], 'author' => $book['author'], 'summary' => $book['summary']); } return $books; })->accept(array('application/json' => 'json_encode')); $r3->get('/book/*', function ($id) use($db) {
/** * Redefine run taking into account mountend end points */ public function run(Request $request = null) { $endPointName = $this->getEndPointName(); $applicationPath = $this->getEndPointPath(); $routerClass = $endPointName && isset($this->endPointCatalog[$endPointName]) ? $this->endPointCatalog[$endPointName] : ''; $virtualhost = empty($endPointName) ? $applicationPath : $applicationPath . '/' . $endPointName; if (!$routerClass) { $result = parent::run($request); //fall back to local application routing } else { // now we test that $routerclass is a valid end_point $myClass = get_class(); if ($routerClass == $myClass || is_subclass_of($routerClass, $myClass)) { // Create new end-point $endpoint = new $routerClass($virtualhost); $result = $endpoint->run(); } else { throw new HttpErrorException(HttpProblem::factory(500, 'Invalid endpoint', $routerClass . ' end point class is not a subClass of ' . $myClass)); } } //now prepare an error report for humans when something went wrong //Warning this trigger is called only in php >5.4. Otherwhise just empty content is printed //(but original status is preserved) if (empty($result) && ($errorCode = Http::getHttpResponseCode()) >= 400) { $result = ErrorManager::getInstance()->serializeHttpProblem(new HttpProblem($errorCode)); } return $result; }
/** * @covers Respect\Rest\Router::handleOptionsRequest * @runInSeparateProcess */ public function testOptionsRequestShouldBeDispatchedToCorrectOptionsHandler() { // arrange $router = new Router(); $router->get('/asian', 'GET: Asian Food!'); $router->options('/asian', 'OPTIONS: Asian Food!'); $router->post('/asian', 'POST: Asian Food!'); // act $response = (string) $router->dispatch('OPTIONS', '/asian')->response(); // assert $this->assertContains('Allow: GET, OPTIONS, POST', xdebug_get_headers(), 'There should be a sent Allow header with all methods for the handler that match this request.'); $this->assertEquals('OPTIONS: Asian Food!', $response, 'OPTIONS request should call the correct custom OPTIONS handler.'); }
public function postLoguot(Router $r) { $r->post("/ajax/ControleUsuario/logout", function () { $sessao = Container::getSession(); $sessao->unsetKey("usuario"); echo "Loged out"; }); }
/** Sorts current routes according to path and parameters */ protected function sortRoutesByComplexity() { usort($this->routes, function ($a, $b) { $a = $a->pattern; $b = $b->pattern; $pi = AbstractRoute::PARAM_IDENTIFIER; //Compare similarity and ocurrences of "/" if (Router::compareRoutePatterns($a, $b, '/')) { return 1; //Compare similarity and ocurrences of /* } elseif (Router::compareRoutePatterns($a, $b, $pi)) { return -1; //Hard fallback for consistency } else { return 1; } }); }
public function getValidarUsuario(Router $r) { $r->get("/ControleUsuario/validar/*/*/*", function ($email, $fullname, $nick) { }); }
<?php require "database.php"; error_reporting(E_ALL); ini_set('display_errors', 'on'); set_time_limit(0); use Respect\Rest\Router; $router = new Router(); $router->get('/', function () { require "views/default.php"; }); $router->any('/devs/*', '\\Beeblebrox3\\DevShop\\Controllers\\Devs'); $router->any('/cart', '\\Beeblebrox3\\DevShop\\Controllers\\Cart'); $router->post('/cart/apply-cupom', function () { $controller = new \Beeblebrox3\DevShop\Controllers\Cart(); $controller->applyCupom(); }); $router->post('/cart/buy/', function () { $controller = new Beeblebrox3\DevShop\Controllers\Cart(); $controller->buy(); }); $router->delete('/cart/*', '\\Beeblebrox3\\DevShop\\Controllers\\Cart'); $router->post('/config', function () { $controller = new Beeblebrox3\DevShop\Controllers\Config(); $controller->import(); }); $router->exceptionRoute('InvalidArgumentException', function (InvalidArgumentException $e) { return 'Sorry, this error happened: ' . $e->getMessage(); }); $router->errorRoute(function ($a = null) { print_r($a);
<?php require_once '../tests/bootstrap.php'; use Respect\Rest\Router; $r3 = new Router(); $r3->any('/**', function ($url) { return 'Welcome to Respect/Rest the url you want is: /' . implode('/', $url); });
/** * @covers Respect\Rest\Router::applyVirtualHost * @covers Respect\Rest\Router::appendRoute */ public function testCreateUriShouldBeAwareOfVirtualHost() { $router = new Router('/my/virtual/host'); $catsRoute = $router->any('/cats/*', 'Meow'); $virtualHostUri = $catsRoute->createUri('mittens'); $this->assertEquals('/my/virtual/host/cats/mittens', $virtualHostUri, 'Virtual host should be prepended to the path on createUri()'); }
<?php define('DS', DIRECTORY_SEPARATOR); define('APP_ROOT', __DIR__ . DS . '..'); use Respect\Config\Container; use Respect\Rest\Router; chdir(APP_ROOT); $composer_autoload = APP_ROOT . DS . 'vendor' . DS . 'autoload.php'; if (false === is_file($composer_autoload)) { throw new \Exception('Por favor, instale as dependências do Composer'); } require $composer_autoload; $config = new Container(APP_ROOT . DS . 'config' . DS . 'app.ini'); $app = $config->application; ini_set('display_errors', $app->display_errors); error_reporting($app->error_reporting); date_default_timezone_set($app->timezone); setlocale(LC_ALL, 'pt_BR'); define('APP_NAME', $app->app_name); $r = new Router(); $r->get('/', 'Wadmin\\Routes\\GenericRoute'); $r->get('/*', 'Wadmin\\Routes\\GenericRoute'); $r->always('Accept', array('text/html' => new Common\Routine\Twig($app->twig)));
<?php // error_reporting(0); use Respect\Rest\Router; use Icecave\SemVer\Version; $packageRoot = dirname(__DIR__); $matches = array(); if (preg_match('{^(.*)/vendor/.+/.+$}', $packageRoot, $matches)) { require $matches[1] . '/vendor/autoload.php'; } else { require $packageRoot . '/vendor/autoload.php'; } if (basename($_SERVER['SCRIPT_NAME']) == basename($_SERVER['SCRIPT_FILENAME']) and ($basedir = dirname($_SERVER['SCRIPT_NAME'])) != "/") { $router = new Router($basedir); } else { $router = new Router(); } // $router->exceptionRoute('InvalidArgumentException', function (InvalidArgumentException $e) { // return '[InvalidArgumentException] Sorry, this error happened: '.$e->getMessage(); // }); $router->exceptionRoute('\\Exception', function (Exception $e) { return '[Exception] Sorry, this error happened: ' . $e->getMessage(); }); $router->get('/js/**', function ($jsPath) { return readfile(__DIR__ . '/js/' . $jsPath[0]); }); $router->any('/**', 'Koshatul\\HAProxyWeb\\HTML\\v1_0_0\\Stats');
<?php date_default_timezone_set('America/Bahia'); require __DIR__ . '/../vendor/autoload.php'; use Monolog\Logger; use Monolog\Handler\StreamHandler; use Respect\Rest\Router; // create a log channel $log = new Logger('name'); $log->pushHandler(new StreamHandler('names.log')); $loader = new Twig_Loader_Filesystem(__DIR__ . '/../templates'); $twig = new Twig_Environment($loader); $r = new Router(); $r->get('/hello/*', function ($meuNome) use($log, $twig) { // add records to the log $log->addInfo('Acessou /hello/' . $meuNome); return $twig->render('hello.twig', array('name' => $meuNome)); });
/** * @covers Respect\Rest\Router::always * #64 */ public function test_always_can_take_multiple_parameters_for_routine_constructor() { $this->assertEmpty(DummyRoutine::$result); $r3 = new \Respect\Rest\Router(); $r3->always('dummyRoutine', 'arg1', 'arg2', 'arg3'); $this->assertEquals('arg1, arg2, arg3', DummyRoutine::$result); }