示例#1
1
文件: Hive.php 项目: 100hz/hive
 /**
  * The most important method.
  * Will start the hive engine and listening for requests.
  *
  * @param Request $request
  * @param AbstractResponse $response
  * @param boolean $sendResponse
  *
  * @return void
  */
 public function api($request = null, $response = null, $sendResponse = true)
 {
     $this->klein->respond('POST', '/authenticate', $this->authenticate);
     $this->klein->onHttpError($this->handleError);
     // see https://github.com/klein/klein.php/wiki/Sub-Directory-Installation
     if ($request === null) {
         $request = Request::createFromGlobals();
     }
     // Grab the server-passed "REQUEST_URI"
     $uri = $request->server()->get('REQUEST_URI');
     // Set the request URI to a modified one (without the "subdirectory") in it
     $request->server()->set('REQUEST_URI', '/' . substr($uri, strlen($this->configuration['basePath'])));
     // Pass our request to our dispatch method
     $this->klein->dispatch($request, $response, $sendResponse);
 }
示例#2
1
文件: Router.php 项目: allyse/allyse
 /**
  * @param Klein $klein
  */
 public function create(Klein $klein)
 {
     $klein->respond(function ($request, $response, $service, $app) use($klein) {
         $app->register('call', function () use($request, $response, $service, $app) {
             return new Call($request, $response, $service, $app);
         });
         $app->register('util', function () use($request, $response, $service, $app) {
             return new Util($request, $response, $service, $app);
         });
         $klein->onHttpError(function ($code) use($app) {
             if ($code >= 400 && $code < 500) {
                 require ERROR_404_PAGE;
             } else {
                 require ERROR_500_PAGE;
             }
         });
     });
 }
示例#3
1
 /**
  * @param Klein $klein
  */
 public function create(Klein $klein)
 {
     $klein->respond('GET', '/', function ($request, $response, $service, $app) use($klein) {
         $app->call->IndexController()->index();
     });
 }
示例#4
1
<?php

