If the X-HTTP-Method-Override header is set, and if the method is a POST,
then it is used to determine the "real" intended HTTP method.
The _method request parameter can also be used to determine the HTTP method,
but only if enableHttpMethodParameterOverride() has been called.
The method is always an uppercased string.
public static function run(Request $request) { /** get the Controller, Method, Arguments/Parameters and the URL of the Controller */ $controller = $request->getController() . "Controller"; $method = $request->getMethod(); $args = $request->getArgs(); $controllerUrl = ROOT . "controllers" . DS . $controller . ".php"; if ($method == "index.php") { $method = "index"; } /** if the Controller exists, call the Controller */ if (is_readable($controllerUrl)) { require_once $controllerUrl; $fullController = "Controllers\\" . $controller; $controller = new $fullController(); if (!isset($args)) { $data = call_user_func(array($controller, $method)); } else { $data = call_user_func_array(array($controller, $method), $args); } } /** Render view */ $controllerUrl = ROOT . "views" . DS . $request->getController() . DS . $request->getMethod() . ".php"; if (is_readable($controllerUrl)) { require_once $controllerUrl; } else { print "No se encontró la ruta especificada."; } }
/** * The method of the request was set to get in the constructor * * @depends testConstructorNoParams * @return null */ public function testIsGetPostCli() { $this->assertTrue($this->input->isGet()); $this->assertFalse($this->input->isPost()); $this->assertFalse($this->input->isCli()); $this->assertEquals('get', $this->input->getMethod()); $input = new AppInput('post'); $this->assertTrue($input->isPost()); $this->assertFalse($input->isGet()); $this->assertFalse($input->isCli()); $this->assertEquals('post', $input->getMethod()); $input = new AppInput('cli'); $this->assertTrue($input->isCli()); $this->assertFalse($input->isGet()); $this->assertFalse($input->isPost()); $this->assertEquals('cli', $input->getMethod()); /* prove not case sensitive */ $input = new AppInput('GET'); $this->assertTrue($input->isGet()); $this->assertFalse($input->isPost()); $this->assertFalse($input->isCli()); $this->assertEquals('get', $input->getMethod()); $input = new AppInput('POST'); $this->assertTrue($input->isPost()); $this->assertFalse($input->isGet()); $this->assertFalse($input->isCli()); $this->assertEquals('post', $input->getMethod()); $input = new AppInput('CLI'); $this->assertTrue($input->isCli()); $this->assertFalse($input->isGet()); $this->assertFalse($input->isPost()); $this->assertEquals('cli', $input->getMethod()); }
public function getResponse() { try { return new SuccesfullResponse($this->requestObject->getId(), $this->dispatchMethod($this->requestObject->getMethod(), $this->requestObject->getParams())); } catch (\Exception $e) { return new ErrorResponse($this->requestObject->getId(), array('message' => $e->getMessage(), 'code' => $e->getCode())); } }
/** * Invokes controller's method of given route * * @param Route $route * @return void */ public static function invoke(Route $route) { $ctrl_file = CTRLPATH . $route->controller . EXT; $class_name = self::getClassNameByController($route->controller); if (!$ctrl_file) { App::notFound('Could not find controller "' . $route->controller . '" for route "' . $route->name . '"'); } if (!is_readable($ctrl_file)) { App::notFound('Cannot load file "' . $ctrl_file . '" for route "' . $route->name . '"'); } if (!class_exists($class_name)) { require $ctrl_file; } $ctrl_class = new $class_name(); $methods_to_try[] = 'action' . ucfirst(Request::getMethod()) . '__' . $route->action; $methods_to_try[] = 'action__' . $route->action; $called = false; foreach ($methods_to_try as $method) { if (method_exists($ctrl_class, $method)) { call_user_func_array(array($ctrl_class, $method), array()); $called = true; break; } } if (!$called) { App::notFound('Could not find valid method of class "' . $class_name . '" to execute'); } unset($ctrl_class); }
/** * Handles an incoming HTTP request and dispatches it to the appropriate action. * * @param Request $request The HTTP request message. * @param Socket $socket The client socket connection. * * @return \Generator * * @resolve \Icicle\Http\Message\Response The appropriate HTTP response. */ public function onRequest(Request $request, Socket $socket) : \Generator { $dispatched = $this->app->getDispatcher()->dispatch($request->getMethod(), $request->getUri()->getPath()); switch ($dispatched[0]) { case FastRoute\Dispatcher::NOT_FOUND: // no route found $randomStr = ''; for ($i = 0; $i < 1000; ++$i) { $char = chr(mt_rand(32, 126)); if ($char !== '<') { $randomStr .= $char; } } $html = $this->app->getRenderer()->render('404', ['randomStr' => $randomStr]); $sink = new MemorySink(); yield from $sink->end($html); return new BasicResponse(404, ['Content-Type' => 'text/html', 'Content-Length' => $sink->getLength()], $sink); case FastRoute\Dispatcher::METHOD_NOT_ALLOWED: // HTTP request method not allowed $sink = new MemorySink(); yield from $sink->end('405 Method Not Allowed'); return new BasicResponse(405, ['Content-Type' => 'text/plain', 'Content-Length' => $sink->getLength()], $sink); case FastRoute\Dispatcher::FOUND: // route was found $action = new $dispatched[1]($this->app); $response = (yield from $action->handle($request, $dispatched[2])); return $response; default: throw new \RuntimeException('Invalid router state'); } }
public function handle() { // Propagate the request based on the HTTPMethod of the request. $method = \Request::getMethod(); switch ($method) { case "PUT": Auth::requirePermissions('tdt.input.create'); $uri = $this->getUri(); return $this->createJob($uri); break; case "GET": Auth::requirePermissions('tdt.input.view'); return $this->getJob(); break; case "DELETE": Auth::requirePermissions('tdt.input.delete'); return $this->deleteJob(); break; case "POST": Auth::requirePermissions('tdt.input.edit'); return $this->editJob(); break; default: \App::abort(400, "The method {$method} is not supported by the jobs."); break; } }
private function routeRequest(Request $request, Service $service) { $desired_method = String::underscoreToCamelCase($request->getMethod()); $requested_method = $request->getRequestMethod() . $desired_method; $method = $requested_method; $arguments = $request->getArguments(); if (!method_exists($service, $method)) { $method = $request->getRequestMethod() . 'Router'; if (!method_exists($service, $method)) { throw new MethodNotSupported($request->getService(), $requested_method); } array_splice($arguments, 0, 0, array($request->getMethod())); } $output = call_user_func_array(array($service, $method), $arguments); $this->response->setResponse($output); }
public function prepare(Request $request) { $headers = $this->headers; if ($this->isInformational() || in_array($this->statusCode, array(204, 304))) { $this->setContent(null); } // Content-type based on the Request if (!$headers->has('Content-Type')) { $format = $request->getRequestFormat(); if (null !== $format && ($mimeType = $request->getMimeType($format))) { $headers->set('Content-Type', $mimeType); } } // Fix Content-Type $charset = $this->charset ?: 'UTF-8'; if (!$headers->has('Content-Type')) { $headers->set('Content-Type', 'text/html; charset=' . $charset); } elseif (0 === strpos($headers->get('Content-Type'), 'text/') && false === strpos($headers->get('Content-Type'), 'charset')) { // add the charset $headers->set('Content-Type', $headers->get('Content-Type') . '; charset=' . $charset); } // Fix Content-Length if ($headers->has('Transfer-Encoding')) { $headers->remove('Content-Length'); } if ('HEAD' === $request->getMethod()) { // cf. RFC2616 14.13 $length = $headers->get('Content-Length'); $this->setContent(null); if ($length) { $headers->set('Content-Length', $length); } } return $this; }
public static function run($request) { if (!$request instanceof Request) { $request = new Request($request); } $file = $request->getFile(); $class = $request->getClass(); $method = $request->getMethod(); $args = $request->getArgs(); $front = FrontController::getInstance(); $registry = $front->getRegistry(); $registry->oRequest = $request; $front->setRegistry($registry); if (file_exists($file)) { require_once $file; $rc = new ReflectionClass($class); // if the controller exists and implements IController // if($rc->implementsInterface('IController')) if ($rc->isSubclassOf('BaseController')) { try { $controller = $rc->newInstance(); $classMethod = $rc->getMethod($method); return $classMethod->invokeArgs($controller, $args); } catch (ReflectionException $e) { throw new MvcException($e->getMessage()); } } else { // throw new MvcException("Interface iController must be implemented"); throw new MvcException("abstract class BaseController must be extended"); } } else { throw new MvcException("Controller file not found"); } }
/** * {@inheritdoc} */ public function matches(Request $request) { if (null !== $this->methods && !in_array(strtolower($request->getMethod()), $this->methods)) { return false; } foreach ($this->attributes as $key => $pattern) { if (!preg_match('#' . str_replace('#', '\\#', $pattern) . '#', $request->attributes->get($key))) { return false; } } if (null !== $this->path) { if (null !== ($session = $request->getSession())) { $path = strtr($this->path, array('{_locale}' => $session->getLocale(), '#' => '\\#')); } else { $path = str_replace('#', '\\#', $this->path); } if (!preg_match('#' . $path . '#', $request->getPathInfo())) { return false; } } if (null !== $this->host && !preg_match('#' . str_replace('#', '\\#', $this->host) . '#', $request->getHost())) { return false; } if (null !== $this->ip && !$this->checkIp($request->getClientIp())) { return false; } return true; }
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()); }
/** * Отправляет запрос. * * @param Request $request * @return Response|NULL * @throws \Exception */ public function send(Request $request) { $response = null; $curlHandle = curl_init(); $requestMethod = $request->getMethod(); try { switch (strtoupper($requestMethod)) { case 'GET': $response = $this->executeGet($curlHandle, $request); break; case 'POST': $response = $this->executePost($curlHandle, $request); break; case 'PUT': $response = $this->executePut($curlHandle, $request); break; case 'DELETE': $response = $this->executeDelete($curlHandle, $request); break; default: throw new \InvalidArgumentException("Current verb ({$requestMethod}) is an invalid REST verb."); } } catch (\Exception $e) { curl_close($curlHandle); throw $e; } curl_close($curlHandle); return $response; }
public function handle($id = null) { // Delegate the request based on the used http method $method = \Request::getMethod(); switch ($method) { case "PUT": return $this->put($id); break; case "GET": return $this->get($id); break; case "POST": if (!empty($id)) { // Don't allow POSTS to specific configurations (only PUT and DELETE allowed) \App::abort(405, "The HTTP method POST is not allowed on this resource. POST is only allowed on api/triples."); } return $this->post(); break; case "PATCH": return $this->patch(); break; case "DELETE": return $this->delete($id); break; case "HEAD": return $this->head(); break; default: // Method not supported \App::abort(405, "The HTTP method '{$method}' is not supported by this resource."); break; } }
/** * @Route("/change-password") */ public function changePasswordAction(Request $request) { $entityName = $this->container->getParameter('lemlabs_user.class'); // Prevent perfom logic below if user is authenticated, redirect to dashboard if ($this->container->get('security.context')->isGranted('IS_AUTHENTICATED_FULLY')) { return $this->redirect($redirectUrl); } $em = $this->getDoctrine()->getManager(); $salt = base64_decode($request->query->get('token')); $user = $em->getRepository($entityName)->findOneBySalt($salt); if (!$user) { $this->get('session')->getFlashBag()->add('danger', 'Cannot found the user'); } $form = $this->createForm(new PasswordType(), $user); if ($request->getMethod() == 'POST') { $form->bind($request); if ($form->isValid()) { $factory = $this->get('security.encoder_factory'); $encoder = $factory->getEncoder($user); // Dont forget salt, common in security process $user->setSalt(md5(time())); $user->setPassword($encoder->encodePassword($user->getPassword(), $user->getSalt())); $em->persist($user); $em->flush(); $this->get('session')->getFlashBag()->add('success', 'Congratulations, your password has been updated correctly;'); return $this->redirect($this->generateUrl('lemlabs_login')); } } return $this->render('LemLabsUserBundle:User:change-password.html.twig', array('form' => $form->createView(), 'errors' => $form->getErrors())); }
public function handle($uri) { $uri = ltrim($uri, '/'); // Delegate the request based on the used http method $method = \Request::getMethod(); switch ($method) { case "PUT": return $this->put($uri); break; case "GET": return $this->get($uri); break; case "POST": case "PATCH": return $this->patch($uri); break; case "DELETE": return $this->delete($uri); break; case "HEAD": return $this->head($uri); break; default: // Method not supported \App::abort(405, "The HTTP method '{$method}' is not supported by this resource ({$uri})."); break; } }
public function sign(Request $request) { $currentHeaders = $request->getHeaders(); $signatureHeader = $this->getV1SignatureHeader($this->credentials->getPublicId(), base64_decode($this->credentials->getSecret())); $currentHeaders['x-signature'] = $signatureHeader; return new ApiRequest($request->getBaseUrl(), $request->getFunction(), $request->getUrlParams(), $request->getMethod(), $request->getParams(), $currentHeaders); }
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); }
public function send(Request $request) { $functionUrl = $request->getBaseUrl() . '/' . $request->getFunction(); if (count($request->getUrlParams()) > 0) { $finalUrl = $functionUrl . '?' . http_build_query($request->getUrlParams()); } else { $finalUrl = $functionUrl; } $ch = curl_init($finalUrl); $headerArray = []; foreach ($request->getHeaders() as $key => $value) { $headerArray[] = ucfirst($key) . ': ' . $value; } curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $method = strtoupper($request->getMethod()); switch ($method) { case "GET": break; case "POST": curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $request->getParams()); break; case "DELETE": curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE"); break; case "PUT": curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($request->getParams())); break; } return json_decode(curl_exec($ch)); }
/** * Creates a Laravel route, returning a closure which passes the raw input to AngularPHP and returns the response */ protected function init() { $route = func_get_arg(0); $this->setErrorHandler(function (\Exception $e, Request $r) { \Log::error($e, $r->toArray()); }); $endpoint = $this; \Route::any($route, function () use($endpoint) { $path = '/' . \Request::path(); $referrer = \Request::header('referer'); $host = \Request::header('host'); if (($origin = \Request::header('Origin')) && count($this->corsHosts)) { $this->setCorsOrigin($origin); } /** * If being called remotely, add the domain name to the URI */ if (strlen($referrer) && parse_url($referrer, PHP_URL_HOST) != $host) { $uri = '//' . $host . $path; } else { $uri = $path; } $request = new Request(\Request::json()->all()); $response = $endpoint->setUri($uri)->execute($request, \Request::getMethod()); return \Response::make($response->content, $response->code, $response->headers)->header('Content-Type', $response->contentType); }); }
public function modify(array $params) { if (isset($params[0])) { $id_user = intval($params[0]); if (!($user = $this->model->getUser($id_user))) { return false; } $data = Request::getAssoc(array()); $errors = array(); if (Request::getMethod() == 'POST') { $data = Request::getAssoc(array('access', 'lastname', 'firstname', 'lastname', 'email')); if (!Tools::isEmail($data['email'])) { $errors[] = 'L\'email saisi n\'est pas valide !'; } if (empty($errors)) { $this->model->updateUser($id_user, $data); } $password = Request::getAssoc(array('password', 'password_confirm')); if (!empty($password['password']) && !empty($password['password_confirm'])) { // Update the password only if modified if ($password['password'] == $password['password_confirm']) { $this->model->updateUserPassword($id_user, $password['password']); } else { $errors[] = 'Les mots de passe saisis ne sont pas identiques.'; } } return array('id_user' => $id_user, 'user' => $user, 'method' => 'POST', 'errors' => $errors); } return array('id_user' => $id_user, 'user' => $user, 'method' => 'GET', 'errors' => $errors); } return false; }
/** * @param Huxtable\Web\Request $request * @return Huxtable\Web\Response */ public function route(Request $request) { $url = $request->getURL(); $method = $request->getMethod(); // Default response $response = new Response(); $response->setStatusCode(404); $response->setContents('Not Found :('); if (isset($this->routes[$url])) { $routes = $this->routes[$url]; // Route pattern + method match found if (isset($this->routes[$url][$method])) { $routeObject = $this->routes[$url][$method]; $routeObject->setRequest($request); // Call authenticatiion callback if defined $authenticationClosure = $routeObject->getAuthenticationClosure(); if ($authenticationClosure != false) { try { call_user_func($authenticationClosure); } catch (Request\UnauthorizedException $e) { $routeObject->response->setStatusCode(401); $routeObject->response->setContents($routeObject->response->getStatusMessage()); return $routeObject->response; } } // Confirm required headers were sent foreach ($routeObject->getRequiredHeaders() as $header) { if ($request->getHeader($header) === false) { $response->setStatusCode(400); $response->setContents($routeObject->response->getContents()); return $response; } } // Confirm required arguments were passed foreach ($routeObject->getRequiredArguments() as $argument) { if ($request->getArgument($argument) === false) { $response = new Response(); $response->setStatusCode(400); $response->setContents("Missing required argument '{$argument}'"); return $response; } } try { // Call the main routing closure $contents = call_user_func($routeObject->getClosure()); } catch (\Exception $e) { $response = new Response(); $response->setStatusCode(500); $response->setContents($e->getMessage()); return $response; } $routeObject->response->setContents($contents); return $routeObject->response; } // No route pattern + method match found $response->setStatusCode(405); $response->setContents('Method Not Allowed :('); } return $response; }
public static function route(Request $request) { $controller = $request->getController() . 'Controller'; $method = $request->getMethod(); $args = $request->getArgs(); //$controllerFile = SITE_PATH.'controllers/'.$controller.'.php'; //***Because autoload //if(is_readable($controllerFile)){ //***Because autoload //require_once $controllerFile; //***Because autoload $controller = new $controller(); $method = is_callable(array($controller, $method)) ? $method : 'index'; if (!empty($args)) { //call_user_func_array(array($controller,$method),$args); if (extension_loaded('newrelic')) { newrelic_name_transaction((string) $request->getController() . '/' . (string) $method); } call_user_func(array($controller, $method), $args); } else { if (extension_loaded('newrelic')) { newrelic_name_transaction((string) $request->getController() . '/' . (string) $method); } call_user_func(array($controller, $method), NULL); } return; //} //***Because autoload throw new Exception('404 - ' . $request->getController() . ' not found'); }
public function testConstructorSetsMethodResourceAndHost() { $request = new Request('HEAD', '/resource/123', 'http://example.com'); $this->assertEquals($request->getMethod(), 'HEAD'); $this->assertEquals($request->getResource(), '/resource/123'); $this->assertEquals($request->getHost(), 'http://example.com'); }
public function modder($dash, $id, $mode) { if (Request::getMethod() == 'GET') { switch ($mode) { case 'delete': $validator = Validator::make(['id' => $id], ['id' => 'required|exists:subjects,id']); if ($validator->fails()) { return Redirect::to(URL::previous()); } self::delete($id); return Redirect::to(URL::previous()); case 'update': $validator = Validator::make(['id' => $id], ['id' => 'required|exists:subjects,id']); if ($validator->fails()) { return Redirect::to(URL::previous()); } $theme = Theme::uses('dashboard')->layout('default'); $view = ['id' => $id]; $theme->setTitle(Setting::get('system.adminsitename') . ' Subjects'); $theme->breadcrumb()->add([['label' => 'Dashboard', 'url' => Setting::get('system.dashurl')], ['label' => 'Subjects', 'url' => Setting::get('system.dashurl') . '/subjects'], ['label' => $id, 'url' => Setting::get('system.dashurl') . '/subject/edit/' . $id . '/update']]); return $theme->scope('subject.update', $view)->render(); case 'view': $validator = Validator::make(['id' => $id], ['id' => 'required|exists:subjects,id']); if ($validator->fails()) { return Redirect::to(URL::previous()); } $theme = Theme::uses('dashboard')->layout('default'); $view = ['id' => $id]; $theme->setTitle(Setting::get('system.adminsitename') . ' Subjects'); $theme->breadcrumb()->add([['label' => 'Dashboard', 'url' => Setting::get('system.dashurl')], ['label' => 'Subjects', 'url' => Setting::get('system.dashurl') . '/subjects'], ['label' => $id, 'url' => Setting::get('system.dashurl') . '/subject/edit/' . $id . '/update']]); return $theme->scope('subject.view', $view)->render(); case 'create': $theme = Theme::uses('dashboard')->layout('default'); $view = ['id' => 0]; $theme->setTitle(Setting::get('system.adminsitename') . ' Subjects'); $theme->breadcrumb()->add([['label' => 'Dashboard', 'url' => Setting::get('system.dashurl')], ['label' => 'Subjects', 'url' => Setting::get('system.dashurl') . '/subjects'], ['label' => $id, 'url' => Setting::get('system.dashurl') . '/subject/edit/0/update']]); return $theme->scope('subject.create', $view)->render(); default: return "UNAUTHORISED METHOD"; break; } } if (Request::getMethod() == 'POST') { switch ($mode) { case 'update': self::update($id); return Redirect::to('/subjects'); case 'create': if ($id == 0) { self::create(); return Redirect::to('/subjects'); } return Redirect::to(URL::previous()); default: Log::error('UnAuthorised Access at Subjects Page.'); return Redirect::to('dash'); } } }
/** Sets the response in corcondance with the given request. */ function prepare(Request $req) : self { $res = clone $this; if ($req->getMethod() === 'HEAD') { $res->body = null; } return $res; }
public static function validate($data) { if (Request::getMethod() == 'PUT') { $id = $data['id']; self::$rules['pergunta'] .= ",{$id}"; } return Validator::make($data, self::$rules); }
/** * {@inheritdoc} */ public function writeResponse(Socket $socket, Response $response, Request $request = null, float $timeout = 0) : \Generator { $written = (yield from $socket->write($this->encoder->encodeResponse($response))); $stream = $response->getBody(); if ((!isset($request) || $request->getMethod() !== 'HEAD') && $stream->isReadable()) { $written += (yield from Stream\pipe($stream, $socket, false, 0, null, $timeout)); } return $written; }
public function matches(Request $request) { if (in_array($request->getMethod(), $this->methods)) { if (preg_match($this->pattern, $request->getPath(), $matches)) { return $matches; } } return false; }
/** * Checks if the request method is POST * * @return bool Returns true if the request method is POST otherwise returns false */ public static function isMethodPost() : bool { try { $method = Request::getMethod(); } catch (\OutOfBoundsException $e) { return false; } return $method == Request::METHOD_POST; }
/** * Makes a request. * * @param Request $request A Request instance * * @return Response A Response instance */ protected function doRequest($request) { curl_setopt($this->curl, CURLOPT_URL, $request->getUri()); curl_setopt($this->curl, CURLOPT_POSTFIELDS, $request->getParameters()); curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, $request->getMethod()); curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, 1); $content = curl_exec($this->curl); $this->assertCurlError(); $requestInfo = curl_getinfo($this->curl); return new Response($content, $requestInfo['http_code']); }