public function testWritePlain() { $this->_jsonTestOutputWriter->expects($this->exactly(1))->method('_jsonEncode')->with($this->equalTo(array('mockKey' => 'mockValue')))->will($this->returnValue('{"mockKey": "mockValue"}')); $this->_mockHeaders->expects($this->exactly(1))->method('set')->with($this->equalTo('Content-Type'), $this->equalTo('application/json; charset=UTF-8')); $this->_mockResponse->expects($this->exactly(1))->method('setStatus')->with($this->equalTo(200)); $this->_mockResponse->expects($this->exactly(1))->method('setBody')->with($this->equalTo('{"mockKey": "mockValue"}')); $this->_jsonTestOutputWriter->writePlain(array('mockKey' => 'mockValue')); }
/** * @param $data * * @dataProvider normalizeAllDataProvider */ public function testWriteArray($data) { $localCsvTestOutputWriter = $this->getMock('\\SlimBootstrap\\ResponseOutputWriter\\Csv', array('_csvEncode'), array($this->_mockRequest, $this->_mockResponse, $this->_mockHeaders, 'mockShortName')); $this->_mockHeaders->expects($this->once())->method('set')->with($this->identicalTo("Content-Type"), $this->identicalTo("text/csv; charset=UTF-8")); $this->_mockResponse->expects($this->once())->method('setStatus')->with($this->equalTo(200)); $localCsvTestOutputWriter->expects($this->once())->method('_csvEncode'); $this->_mockResponse->expects($this->once())->method('setBody'); $localCsvTestOutputWriter->write($data, 200); }
/** * Run before each test. */ public function setUp() { $uri = Uri::createFromString('https://example.com:443/foo/bar'); $headers = new Headers(); $headers->set('REMOTE_ADDR', '127.0.0.1'); $cookies = []; $env = Environment::mock(); $serverParams = $env->all(); $body = new Body(fopen('php://temp', 'r+')); $this->request = new Request('GET', $uri, $headers, $cookies, $serverParams, $body); $this->response = new Response(); }
/** * Setup for the XML POST requests. * * @param string $xml The XML to use to mock the body of the request. */ public function setUpXmlPost($xml) { $uri = Uri::createFromString('https://example.com:443/foo'); $headers = new Headers(); $headers->set('Content-Type', 'application/xml;charset=utf8'); $cookies = []; $env = Environment::mock(['SCRIPT_NAME' => '/index.php', 'REQUEST_URI' => '/foo', 'REQUEST_METHOD' => 'POST']); $serverParams = $env->all(); $body = new RequestBody(); $body->write($xml); $this->request = new Request('POST', $uri, $headers, $cookies, $serverParams, $body); $this->response = new Response(); }
private function request($method, $path, $data = array(), $optionalHeaders = array()) { //Make method uppercase $method = strtoupper($method); $options = array('REQUEST_METHOD' => $method, 'REQUEST_URI' => $path); if ($method === 'GET') { $options['QUERY_STRING'] = http_build_query($data); } else { $params = json_encode($data); } // Prepare a mock environment $env = Environment::mock(array_merge($options, $optionalHeaders)); $uri = Uri::createFromEnvironment($env); $headers = Headers::createFromEnvironment($env); $cookies = $this->cookies; $serverParams = $env->all(); $body = new RequestBody(); // Attach JSON request if (isset($params)) { $headers->set('Content-Type', 'application/json;charset=utf8'); $body->write($params); } $this->request = new Request($method, $uri, $headers, $cookies, $serverParams, $body); $response = new Response(); // Invoke request $app = $this->app; $this->response = $app($this->request, $response); // Return the application output. return (string) $this->response->getBody(); }
protected function dispatch($path, $method = 'GET', $data = array(), $cookies = array()) { $container = $this->app->getContainer(); // seperate the path from the query string so we can set in the environment @(list($path, $queryString) = explode('?', $path)); // Prepare a mock environment $env = Environment::mock(array('REQUEST_URI' => $path, 'REQUEST_METHOD' => $method, 'QUERY_STRING' => is_null($queryString) ? '' : $queryString)); // Prepare request and response objects $uri = Uri::createFromEnvironment($env); $headers = Headers::createFromEnvironment($env); $cookies = $cookies; $serverParams = $env->all(); $body = new RequestBody(); // create request, and set params $req = new $container['request']($method, $uri, $headers, $cookies, $serverParams, $body); if (!empty($data)) { $req = $req->withParsedBody($data); } $res = new $container['response'](); // // Fix for body, but breaks POST params in tests - http://stackoverflow.com/questions/34823328/response-getbody-is-empty-when-testing-slim-3-routes-with-phpunit // $body = new RequestBody(); // if (!empty($data)) // $body->write(json_encode($data)); // // // create request, and set params // $req = new $container['request']($method, $uri, $headers, $cookies, $serverParams, $body); // $res = new $container['response'](); $this->headers = $headers; $this->request = $req; $this->response = call_user_func_array($this->app, array($req, $res)); }
/** * This function outputs the given $data as valid HAL+JSON to the client * and sets the HTTP Response Code to the given $statusCode. * * @param array|SlimBootstrap\DataObject $data The data to output to * the client * @param int $statusCode The status code to set * in the reponse */ public function write($data, $statusCode = 200) { $path = $this->_request->getPath(); $hal = new hal\Hal($path); if (true === is_array($data)) { $pathData = explode('/', $path); unset($pathData[0]); $endpointName = end($pathData); $endpointUri = '/' . implode('/', $pathData) . '/'; foreach ($data as $entry) { /** @var SlimBootstrap\DataObject $entry */ $identifiers = $entry->getIdentifiers(); $resourceName = $endpointUri . implode('/', array_values($identifiers)); $resource = new hal\Hal($resourceName, $entry->getData() + $entry->getIdentifiers()); $this->_addAdditionalLinks($resource, $entry->getLinks()); $hal->addLink($endpointName, $resourceName); $hal->addResource($endpointName, $resource); } } else { $hal->setData($data->getData() + $data->getIdentifiers()); $this->_addAdditionalLinks($hal, $data->getLinks()); } $body = $this->_jsonEncode($hal); if (false === $body) { $this->_response->setStatus(500); $this->_response->setBody("Error encoding requested data."); return; } $this->_headers->set('Content-Type', 'application/hal+json; charset=UTF-8'); $this->_response->setStatus($statusCode); $this->_response->setBody($hal->asJson()); }
/** * Constructor (private access) * * @param array|null $settings If present, these are used instead of global server variables */ private function __construct($settings = null) { if ($settings) { $this->properties = $settings; } else { $env = array(); //The HTTP request method $env['REQUEST_METHOD'] = $_SERVER['REQUEST_METHOD']; //The IP $env['REMOTE_ADDR'] = $_SERVER['REMOTE_ADDR']; // Server params $scriptName = $_SERVER['SCRIPT_NAME']; // <-- "/foo/index.php" $requestUri = $_SERVER['REQUEST_URI']; // <-- "/foo/bar?test=abc" or "/foo/index.php/bar?test=abc" $queryString = isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : ''; // <-- "test=abc" or "" // Physical path if (strpos($requestUri, $scriptName) !== false) { $physicalPath = $scriptName; // <-- Without rewriting } else { $physicalPath = str_replace('\\', '', dirname($scriptName)); // <-- With rewriting } $env['SCRIPT_NAME'] = rtrim($physicalPath, '/'); // <-- Remove trailing slashes $env['PATH_INFO'] = !empty($requestUri) && !empty($physicalPath) && strpos($requestUri, $physicalPath) === 0 ? substr_replace($requestUri, '', 0, strlen($physicalPath)) : $requestUri; // <-- Remove physical path $env['PATH_INFO'] = str_replace('?' . $queryString, '', $env['PATH_INFO']); // <-- Remove query string $env['PATH_INFO'] = '/' . ltrim($env['PATH_INFO'], '/'); // <-- Ensure leading slash // Query string (without leading "?") $env['QUERY_STRING'] = $queryString; //Name of server host that is running the script $env['SERVER_NAME'] = $_SERVER['SERVER_NAME']; //Number of server port that is running the script $env['SERVER_PORT'] = $_SERVER['SERVER_PORT']; //HTTP request headers (retains HTTP_ prefix to match $_SERVER) $headers = \Slim\Http\Headers::extract($_SERVER); foreach ($headers as $key => $value) { $env[$key] = $value; } //Is the application running under HTTPS or HTTP protocol? $env['slim.url_scheme'] = empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] === 'off' ? 'http' : 'https'; //Input stream (readable one time only; not available for multipart/form-data requests) $rawInput = @file_get_contents('php://input'); if (!$rawInput) { $rawInput = ''; } $env['slim.input'] = $rawInput; //Error stream $env['slim.errors'] = @fopen('php://stderr', 'w'); // print_r($env); die; $this->properties = $env; } }
protected function createRequest($env) { $method = $env["REQUEST_METHOD"]; $uri = Uri::createFromEnvironment($env); $headers = Headers::createFromEnvironment($env); $cookies = Cookies::parseHeader($headers->get("Cookie", [])); $serverParams = $env->all(); $body = new Body(fopen("php://input", "r")); return new Request($method, $uri, $headers, $cookies, $serverParams, $body); }
/** * Creates a new request object from the data of a reactPHP request object * * @param \React\Http\Request $request ReactPHP native request object * * @return \Slim\Http\Request */ public static function createFromReactRequest(\React\Http\Request $request) { $slimHeads = new Headers(); foreach ($request->getHeaders() as $reactHeadKey => $reactHead) { $slimHeads->add($reactHeadKey, $reactHead); if ($reactHeadKey === 'Host') { $host = explode(':', $reactHead); if (count($host) === 1) { $host[1] = '80'; } } } $slimUri = new Uri('http', $host[0], (int) $host[1], $request->getPath(), $request->getQuery()); $cookies = []; $serverParams = $_SERVER; $serverParams['SERVER_PROTOCOL'] = 'HTTP/' . $request->getHttpVersion(); $slimBody = new RequestBody(); return new self($request->getMethod(), $slimUri, $slimHeads, $cookies, $serverParams, $slimBody); }
/** * @param $method * @param string $url * * @return Request */ public function makeRequest($method, $url = '/') { $env = Environment::mock(); $uri = Uri::createFromString('http://example.com' . $url); $headers = Headers::createFromEnvironment($env); $serverParams = $env->all(); $body = new RequestBody(); $uploadedFiles = UploadedFile::createFromEnvironment($env); $request = new Request($method, $uri, $headers, [], $serverParams, $body, $uploadedFiles); return $request; }
/** * @param DataObject $entry * @param int $statusCode - default 200, is only set at first method call */ public function writeToStream(SlimBootstrap\DataObject $entry, $statusCode = 200) { if (true === $this->_firstCall) { $this->_headers->set('Content-Type', 'text/csv; charset=UTF-8'); $this->_response->setStatus($statusCode); echo $this->_determineHeadline(array($entry)); $this->_firstCall = false; } echo $this->_buildCsvLineFromDataSet($entry->getData(), $this->_multidimensionalFields, $this->_lastFieldName, $this->_encloseAll) . $this->_linebreak; $this->_flush(); }
public function requestFactory($acceptType = 'application/json') { $env = Environment::mock(['HTTP_ACCEPT' => $acceptType]); $uri = Uri::createFromString('https://example.com:443/foo/bar?abc=123'); $headers = Headers::createFromEnvironment($env); $serverParams = $env->all(); $body = new RequestBody(); $uploadedFiles = UploadedFile::createFromEnvironment($env); $request = new Request('GET', $uri, $headers, [], $serverParams, $body, $uploadedFiles); return $request; }
protected function createRequest() { $env = (new Environment())->mock(["PATH_INFO" => "/index/hello/", "SCRIPT_NAME" => "/index.php"]); $method = $env["REQUEST_METHOD"]; $uri = Uri::createFromEnvironment($env); $headers = Headers::createFromEnvironment($env); $cookies = Cookies::parseHeader($headers->get("Cookie", [])); $serverParams = $env->all(); $body = new Body(fopen("php://input", "r")); return new Request($method, $uri, $headers, $cookies, $serverParams, $body); }
public function requestFactory($queryString = '') { $env = Environment::mock(); $uri = Uri::createFromString('https://example.com:443/foo/bar' . $queryString); $headers = Headers::createFromEnvironment($env); $cookies = ['user' => 'john', 'id' => '123']; $serverParams = $env->all(); $body = new RequestBody(); $uploadedFiles = UploadedFile::createFromEnvironment($env); $request = new Request('GET', $uri, $headers, $cookies, $serverParams, $body, $uploadedFiles); return $request; }
public function setRequest($method = 'GET', $uri = '/', $other = []) { // Prepare request and response objects $base = ['SCRIPT_NAME' => '/index.php', 'REQUEST_URI' => $uri, 'REQUEST_METHOD' => $method]; $env = \Slim\Http\Environment::mock(array_merge($base, $other)); $uri = \Slim\Http\Uri::createFromEnvironment($env); $headers = \Slim\Http\Headers::createFromEnvironment($env); $cookies = (array) new \Slim\Collection(); $serverParams = (array) new \Slim\Collection($env->all()); $body = new \Slim\Http\Body(fopen('php://temp', 'r+')); return new \Slim\Http\Request('GET', $uri, $headers, $cookies, $serverParams, $body); }
public function requestFactory($uri = '/') { // Prepare request and response objects $env = Environment::mock(['SCRIPT_NAME' => '/index.php', 'REQUEST_URI' => '/', 'REQUEST_METHOD' => 'GET']); $uri = Uri::createFromEnvironment($env); $headers = Headers::createFromEnvironment($env); $cookies = []; $serverParams = $env->all(); $body = new Body(fopen('php://temp', 'r+')); $req = new Request('GET', $uri, $headers, $cookies, $serverParams, $body); return $req; }
/** * @param string $method * @param string $uri * @return Request */ public function makeRequest($method = 'GET', $uri = '') { $env = Environment::mock([]); $uri = Uri::createFromString($uri); $headers = Headers::createFromEnvironment($env); $cookies = []; $serverParams = $env->all(); $body = new RequestBody(); $uploadedFiles = UploadedFile::createFromEnvironment($env); $request = new Request($method, $uri, $headers, $cookies, $serverParams, $body, $uploadedFiles); $request = $request->withHeader("Content-Type", "application/x-www-form-urlencoded"); return $request; }
/** * Creates a new request object from the data of a reactPHP request object * * @param \React\Http\Request $request ReactPHP native request object * @param string $body Content of received call * * @return \Slim\Http\Request */ public static function createFromReactRequest(\React\Http\Request $request, $body = '') { $slimHeads = new Headers(); $cookies = []; $host = ['', 80]; foreach ($request->getHeaders() as $reactHeadKey => $reactHead) { $slimHeads->add($reactHeadKey, $reactHead); switch ($reactHeadKey) { case 'Host': $host = static::getHost($reactHead); break; case 'Cookie': $cookies = Cookies::parseHeader($reactHead); break; } } $slimUri = new Uri('http', $host[0], (int) $host[1], $request->getPath(), $request->getQuery()); $serverParams = $_SERVER; $serverParams['SERVER_PROTOCOL'] = 'HTTP/' . $request->getHttpVersion(); $slimBody = static::getBody($body); return new Request($request->getMethod(), $slimUri, $slimHeads, $cookies, $serverParams, $slimBody); }
public function request($method, $path, $options = array()) { $env = Environment::mock(array_merge(['SCRIPT_NAME' => '/index.php', 'REQUEST_URI' => $path, 'REQUEST_METHOD' => $method], $options)); $uri = Uri::createFromEnvironment($env); $headers = Headers::createFromEnvironment($env); $cookies = []; $serverParams = $env->all(); $body = new RequestBody(); $req = new Request($method, $uri, $headers, $cookies, $serverParams, $body); $res = new Response(); $app = (require ROOT_DIR . '/bootstrap/bootstrap.php'); $app($req, $res); return $app($req, $res); }
/** * This function outputs the given $data as valid JSON to the client * and sets the HTTP Response Code to the given $statusCode. * * @param array|SlimBootstrap\DataObject $data The data to output to * the client * @param int $statusCode The status code to set * in the response */ public function write($data, $statusCode = 200) { $result = array(); if (true === is_array($data)) { foreach ($data as $entry) { /** @var SlimBootstrap\DataObject $entry */ $identifiers = array_values($entry->getIdentifiers()); $this->_buildStructure($entry, $identifiers, 0, $result); } } else { $identifiers = array_values($data->getIdentifiers()); $this->_buildStructure($data, $identifiers, 0, $result); } $body = $this->_jsonEncode($result); if (false === $body) { $this->_response->setStatus(500); $this->_response->setBody("Error encoding requested data."); return; } $this->_headers->set('Content-Type', 'application/json; charset=UTF-8'); $this->_response->setStatus($statusCode); $this->_response->setBody($body); }
public function setupRequest($url, $method, $request, $files) { $env = Environment::mock(['REQUEST_URI' => $url, 'REQUEST_METHOD' => $method, 'HTTP_CONTENT_TYPE' => 'multipart/form-data; boundary=---foo']); $uri = Uri::createFromEnvironment($env); $headers = Headers::createFromEnvironment($env); $files = UploadedFile::createFromEnvironment(Environment::mock()); $cookies = []; $serverParams = $env->all(); $body = new RequestBody(); $this->request = new Request($method, $uri, $headers, $cookies, $serverParams, $body, $files); $this->response = new Response(); $app = $this->app; return $app($this->request, $this->response); }
/** * @param array $serverParams * @return ServerRequest */ public function makeServerRequest(array $serverParams) { // I have no idea why I need to type hint here, but phpstorm is complaining /** @var $serverRequest ServerRequest */ $headers = Headers::createFromArray($serverParams); $cookies = Cookies::parseHeader($headers->get('Cookie', [])); $serverRequest = new ServerRequest($serverParams, $cookies); $serverRequest = $serverRequest->withMethod($serverParams['REQUEST_METHOD']); $serverRequest = $serverRequest->withUri(); foreach ($headers->all() as $header => $value) { $serverRequest = $serverRequest->withHeader($header, $value); } $serverRequest = $serverRequest->withUploadedFiles(UploadedFile::parseUploadedFiles($_FILES)); return $serverRequest; }
private function prepareRequest($method, $url, array $requestParameters) { $env = Environment::mock(['SCRIPT_NAME' => '/index.php', 'REQUEST_URI' => $url, 'REQUEST_METHOD' => $method]); $parts = explode('?', $url); if (isset($parts[1])) { $env['QUERY_STRING'] = $parts[1]; } $uri = Uri::createFromEnvironment($env); $headers = Headers::createFromEnvironment($env); $cookies = []; $serverParams = $env->all(); $body = new RequestBody(); $body->write(json_encode($requestParameters)); $request = new Request($method, $uri, $headers, $cookies, $serverParams, $body); return $request->withHeader('Content-Type', 'application/json'); }
public static function fromGlobals(array $server = null, array $query = null, array $body = null, array $cookies = null, array $files = null) { $environment = new Environment($server); $method = $environment['REQUEST_METHOD']; $uri = Uri::createFromEnvironment($environment); $headers = Headers::createFromEnvironment($environment); $cookies = Cookies::parseHeader($headers->get('Cookie', [])); $serverParams = $environment->all(); $body = new RequestBody(); $uploadedFiles = UploadedFile::createFromEnvironment($environment); $request = new ServerRequest($method, $uri, $headers, $cookies, $serverParams, $body, $uploadedFiles); if ($method === 'POST' && in_array($request->getMediaType(), ['application/x-www-form-urlencoded', 'multipart/form-data'])) { // parsed body must be $_POST $request = $request->withParsedBody($_POST); } return $request; }
public function testException() { $app = new App(); $app->add(new WhoopsMiddleware()); $app->get('/foo', function ($req, $res) use($app) { return $app->router->pathFor('index'); }); $env = Environment::mock(['SCRIPT_NAME' => '/index.php', 'REQUEST_URI' => '/foo', 'REQUEST_METHOD' => 'GET']); $uri = Uri::createFromEnvironment($env); $headers = Headers::createFromEnvironment($env); $cookies = []; $serverParams = $env->all(); $body = new Body(fopen('php://temp', 'r+')); $req = new Request('GET', $uri, $headers, $cookies, $serverParams, $body); $res = new Response(); $this->setExpectedException('\\RuntimeException'); $app($req, $res); }
protected function dispatch($path, $method = 'GET', $data = array()) { // Prepare a mock environment $env = Environment::mock(array('REQUEST_URI' => $path, 'REQUEST_METHOD' => $method)); // Prepare request and response objects $uri = Uri::createFromEnvironment($env); $headers = Headers::createFromEnvironment($env); $cookies = []; $serverParams = $env->all(); $body = new RequestBody(); $container = $this->app->getContainer(); // create request, and set params $req = new $container['request']($method, $uri, $headers, $cookies, $serverParams, $body); if (!empty($data)) { $req = $req->withParsedBody($data); } $res = new $container['response'](); $this->headers = $headers; $this->request = $req; $this->response = call_user_func_array($this->app, array($req, $res)); }
/** * DEPRECATION WARNING! IteratorAggregate interface will be removed from \Slim\Http\Response. * Iterate `headers` or `cookies` properties directly. * * Get Iterator * * This returns the contained `\Slim\Http\Headers` instance which * is itself iterable. * * @return \Slim\Http\Headers */ public function getIterator() { return $this->headers->getIterator(); }
/** * Get User Agent * @return string|null */ public function getUserAgent() { return $this->headers->get('HTTP_USER_AGENT'); }
public function testExtractHeaders() { $test = array('HTTP_HOST' => 'foo.com', 'SERVER_NAME' => 'foo', 'CONTENT_TYPE' => 'text/html', 'X_FORWARDED_FOR' => '127.0.0.1'); $results = \Slim\Http\Headers::extract($test); $this->assertEquals(array('HTTP_HOST' => 'foo.com', 'CONTENT_TYPE' => 'text/html', 'X_FORWARDED_FOR' => '127.0.0.1'), $results); }