use ComposerProxy\Server\Server;
use Klein\Klein;
use Klein\Request;
define('APP_ROOT', realpath(__DIR__ . '/../'));
require_once APP_ROOT . '/vendor/autoload.php';
$klein = new Klein();
$klein->respond('POST', '/packages', function (Request $request) {
    $server = new Server();
    return $server->serve($request->paramsPost()->all());
});
$klein->dispatch();
示例#5
1
 public function dispatch()
 {
     $params = $this->parameters;
     // ---- services ----
     $this->routing->respond(function ($request, $response, $service, $app) use($params) {
         // set this site's title
         $app->title = 'Lunchsite';
         // add a custom validator (all amounts need to be positive floats)
         $service->addValidator('positiveFloat', function ($str) {
             return preg_match('/^([0-9]+)([\\.0-9]+)?$/', $str);
         });
         // -- Lazy stored database
         $app->register('connection', function () use($params) {
             $db_address = join(';', array('host=' . $params['db_host'], 'port=' . $params['db_port'], 'dbname=' . $params['db_name']));
             $db = new ezSQL_pdo('mysql:' . $db_address, $params['db_user'], $params['db_pass']);
             /*
             // Cache expiry
             $db->cache_timeout = 1; // in hours
             
             // Specify a cache dir. Path is taken from calling script
             $db->cache_dir = 'ezsql_cache';
             
             // (1. You must create this dir. first!)
             // (2. Might need to do chmod 775)
             
             // Global override setting to turn disc caching off
             // (but not on)
             $db->use_disk_cache = true;
             
             // By wrapping up queries you can ensure that the default
             // is NOT to cache unless specified
             $db->cache_queries = true;
             */
             return $db;
         });
         // -- Lazy load the repositories (not all are needed for every single request)
         $app->register('transactionController', function () {
             return new TransactionController();
         });
         // -- Lazy load the repositories (not all are needed for every single request)
         $app->register('accountRepository', function () use($app) {
             return new AccountRepository($app->connection);
         });
         $app->register('dashboardRepository', function () use($app) {
             return new DashboardRepository($app->connection);
         });
         $app->register('transactionRepository', function () use($app) {
             return new TransactionRepository($app->connection);
         });
         // -- Lazy stored initialized twig engine
         $app->register('twig', function () use($params) {
             $useCache = $params['twig_use_cache'];
             $paths = $this->getFolders($params['paths']['twig']);
             $loader = new Twig_Loader_Filesystem($paths);
             $twig = new Twig_Environment($loader, array('cache' => $useCache ? $params['paths']['cache'] : false));
             TwigExtensions::addExtensions($twig);
             return $twig;
         });
     });
     // ---- root ----
     $this->routing->respond('GET', '/?', function ($request, $response, $service, $app) {
         $data = array('app' => $app, 'testData' => $app->dashboardRepository->getUserTotals2(), 'userData' => $app->dashboardRepository->getUserTotals(), 'totalCash' => $app->dashboardRepository->getTotalCash(), 'totalBank' => $app->dashboardRepository->getTotalBank(), 'lunchAccount' => $app->accountRepository->getLunchpotAccount(), 'accounts' => $app->accountRepository->getAccounts(), 'transactions' => $app->transactionRepository->findAll(true), 'transactionTypes' => $app->transactionRepository->getTransactionTypes());
         return $app->twig->render('dashboard.html.twig', $data);
     });
     $this->routing->respond('GET', '/ng/?', function ($request, $response, $service, $app) {
         $response->file('/ng/index.html');
     });
     /*$this->routing->respond('GET', '/ng/.+', function ($request, $response, $service, $app) {
     			return $response->file(__DIR__ . $request->pathname());
     		});*/
     // ---- transaction ----
     /*foreach(array('TransactionController') as $controller) {
     			$controller = preg_replace('/^(.+)Controller$/', '$1', $controller);
     			// Include all routes defined in a file under a given namespace
     			$klein->with("/$controller", "controller/$controller.php");
     		}*/
     $this->routing->respond('POST', '/transaction/[create|read|update|delete:action]', function ($request, $response, $service, $app) {
         return $app->transactionController->{$request->action . 'Action'}($request, $response, $service, $app);
     });
     // ---- account ----
     $this->routing->respond('GET', '/account/[i:id]', function ($request, $response, $service, $app) {
         $data = array('account' => $app->accountRepository->getAccountById($request->id));
         return $app->twig->render('account.html.twig', $data);
     });
     // -- Handle errors
     $this->routing->onHttpError(function ($code, $router) {
         $app = $router->app();
         switch ($code) {
             case 400:
                 $response = $app->twig->render('400-bad-request.html.twig');
                 $router->response()->body($response);
                 break;
             case 403:
                 $response = $app->twig->render('403-forbidden.html.twig');
                 $router->response()->body($response);
                 break;
             case 404:
                 $response = $app->twig->render('404-not-found.html.twig');
                 $router->response()->body($response);
                 break;
             case 405:
                 $router->response()->json(array('code' => $code, 'status' => 'Method Not Allowed'));
                 break;
             default:
                 $router->response()->body('Oh no, a bad error happened that caused a ' . $code);
         }
     });
     $this->routing->dispatch();
 }
示例#6
0
 /**
  * Set the routes
  *
  * @param array $routes Array of routes configurations
  *
  * @throws \Exception
  */
 public function configureRoutes($routes)
 {
     $routeCollection = new RouteCollection();
     foreach ($routes as $route) {
         if ($this->debug) {
             Log::write('Configuring route "' . $route['path'] . '"');
         }
         $routeObject = $this->router->respond($route['httpMethod'], $route['path'], $route['callback']);
         $routeObject->setName($route['name']);
         $routeCollection->set($route['name'], $routeObject);
     }
     $this->router = new Klein($this->router->service(), $this->router->app(), $routeCollection);
     if ($this->debug) {
         // Add a catchall debugging route
         Log::write('Configuring catchall route');
         $this->router->respond('*', function (Request $request, Response $response) {
             Log::write(' ==> URI called : "' . $request->uri() . '" / User Agent : "' . $request->userAgent() . '"');
             Log::write(' <== Response code : ' . $response->code());
         });
     }
 }
