Extends the Request definition to add methods for accessing incoming data, specifically server parameters, cookies, matched path parameters, query string arguments, body parameters, and upload file information. "Attributes" are discovered via decomposing the request (and usually specifically the URI path), and typically will be injected by the application. Requests are considered immutable; all methods that might change state are implemented such that they retain the internal state of the current message and return a new instance that contains the changed state.
Inheritance: implements Psr\Http\Message\ServerRequestInterface, use trait MessageTrait, use trait RequestTrait
 /**
  * Check user session login
  *
  * @param Request $request
  * @param Response $response
  * @return bool|Response
  */
 public static function check(Request $request, Response $response, $action, $callback)
 {
     /* @var $app AppContainer */
     $app = $request->getAttribute(\App\Middleware\AppMiddleware::ATTRIBUTE);
     if (!static::isAuthRequired($app, $action)) {
         return true;
     }
     $userSession = new UserSession($app);
     if ($userSession->isValid()) {
         return true;
     } else {
         $http = new \App\Util\Http($request, $response);
         if ($http->isJsonRpc()) {
             $json = new \App\Util\JsonServer($request, $response);
             $jsonContent = $json->getResponseByError('Unauthorized', 0, 0, 401);
             return $jsonContent;
         } else {
             $uri = $app->http->getBaseUrl('/login');
             return new RedirectResponse($uri);
             // alternative would be
             // new HtmlResponse('401 Unauthorized', 401);
         }
     }
     return true;
 }
 /**
  * Action (JsonRpc)
  *
  * @param Request $request
  * @param Response $response
  * @return mixed
  */
 public function load(Request $request = null, Response $response = null)
 {
     $json = $request->getAttribute('json');
     $params = value($json, 'params');
     $result = ['status' => 1];
     return $result;
 }
Beispiel #3
0
 /**
  * Shoppingcart constructor.
  * @param \Zend\ServiceManager\ServiceManager $serviceManager
  */
 public function __construct(\Zend\ServiceManager\ServiceManager $serviceManager)
 {
     parent::__construct($serviceManager);
     $this->request = $this->serviceManager->get('request');
     $this->textcats = $this->serviceManager->get('textcats');
     $this->get = $this->request->getQueryParams();
     $this->post = $this->request->getParsedBody();
 }
Beispiel #4
0
 /**
  * Pageadmin constructor.
  * @param ServiceManager $serviceManager
  */
 public function __construct(ServiceManager $serviceManager)
 {
     parent::__construct($serviceManager);
     /** @var \Zend\Diactoros\ServerRequest request */
     $this->request = $serviceManager->get('request');
     $this->post = $this->request->getParsedBody();
     $this->get = $this->request->getQueryParams();
 }
Beispiel #5
0
 public function getData(Request $request, array $data = null)
 {
     $result = ['baseurl' => $request->getAttribute('base_url')];
     if (!empty($data)) {
         $result = array_replace_recursive($result, $data);
     }
     return $result;
 }
