/** * @param Request $request * @return RawResponse * @throws \Exception */ public function request(Request $request) { $res = $this->client->request('GET', $request->getUrl()); if ($res->getStatusCode() == 200) { return new RawResponse((string) $res->getBody()); } throw new \Exception('Error code', $res->getStatusCode()); }
/** * Cleanup the cookie support check */ public function cleanupCheck() { if ($this->request->getUrl()->hasParam('_checkCookie') && isset($_COOKIE[self::CHECK_COOKIE])) { $requestUri = $this->request->getUrl()->without('_checkCookie'); $this->request->getResponse()->redirectAndExit($requestUri); } }
private function initCurl() { $this->curl = curl_init($this->request->getUrl()); foreach ($this->request->getOptions() as $option) { curl_setopt($this->curl, $option[0], $option[1]); } $this->curlResponse = curl_exec($this->curl); }
/** * Matches Request to one of defined routes * * @param Request $request * @return array * @throws NoRouteFound */ public function match(Request $request) { $method = $request->getMethod(); if (isset($this->routes[$method])) { foreach ((array) $this->routes[$method] as $routePattern => $routeSettings) { if ($this->matchRoute($request->getUrl(), $routePattern, $routeSettings) === TRUE) { return $routeSettings; } } } http_response_code(404); throw new NoRouteFound('No routed found for method "' . $method . '" and URL "' . $request->getUrl() . '"'); }
/** * @param Request $request * @return Response */ public function call(Request $request) { // Create cURL $ch = curl_init(); // Set-up URL curl_setopt($ch, CURLOPT_URL, $request->getUrl()); // Set-up headers $headers = $request->getHeaders(); array_walk($headers, function (&$item, $key) { $item = "{$key}: {$item}"; }); curl_setopt($ch, CURLOPT_HTTPHEADER, array_values($headers)); // Set-up others curl_setopt_array($ch, $request->getOpts()); // Receive result $result = curl_exec($ch); // Parse response $response = new Response(); if ($result === FALSE) { $response->setError(curl_strerror(curl_errno($ch))); $response->setData(FALSE); $response->setCode(curl_errno($ch)); $response->setHeaders(curl_getinfo($ch)); } else { $response->setData(json_decode($result)); $response->setCode(curl_getinfo($ch, CURLINFO_HTTP_CODE)); $response->setHeaders(curl_getinfo($ch)); } // Close cURL curl_close($ch); return $response; }
function testConstruct() { $request = new Request('GET', '/foo', ['User-Agent' => 'Evert']); $this->assertEquals('GET', $request->getMethod()); $this->assertEquals('/foo', $request->getUrl()); $this->assertEquals(['User-Agent' => ['Evert']], $request->getHeaders()); }
public function testGetUrlFormatsAUrl() { $request = new Request(); $request->setHost('http://example.com'); $request->setResource('/resource/123'); $this->assertEquals($request->getUrl(), 'http://example.com/resource/123'); }
public function execute(Request $request) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $request->getUrl()); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:')); $username = $request->getUsername(); $password = $request->getPassword(); if ($username && $password) { curl_setopt($ch, CURLOPT_USERPWD, $username . ':' . $password); } switch ($request->getMethod()) { case self::POST: case self::PUT: curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($request->getParameters())); break; case self::DELETE: curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE'); break; case self::GET: default: break; } $result = curl_exec($ch); if (!$result) { $errorNumber = curl_errno($ch); $error = curl_error($ch); curl_close($ch); throw new \Exception($errorNumer . ': ' . $error); } curl_close($ch); return $request->getResponseTransformerImpl()->transform($result); }
/** * @param $destination */ public function redirect($destination) { if (!isset($_SESSION)) { session_start(); } $_SESSION['referrer'] = Request::getUrl(); header('Location: ' . $destination, true); exit; }
public function handle(Request $req, Response $res) : Response { if ($this->startTime) { $endTime = microtime(true); $message = date(\DateTime::ATOM, $this->startTime) . ' ' . $req->getUrl()->getFull() . ' ' . ($endTime - $this->startTime); file_put_contents($this->logfile, $message, \FILE_APPEND | \LOCK_EX); } else { $this->startTime = microtime(true); } }
/** * Verify basic functionality of the request object. * * @test * @covers ::__construct * @covers ::getUrl * @covers ::getBody * @covers ::getMethod * @covers ::getHeaders * * @return void */ public function construct() { $url = 'a url'; $method = 'a method'; $body = ['some' => 'data']; $headers = ['key' => 'value']; $request = new Request($url, $method, $headers, $body); $this->assertSame($url, $request->getUrl()); $this->assertSame($method, $request->getMethod()); $this->assertSame($headers, $request->getHeaders()); $this->assertSame($body, $request->getBody()); }
/** * Handle Request. * * Determines which router should be executed and hand over job to it * * @param Request $request * * @return Response */ public function handle(Request $request) { $router = $this->findRouter($request->getUrl()); if (is_null($router)) { return $this->getNotFoundResponse('Cannot found Controller'); } /** @var Controller $controller */ $controller = new $router['class'](); $controller->setService('octrine', $this->configureOctrineService()); $controller->setService('session', $this->configureSession()); return call_user_func_array([$controller, $router['method']], [$request]); }
public function __construct(\Request $request, \Http\ErrorResponse $response) { $vars = array(); $vars['url'] = $request->getUrl(); $vars['method'] = $request->getMethod(); $vars['module'] = $request->getModule(); $vars['code'] = $response->getCode(); $vars['phrase'] = $response->getPhrase(); $vars['backtrace'] = $response->getBacktrace(); $vars['exception'] = $response->getException(); $this->code = $vars['code']; parent::__construct($vars, PHPWS_SOURCE_DIR . 'Global/Templates/Http/HtmlError.html', false); }
/** * 解析路由规则表 *+-------------- * @param Void * @return Self */ public function parser() { $url = $this->request->getUrl(); if ($url) { //如果$uri不为空,遍历路由规则表,将$uri与每条规则表进行正则匹配,直到找到相匹配的规则信息;否则抛出异常 foreach ($this->routes as $key => $route) { if (empty($route)) { continue; } if (preg_match($this->matchs($route), $url, $this->matchs)) { $this->active = $key; break; } } } else { //获取默认路由规则,路由表最后一个 $route = $this->routes[count($this->routes) - 1]; if (isset($route[2])) { $this->matchs = $route[2]; } } return $this; }
public function passThrough(Request $request) { $params = $request->getParameters(); if (array_key_exists('api_key', $params)) { throw new \ErrorException('Request contains parameter with a reserved name: \'api_key\''); } if (array_key_exists('api_sig', $params)) { throw new \ErrorException('Request contains parameter with a reserved name: \'api_sig\''); } $params['api_key'] = $this->consumerKey; $baseString = BaseString::compute($request->getMethod(), $request->getUrl(), $params); $signature = base64_encode(hash_hmac('sha1', $baseString, rawurlencode($this->consumerSecret), true)); $request->setParameter('api_key', $this->consumerKey); $request->setParameter('api_sig', $signature); }
/** * Decode an HTTP Response. * @static * @throws Exception * @param Request $response The http response to be decoded. * @param Client $client * @return mixed|null */ public static function decodeHttpResponse($response, Client $client = null) { $code = $response->getResponseHttpCode(); $body = $response->getResponseBody(); $decoded = null; if (intVal($code) >= 300) { $decoded = json_decode($body, true); $err = 'Error calling ' . $response->getRequestMethod() . ' ' . $response->getUrl(); if (isset($decoded['error']) && isset($decoded['error']['message']) && isset($decoded['error']['code'])) { // if we're getting a json encoded error definition, use that instead of the raw response // body for improved readability $err .= ": ({$decoded['error']['code']}) {$decoded['error']['message']}"; } else { $err .= ": ({$code}) {$body}"; } $errors = null; // Specific check for APIs which don't return error details, such as Blogger. if (isset($decoded['error']) && isset($decoded['error']['errors'])) { $errors = $decoded['error']['errors']; } $map = null; if ($client) { $client->getLogger()->error($err, array('code' => $code, 'errors' => $errors)); $map = $client->getClassConfig('Exception', 'retry_map'); } throw new Exception($err, $code, null, $errors, $map); } // Only attempt to decode the response, if the response code wasn't (204) 'no content' if ($code != '204') { if ($response->getExpectedRaw()) { return $body; } $decoded = json_decode($body, true); if ($decoded === null || $decoded === "") { $error = "Invalid json in service response: {$body}"; if ($client) { $client->getLogger()->error($error); } throw new Exception($error); } if ($response->getExpectedClass()) { $class = $response->getExpectedClass(); $decoded = new $class($decoded); } } return $decoded; }
public function __construct(\Request $request, \Http\ErrorResponse $response) { $json = array(); $json['url'] = $request->getUrl(); $json['method'] = $request->getMethod(); $json['module'] = $request->getModule(); $json['code'] = $response->getCode(); $json['phrase'] = $response->getPhrase(); $json['backtrace'] = $response->getBacktrace(); $json['exception'] = $response->getException(); if (is_a($json['exception'], '\\Exception')) { $json['exception_code'] = $response->getException()->getCode(); $json['exception_file'] = $response->getException()->getFile(); $json['exception_line'] = $response->getException()->getLine(); $json['exception_message'] = $response->getException()->getMessage(); } parent::__construct(array('error' => $json)); }
/** * @return Response * * @throws BadResponseException */ protected function process(Request $request) { $headerStr = []; foreach ($request->getHeaders() as $name => $value) { foreach ((array) $value as $v) { $headerStr[] = "{$name}: {$v}"; } } $options = ['http' => ['method' => $request->getMethod(), 'header' => implode("\r\n", $headerStr) . "\r\n", 'follow_location' => 0, 'protocol_version' => 1.1, 'ignore_errors' => TRUE], 'ssl' => ['verify_peer' => TRUE, 'cafile' => realpath(__DIR__ . '/../../ca-chain.crt'), 'disable_compression' => TRUE]]; if (($content = $request->getContent()) !== NULL) { $options['http']['content'] = $content; } if ($this->sslOptions) { $options['ssl'] = $this->sslOptions + $options['ssl']; } list($code, $headers, $content) = $this->fileGetContents($request->getUrl(), $options); return new Response($code, $headers, $content); }
public function handle(Request $req, Response $res) : Response { // Skip if it is the path where the user is supposed to sign up if ($this->signUpPath && $this->signUpPath === trim($req->getUrl()->getPath(), '/')) { return $res; } // A way to validate the user credentials is required if (!$this->authStrategy) { throw new \InvalidArgumentException('An authentication strategy must be provided in order to identify the users in the system'); } // Access forbidden if no credentials are provided if (!$_SERVER['PHP_AUTH_USER']) { return $res->build(HttpStatus::Unauthorized, ['WWW-Authenticate' => 'Basic'], ['title' => 'Unauthenticated', 'detail' => 'The information you are trying to access requires authentication']); } $user = $_SERVER['PHP_AUTH_USER']; $pass = $_SERVER['PHP_AUTH_PW']; // Validate the user-provided credentials if (!$this->authStrategy->checkCredentials($user, $pass)) { return $res->build(HttpStatus::Unauthorized, [], ['title' => 'Wrong password', 'detail' => 'The password provided is not correct for the username']); } return $res; }
/** * Prepare the curl resource for sending a request. * * @param Request $request * * @return void */ public function prepareRequest(Request $request) { $this->ch = curl_init(); curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($this->ch, CURLOPT_HEADER, true); if ($request->getUserAndPass()) { curl_setopt($this->ch, CURLOPT_USERPWD, $request->getUserAndPass()); } curl_setopt($this->ch, CURLOPT_URL, $request->getUrl()); $options = $request->getOptions(); if (!empty($options)) { curl_setopt_array($this->ch, $options); } $method = $request->getMethod(); if ($method === 'post') { curl_setopt($this->ch, CURLOPT_POST, 1); } elseif ($method !== 'get') { curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, strtoupper($method)); } curl_setopt($this->ch, CURLOPT_HTTPHEADER, $request->formatHeaders()); if ($this->methods[$method] === true) { curl_setopt($this->ch, CURLOPT_POSTFIELDS, $request->encodeData()); } }
/** * Start the routing procedure and find a valid route, if any. * * @access public */ public function route() { // Start the profiler Profiler::register('Core', 'Router'); // First, let's look at the URL the user supplied $requestUrl = array_values(array_filter(explode('/', Request::getUrl()))); $requestRoute = null; // Loop over each route and test to see if they are valid foreach (self::$_routes as $route) { if ($this->routeTest($requestUrl, $route)) { $requestRoute = $route; break; } } // We have completed the route matching // Finish the setup of the request object Profiler::register('Core', 'Request'); if ($requestRoute) { $_GET['controller'] = $route->endpoint['controller']; $_GET['action'] = $route->endpoint['action']; Request::setUrlFragments(str_replace($this->_routePath, '', Request::getUrl())); } else { Request::setUrlFragments(Request::getUrl(), true); } Profiler::deregister('Core', 'Request'); // Inform the event listener a request has been initialised Event::trigger('initRequest', array('controller' => Request::get('controller'), 'action' => Request::get('action'))); // And stop the profiler Profiler::deregister('Core', 'Router'); Profiler::deregister('Core', 'Front'); // And dispatch Dispatcher::loadController(Request::get('controller'), Request::get('action')); }
">по популярности <span class="glyphicon glyphicon-chevron-down"></span></a> <?php } else { ?> <a href="<?php echo Request::getUrl('sort', 'views_up'); ?> ">по популярности</a> <?php } ?> <?php } else { ?> <a href="<?php echo Request::getUrl('sort', 'views_up'); ?> ">по популярности</a> <?php } ?> </small> </div> </div> </div> </div> </div> <?php if (isset($data['errors'])) { ?> <?php
/** * Render the page. * * @access public * @throws Exception If the view does not exist. */ public function render() { // Can we use a cache to speed things up? // If the cache object exists then it means the controller wants to use caching // However, the action might have disabled it if (Cache::has(Request::getUrl('_'))) { // The cache is enabled and there is an instance of the file in cache $this->_variables['viewContent'] = Cache::get(Request::getUrl('_')); } else { // Set the action location we need to run $templateUrlAction = Config::get('path', 'base') . Config::get('path', 'project') . 'View/Script/' . $this->controller . '/' . $this->action . '.phtml'; // Does the view file exist? if (!file_exists($templateUrlAction)) { throw new \Exception('The view ' . $this->action . ' does not exist in ' . $this->controller); } // And parse the action's script $this->_variables['viewContent'] = $this->parse($templateUrlAction, $this->_variables, Request::getUrl('_')); } // This is the end of the controller's work Profiler::deregister('action', $this->action); Profiler::deregister('controller', $this->controller); // Now start to wrap the view content in the layout if (!$this->layout) { // No template, thanks $template = $this->_variables['viewContent']; } else { // Set the action location we need to run $templateUrlLayout = Config::get('path', 'base') . Config::get('path', 'project') . 'Layout/' . $this->layout . '.phtml'; // And parse the action's script $template = $this->parse($templateUrlLayout, $this->_variables); } // Inform the event listener that we are about to shutdown Event::trigger('initShutdown', array('controller' => $this->controller, 'action' => $this->action)); // Stop the profiling, we're done Profiler::stop(); // Add the profile to the page output? if (Config::get('profiler', 'enable', true)) { $template .= $this->profiler(Profiler::getProfilerData()); } // And now, the journey ends // We die so that we do not call other action's render() die($template); }
/** * */ public static function dispatch(Request $request) { //$url, $verb, $headers, $get_args, $body) { $url = $request->getUrl(); $handler_verb = $verb = $request->getVerb(); if (!isset(self::$handlers[$verb])) { if (!count(self::$handlers[''])) { // error -- invalid verb $resp = new ResponseMethodNotAllowed('Could not find a handler for the "' . $verb . '" HTTP verb.', $request); $resp->render(); return; } else { $handler_verb = ''; } } if ($handler_verb !== '' && self::real_dispatch($request, $handler_verb)) { return; } // try multi-verb handlers if (self::real_dispatch($request, '')) { return; } // could this be dispatched for any other verb? if (self::could_dispatch($url)) { // yes, so the verb is wrong $resp = new ResponseMethodNotAllowed('The HTTP verb "' . $verb . '" cannot be used on the requested URL.', $request); $resp->render(); return; } // error -- no handler for URL $resp = new ResponseNotFound('Could not find a handler for the requested URL.', $request); $resp->render(); return; }
/** * generate base URL */ protected function baseUrl() { $path = dirname($_SERVER['SCRIPT_NAME']); $path = trim($path, '/'); $baseUrl = \Request::getUrl(); $baseUrl = trim($baseUrl, '/'); return $baseUrl . '/' . $path . ($path ? '/' : ''); }
/** * Parses the given request and returns the corresponding route and parameters. * @param \yii\web\UrlManager $manager the URL manager * @param Request $request the request component * @return array|bool the parsing result. The route and the parameters are returned as an array. * @throws ForbiddenHttpException */ public function parseRequest($manager, $request) { $menuMap = $this->menuManager->getMenuMap(); if (!($pathInfo = $request->getPathInfo() or $pathInfo = ($mainMenu = $menuMap->getMainMenu()) ? $mainMenu->path : null)) { return false; } // помечаем как активные все пункты меню которые ссылаются на тотже урл что в запросе $this->menuManager->setActiveMenuIds($menuMap->getMenuIdsByLink($request->getUrl())); // ищем пункт меню, чей путь совпадает с путем в запросе if ($menu = $menuMap->getMenuByPathRecursive($pathInfo)) { // определяем в каком контексте ("Точный" или "Подходящий") рассматривать активное меню $menu->setContext($menu->path === $pathInfo ? MenuItem::CONTEXT_PROPER : MenuItem::CONTEXT_APPLICABLE); // устанавливаем найденный пункт меню в качестве активного $this->menuManager->setActiveMenu($menu); // добавляем данный пункт в список активных пунктов меню $this->menuManager->addActiveMenuId($menu->id); if ($menu->getContext() === MenuItem::CONTEXT_PROPER) { //при "точном" совпадении, метаданные меню перекрывают метаднные контроллера Yii::$app->getView()->on(View::EVENT_BEGIN_PAGE, [$this, 'applyMetaData']); } else { //при "подходящем" устанавливаются по умолчанию $this->applyMetaData(); } } else { return false; } // устанавливаем макет приложению Event::on(Controller::className(), Controller::EVENT_BEFORE_ACTION, [$this, 'applyLayout']); // Проверка на доступ к пунтку меню if (!empty($menu->access_rule) && !Yii::$app->user->can($menu->access_rule)) { if (Yii::$app->user->getIsGuest()) { Yii::$app->user->loginRequired(); } else { throw new ForbiddenHttpException(Yii::t('gromver.platform', 'You have no rights for access to this section of the site.')); } } if ($menu->getContext() === MenuItem::CONTEXT_PROPER) { // при "точном" контексте пункта меню, возвращаем роут на компонент return $menu->parseUrl(); } else { /* * при "подходящем" контексте пункта меню, необходимо на основании оставшейся части пути * и информации из пункта меню маршрутизировать приложение */ $requestRoute = substr($pathInfo, mb_strlen($menu->path) + 1); list($menuRoute, $menuParams) = $menu->parseUrl(); $requestInfo = new MenuRequestInfo(['menuMap' => $menuMap, 'menuRoute' => $menuRoute, 'menuParams' => $menuParams, 'requestRoute' => $requestRoute, 'requestParams' => $request->getQueryParams()]); foreach ($this->_parseUrlRules as $rule) { if ($result = $rule->process($requestInfo, $this)) { return $result; } } return false; } }
<?php /* El front end controller se encarga de configurar nuestra aplicacion * */ require 'config.php'; require 'helpers.php'; require_once 'library/Request.php'; //llamar al controlador indicado //getController($_GET['url']); if (empty($_GET['url'])) { $url = ''; } else { $url = $_GET['url']; } $request = new Request($url); var_dump($request->getUrl()); //var_dump($_GET);
<!-- --><?php //else: ?> <!-- <span>--><?php //echo __('Следующая') ?> <!--</span>--> <!-- --><?php //endif ?> <?php if ($last_page !== FALSE) { ?> <li><a href="<?php echo Request::getUrl('page', $last_page); ?> " title="В конец"><?php echo __('≫'); ?> </a></li> <?php } else { ?> <li><span><?php echo __('≫'); ?> </span></li> <?php } ?>
<span class="glyphicon glyphicon-arrow-up red"></span> </a> <?php } elseif (isset($_GET['sort']) && $_GET['sort'] == 'ordering_DESC') { ?> <a href="<?php echo Request::getUrl('sort', 'ordering_ASC'); ?> "> <span class="glyphicon glyphicon-arrow-down red"></span> </a> <?php } else { ?> <a href="<?php echo Request::getUrl('sort', 'ordering_ASC'); ?> "> <span class="glyphicon glyphicon-arrow-down"></span> </a> <?php } ?> </th> <th style="width:100px"> Главный </th> </tr> <?php foreach ($data['widgets'] as $widget) { ?>
/** * Helper function to gather all the curl options: global, inferred, and per request * * @param Request $request * @return array */ private function prepareRequestOptions(Request $request) { // options for this entire curl object $options = $this->getOptions(); // set the request URL $options[CURLOPT_URL] = $request->getUrl(); // set the request method $options[CURLOPT_CUSTOMREQUEST] = $request->getMethod(); // posting data w/ this request? if ($request->getPostData()) { $options[CURLOPT_POST] = 1; $options[CURLOPT_POSTFIELDS] = $request->getPostData(); } // if the request has headers, use those, or if there are global headers, use those if ($request->getHeaders()) { $options[CURLOPT_HEADER] = 0; $options[CURLOPT_HTTPHEADER] = $request->getHeaders(); } elseif ($this->getHeaders()) { $options[CURLOPT_HEADER] = 0; $options[CURLOPT_HTTPHEADER] = $this->getHeaders(); } // if the request has options set, use those and have them take precedence if ($request->getOptions()) { $options = $request->getOptions() + $options; } return $options; }