示例#7
0
文件: Router.php 项目: jh222xk/pophub
 public function doRoute()
 {
     $klein = new Klein();
     $this->config = new Config("../app/config/app.php");
     $klein->respond("GET", $this->homePath, function () {
         $controller = new Home(new View\Home());
         $controller->index();
     });
     $klein->respond("GET", $this->loginPath . "?", function ($request, $response) {
         $url = $this->auth->index();
         $response->redirect($url);
     });
     $klein->respond("GET", "/github-callback/?", function ($request, $response) {
         if ($request->code) {
             $this->auth->getToken($request->code);
             return $response->redirect($this->userPath);
         }
         return $response->redirect($this->homePath);
     });
     $klein->respond("GET", $this->userPath . "?", function ($request, $response) {
         $session = new Session();
         $token = $session->get($this->auth->getTokenSessionName());
         if ($token) {
             return $this->auth->loggedInUser($token);
         }
         return $response->redirect($this->homePath);
     });
     $klein->respond("GET", $this->logoutPath . "?", function ($request, $response) {
         $session = new Session();
         $session->destroy($this->auth->getTokenSessionName());
         return $response->redirect($this->homePath);
     });
     $klein->with($this->usersPath, function () use($klein) {
         $klein->respond("GET", "/?", function ($request, $response) {
             $controller = new Users();
             $controller->index($request->fetchFromID);
         });
         $klein->respond("GET", "/[:username]/?", function ($request, $response) {
             $controller = new Users();
             $controller->show($request->username);
         });
     });
     $klein->respond("GET", $this->searchPath . "?", function ($request, $response) {
         $controller = new Users();
         $controller->search();
     });
     $klein->respond("GET", $this->followPath . "[:username]/?", function ($request, $response) {
         $controller = new Users();
         $controller->follow($request->username);
     });
     $klein->respond("GET", $this->unFollowPath . "[:username]/?", function ($request, $response) {
         $controller = new Users();
         $controller->unFollow($request->username);
     });
     $klein->respond("404", function ($request) {
         $page = $request->uri();
         $controller = new Error(new View\Error());
         $controller->pageNotFoundError($page);
     });
     $klein->onError(function ($klein, $err_msg) {
         if ($this->config->get("DEBUG") === true) {
             throw new \Exception($err_msg);
         } else {
             $controller = new Error(new View\Error());
             $controller->serverError();
             error_log($err_msg, 3, $this->config->get("ERROR_LOG"));
         }
     });
     $klein->dispatch();
 }
示例#8
0
<?php

// Require composer autoloader
require __DIR__ . '/vendor/autoload.php';
use Klein\Klein;
use Klein\Request;
use Klein\Response;
use Stringy\Stringy as S;
$klein = new Klein();
$klein->respond('POST', '/reverse', function (Request $req, Response $res) {
    $res->json(['result' => (new S($req->param('data', '')))->reverse()]);
});
$klein->respond('POST', '/swapcase', function (Request $req, Response $res) {
    $res->json(['result' => (new S($req->param('data', '')))->swapCase()]);
});
$klein->respond('POST', '/titleize', function (Request $req, Response $res) {
    $res->json(['result' => (new S($req->param('data', '')))->titleize()]);
});
示例#9
0
namespace ksv\trouble;

date_default_timezone_set('America/Sao_Paulo');
require_once __DIR__ . '/../vendor/autoload.php';
require 'Base.php';
require 'User.php';
require 'Config.php';
require 'Db.php';
require 'TemplateEngine.php';
use Klein\Klein;
error_reporting(getenv('ENV') === 'production' ? 0 : E_ALL);
$router = new Klein();
$router->respond(function ($req, $res, $svc, $app) {
    $app->register('config', function () {
        return new Config();
    });
    $app->register('db', function () use($app) {
        return new Db($app);
    });
    $app->register('user', function () use($app) {
        return new User($app);
    });
    $app->register('template', function () use($app) {
        return new TemplateEngine($app);
    });
});
foreach (require 'routes.php' as $route) {
    $router->respond($route->path, $route->method, $route->handler);
}
$router->dispatch();
示例#10
0
$klein->respond(["GET", "POST"], "/?[:controller]?/[**:trail]?", function (Request $request, Response $response, ServiceProvider $service, App $app) use($klein) {
    $controller = ucfirst(strtolower($request->param('controller', 'home')));
    $trailRaw = $request->param('trail', []);
    $trail = explode('/', $trailRaw);
    if ($controller == "Static") {
        $name = end($trail);
        $ext = end(explode(".", $name));
        $mime = "text/plain";
        switch ($ext) {
            case "css":
                $mime = "text/css";
                break;
            case "js":
                $mime = "text/javascript";
                break;
            case "jpg":
                $mime = "image/jpeg";
                break;
            case "png":
                $mime = "image/png";
                break;
        }
        $response->file(realpath("./src/Checklist/Views/Static/" . $trailRaw), $name, $mime);
        return;
    }
    $controller = str_replace('Home', ucfirst(strtolower($request->param('controller', 'home'))), HomeController::class);
    if (count($trail) > 0) {
        $action = array_shift($trail);
    } else {
        $action = "index";
    }
    $body = call_user_func_array([new $controller($response, $app, $service), $action], $trail);
    $response->body($body);
});
示例#11
0
 * Environment variables
 */