Beispiel #6
0
 public function hello($name, ServerRequest $request)
 {
     $body = "hello {$name}";
     if (isset($request->getQueryParams()['upper'])) {
         $body = strtoupper($body);
     }
     return new HtmlResponse($body);
 }
 /**
  * Create a request from the supplied superglobal values.
  *
  * If any argument is not supplied, the corresponding superglobal value will
  * be used.
  *
  * The ServerRequest created is then passed to the fromServer() method in
  * order to marshal the request URI and headers.
  *
  * @see fromServer()
  * @param array $server $_SERVER superglobal
  * @param array $query $_GET superglobal
  * @param array $body $_POST superglobal
  * @param array $cookies $_COOKIE superglobal
  * @param array $files $_FILES superglobal
  * @return ServerRequest
  * @throws InvalidArgumentException for invalid file values
  */
 public static function fromGlobals(array $server = null, array $query = null, array $body = null, array $cookies = null, array $files = null)
 {
     $server = static::normalizeServer($server ?: $_SERVER);
     $files = static::normalizeFiles($files ?: $_FILES);
     $headers = static::marshalHeaders($server);
     $request = new ServerRequest($server, $files, static::marshalUriFromServer($server, $headers), static::get('REQUEST_METHOD', $server, 'GET'), 'php://input', $headers);
     return $request->withCookieParams($cookies ?: $_COOKIE)->withQueryParams($query ?: $_GET)->withParsedBody($body ?: $_POST);
 }
 public function testResourceIdRelationIdRequest()
 {
     $request = $this->request->withUri(new Uri('http://localhost/api/ping/1/comments/1'))->withMethod('GET');
     $response = $this->app->__invoke($request, new Response());
     $data = json_decode((string) $response->getBody(), true);
     $this->assertEquals(200, $response->getStatusCode());
     $this->assertArrayHasKey('ack', $data);
 }
 public function testServerParams()
 {
     $swooleRequest = $this->createSwooleRequest(array('request_method' => 'GET', 'request_uri' => '/', 'path_info' => '/', 'request_time' => 123456789, 'server_port' => 9100, 'remote_port' => 49648, 'remote_addr' => '127.0.0.1', 'server_protocol' => 'HTTP/1.1', 'server_software' => 'swoole-http-server'), array('authorization' => 'Basic dXNlcm5hbWU6cGFzc3dvcmQ=', 'host' => 'syrma.local', 'connection' => 'close', 'user-agent' => 'curl/7.35.0', 'accept' => '*/*'));
     $request = $this->createTransformer()->transform($swooleRequest);
     $expServerParams = new ServerRequest(ServerRequestFactory::normalizeServer(array('REQUEST_METHOD' => 'GET', 'REQUEST_URI' => '/', 'PATH_INFO' => '/', 'REQUEST_TIME' => 123456789, 'SERVER_PORT' => 9100, 'REMOTE_PORT' => 49648, 'REMOTE_ADDR' => '127.0.0.1', 'SERVER_PROTOCOL' => 'HTTP/1.1', 'SERVER_SOFTWARE' => 'swoole-http-server', 'HTTP_AUTHORIZATION' => 'Basic dXNlcm5hbWU6cGFzc3dvcmQ=', 'HTTP_HOST' => 'syrma.local', 'HTTP_CONNECTION' => 'close', 'HTTP_USER-AGENT' => 'curl/7.35.0', 'HTTP_ACCEPT' => '*/*')));
     $this->assertInstanceOf(ServerRequest::class, $request);
     /* @var  ServerRequest $request */
     $this->assertSame($expServerParams->getServerParams(), $request->getServerParams());
 }
 public function testDecoratorProxiesToAllMethods()
 {
     $stream = $this->getMockBuilder('Psr\\Http\\Message\\StreamInterface')->getMock();
     $psrRequest = new PsrRequest([], [], 'http://example.com', 'POST', $stream, ['Accept' => 'application/xml', 'X-URL' => 'http://example.com/foo']);
     $request = new Request($psrRequest);
     $this->assertEquals('1.1', $request->getProtocolVersion());
     $this->assertSame($stream, $request->getBody());
     $this->assertSame($psrRequest->getHeaders(), $request->getHeaders());
     $this->assertEquals($psrRequest->getRequestTarget(), $request->getRequestTarget());
 }
 public function testServerParams()
 {
     $reactRequest = $this->createReactRequest('GET', '/', array(), '1.1', array('Host' => 'syrma.local', 'Connection' => 'close', 'User-Agent' => 'curl/7.35.0', 'Accept' => '*/*', 'Authorization' => 'Basic dXNlcm5hbWU6cGFzc3dvcmQ='));
     $reactRequest->remoteAddress = '127.0.0.1';
     $request = $this->createTransformer()->transform($reactRequest);
     $expServerParams = new ServerRequest(ServerRequestFactory::normalizeServer(array('REQUEST_METHOD' => 'GET', 'REQUEST_URI' => '/', 'SERVER_PROTOCOL' => 'HTTP/1.1', 'SERVER_SOFTWARE' => 'reactphp-http', 'REMOTE_ADDR' => '127.0.0.1', 'HTTP_AUTHORIZATION' => 'Basic dXNlcm5hbWU6cGFzc3dvcmQ=', 'HTTP_HOST' => 'syrma.local', 'HTTP_CONNECTION' => 'close', 'HTTP_USER-AGENT' => 'curl/7.35.0', 'HTTP_ACCEPT' => '*/*')));
     $this->assertInstanceOf(ServerRequest::class, $request);
     /* @var  ServerRequest $request */
     $this->assertEquals($expServerParams->getServerParams(), $request->getServerParams());
 }
 /**
  * Compress content
  *
  * @return Response
  */
 public function compress(Request $request, Response $response)
 {
     $acceptEncoding = $request->getHeaderLine('accept-encoding');
     $encodings = array_flip(trim_array(explode(',', $acceptEncoding)));
     if (isset($encodings['gzip'])) {
         return $this->compressBody($response, 'gzip', 'gzcompress');
     }
     if (isset($encodings['deflate'])) {
         return $this->compressBody($response, 'deflate', 'gzdeflate');
     }
     return $response;
 }
 /**
  * @param $resourceName
  * @param $primaryKey
  * @dataProvider testResourceResolverWhirRoutDataProvider
  */
 public function testResourceResolver__invokeWithRouting($resourceName, $primaryKey)
 {
     $this->request = new ServerRequest([], []);
     $this->request = $this->request->withAttribute("resourceName", $resourceName);
     $this->request = $this->request->withAttribute("id", $primaryKey);
     $this->next = function ($req, $resp) {
         return $req;
     };
     $responseResolver = $this->object->__invoke($this->request, $this->response, $this->next);
     $this->assertEquals($responseResolver->getAttribute('Resource-Name'), $resourceName);
     $this->assertEquals($responseResolver->getAttribute('Primary-Key-Value'), $primaryKey);
 }
 /**
  * Create instance
  *
  * @return Engine
  */
 public function create(Request $request)
 {
     $engine = new Engine($this->options['view_path'], null);
     // Add folder shortcut (assets::file.js)
     $engine->addFolder('assets', $this->options['assets_path']);
     $engine->addFolder('view', $this->options['view_path']);
     $session = $request->getAttribute(SessionMiddleware::ATTRIBUTE);
     $baseUrl = $request->getAttribute('base_url');
     // Register Asset extension
     $cacheOptions = array('cachepath' => $this->options['cache_path'], 'cachekey' => $session->get('user.locale'), 'baseurl' => $baseUrl, 'minify' => $this->options['minify']);
     $engine->loadExtension(new \Odan\Plates\Extension\AssetCache($cacheOptions));
     return $engine;
 }
 public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
 {
     if ($request->getMethod() === 'POST') {
         $parsedBody = $this->parseBody($request->getBody());
         if (is_array($parsedBody) && isset($parsedBody[self::PARAM])) {
             $requestToSimulate = $parsedBody[self::PARAM];
             $deserializedRequest = RequestSerializer::fromString($requestToSimulate);
             $request = new ServerRequest($request->getServerParams(), $request->getUploadedFiles(), $deserializedRequest->getUri(), $deserializedRequest->getMethod(), $deserializedRequest->getBody(), $deserializedRequest->getHeaders());
         }
     }
     $requestAsString = RequestSerializer::toString($request);
     $responseResult = $next($request, $response);
     $responseAsString = ResponseSerializer::toString($responseResult);
     $html = sprintf($this->getHtmlTemplate(), self::PARAM, $requestAsString, $responseAsString);
     return new HtmlResponse($html);
 }
 /**
  * Returns the url path leading up to the current script.
  * Used to make the webapp portable to other locations.
  *
  * @return string uri
  */
 public function getBaseUri(Request $request)
 {
     // Get URI from URL
     $uri = $request->getUri()->getPath();
     // Detect and remove subfolder from URI
     $server = $request->getServerParams();
     $scriptName = $server['SCRIPT_NAME'];
     if (isset($scriptName)) {
         $dirname = dirname($scriptName);
         $dirname = dirname($dirname);
         $len = strlen($dirname);
         if ($len > 0 && $dirname != '/') {
             $uri = substr($uri, $len);
         }
     }
     return $uri;
 }
 /**
  * Handle an exception and generate an error response.
  *
  * @param Exception $ex The exception to handle.
  * @param Request $request The request.
  * @param Response $response The response.
  * @return Response A response
  */
 public function handleException(Exception $ex, Request $request, Response $response)
 {
     $message = sprintf("[%s] %s\n%s", get_class($ex), $ex->getMessage(), $ex->getTraceAsString());
     // Must be PSR logger (Monolog)
     $logger = $request->getAttribute(\App\Middleware\LoggerMiddleware::ATTRIBUTE);
     if (!empty($logger)) {
         $logger->error($message);
     }
     $stream = new Stream('php://temp', 'wb+');
     $stream->write('An Internal Server Error Occurred');
     // Verbose error output
     if (!empty($this->config['verbose'])) {
         $stream->write("\n<br>{$message}");
     }
     $response = $response->withStatus(500)->withBody($stream);
     return $response;
 }
 public function testDeleteUnknownUser()
 {
     $uuid = 'badfdcad-1ad5-42fb-8da6-4a2db08c6941';
     $request = $this->request->withUri(new Uri(sprintf('http://localhost/api/users/%s', $uuid)))->withMethod('DELETE');
     $response = $this->app->__invoke($request, new Response());
     $data = json_decode((string) $response->getBody(), true);
     $this->assertEquals(404, $response->getStatusCode());
     $this->assertEquals('application/json', $response->getHeaderLine('Content-Type'));
     $this->assertArrayHasKey('errors', $data);
 }
