public static function route(\Request $request) { $method = $request->getRequestMethod(); $req = $request->getRequestedUri(); $routes = new \Config("routes"); $routes = $routes->{$method}; foreach ($routes as $url => $handler) { $url = preg_replace("|\\:([a-z0-9\\_\\-]+)|iu", "(?P<\$1>.*)", $url); if (preg_match("|{$url}|iu", $request->getRequestedUri(), $params)) { list($controller, $method) = explode("::", $handler); $request->setParams($params); break; } } if (!isset($controller)) { $controller = "Controller\\BadRequest"; $method = "output404"; } $controller = new $controller(); $auth = new Authentication\Auth(); if ($controller instanceof Controller\AbAuthController && !$auth->isLoggedIn()) { return array($controller, "checkLogin"); } return array($controller, $method); }
/** * 处理uri */ private static function _httpRout() { $uri = self::$_uri; $moduleName = null; if ($uri == '') { if (MODULE_MODE) { $moduleName = self::$_defaultModule; } $controllerName = self::$_defaultController; $actionName = self::$_defaultAction; } else { $uriArr = explode('/', $uri); if (MODULE_MODE) { $moduleName = array_shift($uriArr); if (count($uriArr) > 0) { $controllerName = array_shift($uriArr); if (count($uriArr) > 0) { $actionName = array_shift($uriArr); } else { $actionName = self::$_defaultAction; } } else { $controllerName = self::$_defaultController; $actionName = self::$_defaultAction; } } else { $controllerName = array_shift($uriArr); $actionName = array_shift($uriArr); $actionName = $actionName !== null ? $actionName : self::$_defaultAction; } //处理剩余参数 if (count($uriArr) > 0) { $params = array(); preg_replace_callback('/(\\w+)\\/([^\\/]+)/', function ($match) use(&$params) { $params[$match[1]] = $match[2]; }, implode('/', $uriArr)); // 解析剩余的URL参数 Request::setParams($params, 'get'); } } //过滤并赋值 $moduleName = C::filterChars($moduleName); $controllerName = C::filterChars($controllerName); $actionName = C::filterChars($actionName); self::$_currentModule = $moduleName; self::$_currentController = $controllerName; self::$_currentAction = $actionName; }
/** * Given the request data and the loaded resource metadata, pick the best matching * resource to handle the request based on URI and priority. * * @param Request $request * @return ResourceMetadata */ public function route($request = NULL) { $matchedResource = NULL; if (!$request) { $request = new Request(); } foreach ($this->resources as $className => $resourceMetadata) { foreach ($resourceMetadata->getUri() as $index => $uri) { $uriRegex = '|^' . $uri . '$|'; if (($matchedResource == NULL || $matchedResource[0]->getPriority() < $resourceMetadata->getPriority()) && preg_match($uriRegex, $request->getUri(), $params)) { array_shift($params); $uriParams = $resourceMetadata->getUriParams($index); if ($uriParams) { // has params within URI foreach ($uriParams as $key => $name) { $params[$name] = $params[$key]; } } $matchedResource = array($resourceMetadata, $params); } } } if ($matchedResource) { $request->setParams($matchedResource[1]); return $matchedResource[0]; } else { throw new NotFoundException(sprintf('Resource matching URI "%s" not found', $request->uri)); } }
$wsTransactionDetail->buyOrder = $buyOrder; $wsTransactionDetail->amount = $amount; //$wsTransactionDetail->sharesNumber = $shareNumber; //$wsTransactionDetail->sharesAmount = $shareAmount; $wsInitTransactionInput->transactionDetails = $wsTransactionDetail; #Instancia la clase que comunica con el webservice tbk $webpayService = new WsTiendaNormal(); #echo "<pre>";print_r($wsInitTransactionInput);echo "</pre>";die(); #Trata de ejecutar el método try { $initTransactionResponse = $webpayService->initTransaction(array("wsInitTransactionInput" => $wsInitTransactionInput)); } catch (SoapFault $exception) { ClassNegocio::throwException($exception); die; } #Obtiene la respuesta y la válida con el certificado público de Tbk $xmlResponse = $webpayService->soapClient->__getLastResponse(); $soapValidation = new SoapValidation($xmlResponse, SERVER_CERT); $validationResult = $soapValidation->getValidationResult(); if (!$validationResult) { # Si la respuesta no es válida, fracaso. $exception = "Error en Init Trx , la respuesta no es válida."; ClassNegocio::throwException($exception); die; } # Si la respuesta es válida hace un POST a la url que retorna el metodo con el token indicado $wsInitTransactionOutput = $initTransactionResponse->return; $request = new Request(); $params = array("token_ws" => $wsInitTransactionOutput->token); $request->setParams($params); $request->forward($wsInitTransactionOutput->url);
/** * Routing the controller actions based on url, to run a class method in question. * * @return void * @throws Exception * @throws NotFoundException * @throws MemberInaccessibleException */ public function dispatch() { Loader::load('Request', 'core'); Loader::load('ViewAbstract', 'core'); $request = new Request(); $response = new Response(); $view = null; $viewInitialized = false; $subdir = ''; try { // check system root setting. $sysRoot = PathManager::getSystemRoot(); if ($sysRoot == null) { throw new Exception('Path of the system root has not been specified.'); } else { if (!file_exists($sysRoot)) { throw new Exception('Path of the system root does not exist.'); } } $router = new Router(); // initialize by Initializer. $initializer = $this->_searchIntializer(); if ($initializer instanceof InitializerStandard) { $initializer->setDispatcher($this); $initializer->setRouter($router); $initializer->applyConfig(); $initializer->initEnv(); $initializer->initialize(); } $params = $router->route($request->getBasePath()); // create view class instance. Loader::load($this->_viewClassName, null, true, false); $viewClass = $this->_viewClassName; $view = new $viewClass(); // set request instance to controller. $subdir = $params['subdir']; $request->setController($params['controller'], $subdir); $request->setAction($params['action']); $request->setParams($params['params']); $view->setRequest($request); $view->initialize(); $viewInitialized = true; // create controller class instance. $controller = $this->_getControllerInstance($params['controller'], $params['subdir']); if ($controller == false) { throw new NotFoundException($params['controller'], ''); } $controller->setAppEnv($this->_appEnv); $controller->setRequest($request); // set response instance to controller. $controller->setResponse($response); // set view to controller. $controller->setView($view); // get action method name. $reqestMethod = null; $actionMethod = ''; if ($controller instanceof RestController) { $request->isRestAccess(true); $reqestMethod = $request->getMethod(); if ($params['action'] == 'index' && $reqestMethod != 'GET') { $restDefaultMethod = NameManager::convertActionToMethod($reqestMethod); if (method_exists($controller, $restDefaultMethod)) { $actionMethod = $restDefaultMethod; } } } if ($actionMethod == '') { $actionMethod = NameManager::convertActionToMethod($params['action'], $reqestMethod); } // initialize validator $validatorClass = $this->_validatorClassName; $validator = new $validatorClass(); $controller->setValidator($validator); $controller->initValidator(); $controller->initialize(); // Create plugin instance. $plugin = null; if ($this->_pluginEnabled) { $plugin = $this->_searchPlugin($params['subdir']); if ($plugin instanceof PluginAbstract) { $plugin->setControllerInstance($controller); $plugin->preProcess(); } } $controller->preProcess(); if ($controller->isDispatched() == false) { // Check action method exists. if (!method_exists($controller, $actionMethod)) { $controllerParam = $params['controller']; if ($params['subdir'] != null) { $controllerParam = $params['subdir'] . '/' . $controllerParam; } throw new NotFoundException($controllerParam, $params['action']); } else { if (!is_callable(array($controller, $actionMethod))) { throw new MemberInaccessibleException($params['controller'], $params['action']); } } $controller->{$actionMethod}(); } $controller->postProcess(); if ($this->_pluginEnabled) { if ($plugin instanceof PluginAbstract) { $plugin->postProcess(); } } if ($controller instanceof RestController) { if ($controller->isAutoRedirect() == true && $request->getMethod() != 'GET') { $url = ''; if ($params['action'] != 'index') { $url = $params['controller'] . '/' . $params['action']; } else { if ($params['controller'] != 'index') { $url = $params['controller']; } } $url = $request->getBaseUrl() . '/' . $url; $response->redirect($url); } } $response->send(); if ($response->isOutput() == false && $view->getRenderingEnabled() == true) { $viewScript = $this->_getViewScriptInstance($params['controller'], $params['subdir']); if ($viewScript instanceof ViewScript) { if (method_exists($viewScript, $actionMethod)) { $viewScript->setView($view); $viewScript->setRequest($request); $viewScript->{$actionMethod}(); } } $view->render(); } } catch (Exception $e) { $handler = $this->_searchErrorHandler($subdir); if ($handler instanceof ErrorHandlerStandard) { $action = 'error'; $actionMethod = ''; $className = get_class($e); if ($className != 'Exception') { $actionMethod = str_replace('Exception', '', $className); $actionMethod = NameManager::toMethod($actionMethod); } if (method_exists($handler, $actionMethod)) { $action = $actionMethod; } $handler->setException($e); $handler->setRequest($request); $handler->setResponse($response); if ($viewInitialized == true) { $handler->setView($view); } if ($action == 'notFound') { if ($this->_isSend404 == true) { $response->setHttpStatus('404'); $response->send(); } } $handler->{$action}(); } else { throw $e; } } }
/** * Executes a route handler. * * @param array|string $route array('controller','method') or array('controller') * or 'method' * @param Request $req * @param Response $res * @param array $args * * @throws Exception when the route cannot be resolved. * * @return Response */ public function resolve($route, $req, $res, array $args) { $result = false; if (is_array($route) || is_string($route)) { // method name and controller supplied if (is_string($route) && $req->params('controller')) { $route = [$req->params('controller'), $route]; // method name supplied } elseif (is_string($route)) { $route = [$this->defaultController, $route]; // no method name? fallback to the index() method } elseif (count($route) == 1) { $route[] = $this->defaultAction; } list($controller, $method) = $route; $controller = $this->namespace . '\\' . $controller; if (!class_exists($controller)) { throw new \Exception("Controller does not exist: {$controller}"); } $controllerObj = new $controller(); // give the controller access to the DI container if (method_exists($controllerObj, 'setApp')) { $controllerObj->setApp($this->app); } // collect any preset route parameters if (isset($route[2])) { $params = $route[2]; $req->setParams($params); } $result = $controllerObj->{$method}($req, $res, $args); } elseif (is_callable($route)) { $result = call_user_func($route, $req, $res, $args); } if ($result instanceof View) { $res->render($result); } return $res; }
/** * @param array $data * @throws Exception * @return self */ public static function fromArray(array $data) { if (empty($data['jsonrpc'])) { throw new Exception('Request is not valid JsonRPC request: missing protocol version'); } if ($data['jsonrpc'] != self::VERSION) { throw new Exception('Request is not valid JsonRPC request: invalid protocol version'); } if (empty($data['method'])) { throw new Exception('Request is not valid JsonRPC request: missing method'); } $request = new Request(); $request->setMethod($data['method']); if (!empty($data['id'])) { $request->setId($data['id']); } if (!empty($data['params'])) { $request->setParams($data['params']); } return $request; }
/** * Builds a response to an incoming request by routing * it through the application. * * @param Request $req * * @return Response */ public function handleRequest(Request $req) { // set host name from request if not already set $config = $this['config']; if (!$config->get('app.hostname')) { $config->set('app.hostname', $req->host()); } $res = new Response(); try { // determine route by dispatching to router $routeInfo = $this['router']->dispatch($req->method(), $req->path()); $this['routeInfo'] = $routeInfo; // set any route arguments on the request if (isset($routeInfo[2])) { $req->setParams($routeInfo[2]); } // the dispatch middleware is the final step $dispatch = new DispatchMiddleware(); $dispatch->setApp($this); $this->middleware($dispatch); // the request is handled by returning the response // generated by the middleware chain return $this->runMiddleware($req, $res); } catch (\Exception $e) { return $this['exception_handler']($req, $res, $e); } catch (\Error $e) { return $this['php_error_handler']($req, $res, $e); } }