$app['config.storage'] = $config['DBFile'];
$app['twig'] = $twig;
/*
 * Build services and provide them from the Container
 */
$app['service.storage'] = function () use($app) {
    $service = new StorageService();
    $service->setStorageName($app['config.storage']);
    return $service;
};
$app['controller.data'] = function () use($app) {
    $controller = new DataController();
    $controller->setApp($app);
    $controller->setStorageService($app['service.storage']);
    return $controller;
};
/*
 * Build routes
 */
$router->respond('POST', '/update', function () use($app) {
    return $app['controller.data']->saveData($_POST['people']);
});
$router->respond('GET', '/show/[:id]', function ($request) use($app) {
    return $app['controller.data']->showAction($request->id);
});
//in addition always display the following route:
$router->respond(function () use($app) {
    return $app['controller.data']->index();
});
示例#12
0
$modules = array();
$module_root = __DIR__ . '/modules/';
$module_files = utilities::glob_recursive($module_root . "*.php", GLOB_NOSORT);
foreach ($module_files as $mfile) {
    $modules[] = (include $mfile);
}
foreach ($modules as $mj) {
    if (utilities::module_valid($mj)) {
        $app->respond($mj['methods'], $mj['route'], function (\Klein\Request $request, \Klein\Response $response) use($mj) {
            /* TODO: check callback access */
            $answer = $mj['callback']($mj, $request, $response);
            if ($mj['response_type'] === "object") {
                $response_json = array("result" => array("code" => $answer['code'], "object" => $answer['object']), "data" => $answer['data']);
                return $response->json($response_json);
            } else {
                if ($mj['response_type'] === "array") {
                    $response_json = array("result" => array("code" => $answer['code'], "object" => $answer['object']), "pagination" => array("window" => $answer['window'], "current" => $answer['current'], "next" => $answer['next'], "total" => $answer['total'], "pages" => $answer['pages']), "data" => $answer['data']);
                    return $response->json($response_json);
                } else {
                    if ($mj['response_type'] == "file") {
                    }
                }
            }
        });
    } else {
    }
}
$app->onError(function (\Klein\Klein $app, $message, $type, jsonui_exception $ex) {
    /** TODO: save report */
    return $app->response()->json(array("result" => array("code" => $ex->getCode(), "message" => $ex->getMessage())));
});
$app->dispatch();
use Klein\Klein as Route;
$bag = new Pimple\Container();
// container
$route = new Route();
$home = new Home($bag);
//controller
$dashboard = new Dashboard($bag);
// controller
$user = new User();
$role = new Role();
$leave = new LeaveController($bag);
// $route->respond( function () use($home){
//     return 'Middleware should be first palce';
// });
$route->respond('GET', '/', function () use($home) {
    return $home->index();
});
$route->respond('GET', '/test', function () use($user, $role) {
    $users = $user->all();
    foreach ($users as $user) {
        var_dump($user->role->permission);
    }
});
$route->respond('GET', '/show/[i:id]', function ($request) use($home) {
    return $home->show($request);
});
$route->respond('GET', '/create', function () use($home) {
    return $home->create();
});
$route->respond('POST', '/store', function ($request, $response) use($home) {
    return $home->store($request, $response);