Beispiel #19
0
 /**
  * Edit
  *
  * @param Request $request
  * @param Response $response
  * @return Response
  */
 public function edit(Request $request = null, Response $response = null)
 {
     // All GET parameters
     $queryParams = $request->getQueryParams();
     // All POST or PUT parameters
     $postParams = $request->getParsedBody();
     // Single GET parameter
     //$title = $queryParams['title'];
     //
     // Single POST/PUT parameter
     //$data = $postParams['data'];
     //
     // Get routing arguments
     $vars = $request->getAttribute('vars');
     $id = $vars['id'];
     // Get config value
     $app = $this->app($request);
     $env = $app->config['env']['name'];
     // Get GET parameter
     $id = $app->http->get('id');
     // Increment counter
     $counter = $app->session->get('counter', 0);
     $counter++;
     $app->session->set('counter', $counter);
     $app->logger->info('My log message');
     // Set locale
     //$app->session->set('user.locale', 'de_DE');
     //
     //Model example
     //$user = new \App\Model\User($app);
     //$userRows = $user->getAll();
     //$userRow = $user->getById($id);
     //
     // Add data to template
     $data = $this->getData($request, ['id' => $id, 'assets' => $this->getAssets(), 'content' => 'view::User/html/edit.html.php']);
     // Render template
     $content = $app->view->render('view::Layout/html/layout.html.php', $data);
     // Return new response
     $response->getBody()->write($content);
     return $response;
 }
 public function testNotEmmitRequestIdToResponse()
 {
     $requestIdProviderFactory = $this->getMock(RequestIdProviderFactoryInterface::class);
     $requestIdProvider = $this->getMock(RequestIdProviderInterface::class);
     $requestIdProviderFactory->method('create')->willReturn($requestIdProvider);
     $requestIdProvider->method('getRequestId')->willReturn('123456789');
     $middleware = new RequestIdMiddleware($requestIdProviderFactory, null);
     $request = new ServerRequest();
     $response = new Response();
     $calledOut = false;
     $outFunction = function ($request, $response) use(&$calledOut) {
         $calledOut = true;
         $this->assertSame('123456789', $request->getAttribute(RequestIdMiddleware::ATTRIBUTE_NAME));
         return $response;
     };
     $result = call_user_func($middleware, $request, $response, $outFunction);
     $this->assertTrue($calledOut, 'Out is not called');
     $this->assertSame($response, $result);
     $this->assertEquals(null, $result->getHeaderLine(RequestIdProvider::DEFAULT_REQUEST_HEADER));
     $this->assertSame('123456789', $middleware->getRequestId());
 }
 public function testSimulateRequest()
 {
     $simulatedRequest = "DELETE / HTTP/1.1\r\nBar: faz\r\nHost: php-middleware.com";
     $postBody = http_build_query([RequestSimulatorMiddleware::PARAM => $simulatedRequest]);
     $stream = new Stream('php://memory', 'wb+');
     $stream->write($postBody);
     $request = new ServerRequest([], [], new Uri(), 'POST', $stream, ['Content-type' => 'application/x-www-form-urlencoded']);
     $responseBody = json_encode(['boo' => 'foo']);
     $response = new Response('php://memory', 200, ['content-type' => 'application/json']);
     $response->getBody()->write($responseBody);
     $next = function (ServerRequestInterface $request, ResponseInterface $response) {
         $this->assertSame('DELETE', $request->getMethod());
         $this->assertSame('faz', $request->getHeaderLine('Bar'));
         return $response;
     };
     /* @var $result ResponseInterface */
     $result = call_user_func($this->middleware, $request, $response, $next);
     $body = (string) $result->getBody();
     $this->assertContains('text/html', $result->getHeaderLine('Content-type'));
     $this->assertContains('{"boo":"foo"}', $body);
     $this->assertContains('<html>', $body);
     $this->assertContains('DELETE / HTTP/1.1', $body);
 }
