public function testCreateEmptyHttpRequest() { $actualRequest = HttpRequest::create(array()); $expectedRequest = new HttpRequest(); $expectedRequest->setRequestTime($actualRequest->getRequestTime()); $this->assertEquals($expectedRequest, $actualRequest, 'Create request without data'); }
/** * Creates a new HttpRequest object based on the given data * @param array $requestData Data of the HTTP request * @return HttpRequest */ public static function create(array $requestData = array()) { $defaultValues = array('REQUEST_TIME' => time(), 'SERVER_PORT' => null, 'SERVER_NAME' => null, 'QUERY_STRING' => null, 'REMOTE_ADDR' => null, 'HTTP_USER_AGENT' => null, 'HTTPS' => null, 'REQUEST_URI' => null, 'HTTP_ACCEPT_LANGUAGE' => null, 'HTTP_ACCEPT_ENCODING' => null, 'REQUEST_METHOD' => null); $requestData = array_merge($defaultValues, $requestData); $httpRequest = new HttpRequest(); $protocol = null; if ($requestData['HTTPS'] !== null) { $protocol = $requestData['HTTPS'] === 'on' ? HttpRequest::PROTOCOL_HTTPS : HttpRequest::PROTOCOL_HTTP; } $uri = StringUtils::startsWith($requestData['REQUEST_URI'], self::$basePath) ? StringUtils::afterFirst($requestData['REQUEST_URI'], self::$basePath) : $requestData['REQUEST_URI']; $path = StringUtils::beforeLast($uri, '?'); $languages = array(); $langRates = array_filter(explode(',', $requestData['HTTP_ACCEPT_LANGUAGE'])); foreach ($langRates as $lr) { list($langCode, $importance) = array_pad(preg_split('/;(?:q=)?/', $lr), 2, 1.0); $languages[$langCode] = (double) $importance; } $acceptedEncoding = array_filter(array_map('trim', explode(',', $requestData['HTTP_ACCEPT_ENCODING']))); $requestTime = new \DateTime(); $requestTime->setTimestamp($requestData['REQUEST_TIME']); $httpRequest->setHost($requestData['SERVER_NAME']); $httpRequest->setPath($path); $httpRequest->setPort($requestData['SERVER_PORT']); $httpRequest->setProtocol($protocol); $httpRequest->setQuery($requestData['QUERY_STRING']); $httpRequest->setURI($uri); $httpRequest->setRequestTime($requestTime); $httpRequest->setAcceptedEncodings($acceptedEncoding); $httpRequest->setRequestMethod($requestData['REQUEST_METHOD']); $httpRequest->setUserAgent($requestData['HTTP_USER_AGENT']); $httpRequest->setAcceptedLanguages($languages); $httpRequest->setRemoteAddress($requestData['REMOTE_ADDR']); $headers = array(); foreach ($_SERVER as $name => $value) { if (StringUtils::startsWith($name, 'HTTP_') === true) { $name = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5))))); $headers[$name] = $value; } elseif ($name == 'CONTENT_TYPE') { $headers['Content-Type'] = $value; } elseif ($name == 'CONTENT_LENGTH') { $headers['Content-Length'] = $value; } } $httpRequest->setHeaders($headers); return $httpRequest; }