/** * Makes PSR-7 compliant Request object from provided parameters * * @param UriInterface|string $uri * @param null|string|array $data * @param array $queryParameters * @param array $headers * @param null|string $method * @param null|string $contentType * @param null|string $contentCharset * @return RequestInterface * @throws InvalidArgumentException */ public static function make($uri, $data = null, array $queryParameters = [], array $headers = [], $method = null, $contentType = null, $contentCharset = null) { if (is_null($method)) { $method = is_null($data) ? static::METHOD_GET : static::METHOD_POST; } $uri = UriFactory::make($uri, $queryParameters); $stream = new Stream('php://memory', 'r+'); $request = new Request($uri, $method, $stream, $headers); $contentType = $contentType ?: $request->getHeaderLine('Content-Type'); $contentType = $contentType ?: static::DEFAULT_CONTENT_TYPE; $contentTypeParts = explode(';', $contentType); $mimeType = trim(array_shift($contentTypeParts)); if (is_null($data)) { $body = null; } elseif (is_string($data)) { $body = $data; } elseif (is_array($data)) { $body = static::format($data, $mimeType); } else { throw new InvalidArgumentException('Data should be either null, string or array'); } if (!is_null($body)) { $contentCharset = $contentCharset ?: static::extractCharset($contentTypeParts); $contentCharset = $contentCharset ?: static::DEFAULT_CONTENT_CHARSET; $contentTypeReassembled = $mimeType . '; charset=' . $contentCharset; $request = $request->withHeader('Content-Type', $contentTypeReassembled); $request->getBody()->write($body); } return $request; }
public function testMakeWithQueryParametersAdded() { $queryParameters = ['first' => 'different', 'third' => ['c' => 'x', 'b' => 'm', 'd' => null, 'e' => ''], 'fourth' => ['h' => ['j' => 4]]]; $uri = UriFactory::make('https://www.example.com/some/dir?first=one&second=two&third%5Ba%5D=x&third[b]=y&third%5Bd%5D=z&fourth[h][i]=four', $queryParameters); $this->assertInstanceOf('Psr\\Http\\Message\\UriInterface', $uri); $expectedQuery = 'first=different&second=two&third%5Ba%5D=x&third%5Bb%5D=m&third%5Bc%5D=x&third%5Be%5D=&fourth%5Bh%5D%5Bi%5D=four&fourth%5Bh%5D%5Bj%5D=4'; $this->assertSame($expectedQuery, $uri->getQuery()); }