Beispiel #22
0
 /**
  * {@inheritdoc}
  */
 public static function fromGlobals(array $server = null, array $query = null, array $body = null, array $cookies = null, array $files = null)
 {
     $server = static::normalizeServer($server ?: $_SERVER);
     $files = static::normalizeFiles($files ?: $_FILES);
     $headers = static::marshalHeaders($server);
     $request = new ServerRequest($server, $files, static::marshalUriFromServer($server, $headers), static::get('REQUEST_METHOD', $server, 'GET'), 'php://input', $headers);
     $contentType = current($request->getHeader('Content-Type'));
     $input = file_get_contents('php://input');
     // support header like "application/json" and "application/json; charset=utf-8"
     if ($contentType !== false && stristr($contentType, 'application/json')) {
         $data = (array) json_decode($input);
     } else {
         switch ($request->getMethod()) {
             case 'POST':
                 $data = $_POST;
                 break;
             default:
                 parse_str($input, $data);
                 break;
         }
     }
     return $request->withCookieParams($cookies ?: $_COOKIE)->withQueryParams($query ?: $_GET)->withParsedBody($body ?: $data);
 }
Beispiel #23
0
 /**
  * Create instance
  *
  * @return AppContainer
  */
 public function create(Request $request)
 {
     $app = new \App\Container\AppContainer();
     $app->config = $this->config;
     $app->logger = $request->getAttribute(LoggerMiddleware::ATTRIBUTE);
     $app->session = $request->getAttribute(SessionMiddleware::ATTRIBUTE);
     $app->translator = $request->getAttribute(TranslatorMiddleware::ATTRIBUTE);
     $app->db = $request->getAttribute(CakeDatabaseMiddleware::ATTRIBUTE);
     $app->view = $request->getAttribute(PlatesMiddleware::ATTRIBUTE);
     $app->http = $request->getAttribute(HttpMiddleware::ATTRIBUTE);
     $app->user = new \App\Service\User\UserSession($app);
     $app->user->setLocale($app->user->getLocale());
     return $app;
 }
Beispiel #24
0
 /**
  * @return mixed|null
  */
 public function getRoute()
 {
     $this->_routeMap->sortRoutes();
     foreach ($this->_routeMap as $route) {
         if ($this->_request->getMethod() !== $route->getRequestMethod()) {
             continue;
         }
         $route->replaceTokens();
         if (preg_match(sprintf("#^%s\$#i", $route->getPattern()), $this->_request->getUri()->getPath(), $matches)) {
             $this->_request = $this->_request->withAttribute('match', $route->getPattern());
             foreach ($matches as $key => $value) {
                 if (!is_int($key)) {
                     $this->_request = $this->_request->withAttribute($key, $value);
                 }
             }
             return $route;
         }
     }
     return null;
 }
Beispiel #25
0
 /**
  * @param string $name
  * @param mixed  $default
  *
  * @return array|string
  */
 protected function getQueryParam($name, $default = null)
 {
     return isset($this->request->getQueryParams()[$name]) ? $this->request->getQueryParams()[$name] : $default;
 }
 private function makeRequestWithAccept($acceptHeader)
 {
     $request = new ServerRequest();
     return $request->withHeader('accept', $acceptHeader);
 }
Beispiel #27
0
 /**
  * @param CookieJar $jar
  * @param array     $serverParams
  * @param array     $uploadedFiles
  * @param null      $uri
  * @param null      $method
  * @param string    $body
  * @param array     $headers
  */
 public function __construct(CookieJar $jar = null, array $serverParams = [], array $uploadedFiles = [], $uri = null, $method = null, $body = 'php://input', array $headers = [])
 {
     parent::__construct($serverParams, $uploadedFiles, $uri, $method, $body, $headers);
     $this->cookieJar = $jar ?: new CookieJar();
 }
 protected function request($uri = '', array $headers = [], array $server = [])
 {
     $request = new ServerRequest($server, [], $uri, null, 'php://temp', $headers);
     return $request->withUri(new Uri($uri));
 }
 /**
  * Create
  *
  * @return Request Request
  */
 public static function fromRequest(ServerRequest $request)
 {
     return new HttpMessages_CraftRequest($request->getServerParams(), $request->getUploadedFiles(), $request->getUri(), $request->getMethod(), $request->getBody(), $request->getHeaders(), $request->getCookieParams(), $request->getQueryParams(), $request->getParsedBody(), $request->getProtocolVersion());
 }
 public function testDontGenerateBecouseHeaderExists()
 {
     $this->generator->expects($this->never())->method('generateRequestId');
     $middleware = new RequestIdMiddleware($this->generator);
     $request = new ServerRequest([], [], 'https://github.com/php-middleware/request-id', 'GET', 'php://input', [RequestIdMiddleware::DEFAULT_HEADER_REQUEST_ID => '987654321']);
     $response = new Response();
     $calledOut = false;
     $outFunction = function ($request, $response) use(&$calledOut) {
         $calledOut = true;
         $this->assertSame('987654321', $request->getAttribute(RequestIdMiddleware::ATTRIBUTE_NAME));
         return $response;
     };
     $result = call_user_func($middleware, $request, $response, $outFunction);
     $this->assertTrue($calledOut, 'Out is not called');
     $this->assertNotSame($response, $result);
     $this->assertEquals('987654321', $result->getHeaderLine(RequestIdMiddleware::DEFAULT_HEADER_REQUEST_ID));
     $this->assertSame('987654321', $middleware->getRequestId());
 }