Skip to main content
Drupal API
User account menu
  • Log in

Breadcrumb

  1. Drupal Core 11.1.x
  2. ServerRequest.php

class ServerRequest

Server-side HTTP request

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.

Hierarchy

  • class \GuzzleHttp\Psr7\Request implements \Psr\Http\Message\RequestInterface uses \GuzzleHttp\Psr7\MessageTrait
    • class \GuzzleHttp\Psr7\ServerRequest extends \GuzzleHttp\Psr7\Request implements \Psr\Http\Message\ServerRequestInterface

Expanded class hierarchy of ServerRequest

File

vendor/guzzlehttp/psr7/src/ServerRequest.php, line 27

Namespace

GuzzleHttp\Psr7
View source
class ServerRequest extends Request implements ServerRequestInterface {
    
    /**
     * @var array
     */
    private $attributes = [];
    
    /**
     * @var array
     */
    private $cookieParams = [];
    
    /**
     * @var array|object|null
     */
    private $parsedBody;
    
    /**
     * @var array
     */
    private $queryParams = [];
    
    /**
     * @var array
     */
    private $serverParams;
    
    /**
     * @var array
     */
    private $uploadedFiles = [];
    
    /**
     * @param string                               $method       HTTP method
     * @param string|UriInterface                  $uri          URI
     * @param (string|string[])[]                  $headers      Request headers
     * @param string|resource|StreamInterface|null $body         Request body
     * @param string                               $version      Protocol version
     * @param array                                $serverParams Typically the $_SERVER superglobal
     */
    public function __construct(string $method, $uri, array $headers = [], $body = null, string $version = '1.1', array $serverParams = []) {
        $this->serverParams = $serverParams;
        parent::__construct($method, $uri, $headers, $body, $version);
    }
    
    /**
     * Return an UploadedFile instance array.
     *
     * @param array $files An array which respect $_FILES structure
     *
     * @throws InvalidArgumentException for unrecognized values
     */
    public static function normalizeFiles(array $files) : array {
        $normalized = [];
        foreach ($files as $key => $value) {
            if ($value instanceof UploadedFileInterface) {
                $normalized[$key] = $value;
            }
            elseif (is_array($value) && isset($value['tmp_name'])) {
                $normalized[$key] = self::createUploadedFileFromSpec($value);
            }
            elseif (is_array($value)) {
                $normalized[$key] = self::normalizeFiles($value);
                continue;
            }
            else {
                throw new InvalidArgumentException('Invalid value in files specification');
            }
        }
        return $normalized;
    }
    
    /**
     * Create and return an UploadedFile instance from a $_FILES specification.
     *
     * If the specification represents an array of values, this method will
     * delegate to normalizeNestedFileSpec() and return that return value.
     *
     * @param array $value $_FILES struct
     *
     * @return UploadedFileInterface|UploadedFileInterface[]
     */
    private static function createUploadedFileFromSpec(array $value) {
        if (is_array($value['tmp_name'])) {
            return self::normalizeNestedFileSpec($value);
        }
        return new UploadedFile($value['tmp_name'], (int) $value['size'], (int) $value['error'], $value['name'], $value['type']);
    }
    
    /**
     * Normalize an array of file specifications.
     *
     * Loops through all nested files and returns a normalized array of
     * UploadedFileInterface instances.
     *
     * @return UploadedFileInterface[]
     */
    private static function normalizeNestedFileSpec(array $files = []) : array {
        $normalizedFiles = [];
        foreach (array_keys($files['tmp_name']) as $key) {
            $spec = [
                'tmp_name' => $files['tmp_name'][$key],
                'size' => $files['size'][$key] ?? null,
                'error' => $files['error'][$key] ?? null,
                'name' => $files['name'][$key] ?? null,
                'type' => $files['type'][$key] ?? null,
            ];
            $normalizedFiles[$key] = self::createUploadedFileFromSpec($spec);
        }
        return $normalizedFiles;
    }
    
    /**
     * Return a ServerRequest populated with superglobals:
     * $_GET
     * $_POST
     * $_COOKIE
     * $_FILES
     * $_SERVER
     */
    public static function fromGlobals() : ServerRequestInterface {
        $method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
        $headers = getallheaders();
        $uri = self::getUriFromGlobals();
        $body = new CachingStream(new LazyOpenStream('php://input', 'r+'));
        $protocol = isset($_SERVER['SERVER_PROTOCOL']) ? str_replace('HTTP/', '', $_SERVER['SERVER_PROTOCOL']) : '1.1';
        $serverRequest = new ServerRequest($method, $uri, $headers, $body, $protocol, $_SERVER);
        return $serverRequest->withCookieParams($_COOKIE)
            ->withQueryParams($_GET)
            ->withParsedBody($_POST)
            ->withUploadedFiles(self::normalizeFiles($_FILES));
    }
    private static function extractHostAndPortFromAuthority(string $authority) : array {
        $uri = 'http://' . $authority;
        $parts = parse_url($uri);
        if (false === $parts) {
            return [
                null,
                null,
            ];
        }
        $host = $parts['host'] ?? null;
        $port = $parts['port'] ?? null;
        return [
            $host,
            $port,
        ];
    }
    
    /**
     * Get a Uri populated with values from $_SERVER.
     */
    public static function getUriFromGlobals() : UriInterface {
        $uri = new Uri('');
        $uri = $uri->withScheme(!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' ? 'https' : 'http');
        $hasPort = false;
        if (isset($_SERVER['HTTP_HOST'])) {
            [
                $host,
                $port,
            ] = self::extractHostAndPortFromAuthority($_SERVER['HTTP_HOST']);
            if ($host !== null) {
                $uri = $uri->withHost($host);
            }
            if ($port !== null) {
                $hasPort = true;
                $uri = $uri->withPort($port);
            }
        }
        elseif (isset($_SERVER['SERVER_NAME'])) {
            $uri = $uri->withHost($_SERVER['SERVER_NAME']);
        }
        elseif (isset($_SERVER['SERVER_ADDR'])) {
            $uri = $uri->withHost($_SERVER['SERVER_ADDR']);
        }
        if (!$hasPort && isset($_SERVER['SERVER_PORT'])) {
            $uri = $uri->withPort($_SERVER['SERVER_PORT']);
        }
        $hasQuery = false;
        if (isset($_SERVER['REQUEST_URI'])) {
            $requestUriParts = explode('?', $_SERVER['REQUEST_URI'], 2);
            $uri = $uri->withPath($requestUriParts[0]);
            if (isset($requestUriParts[1])) {
                $hasQuery = true;
                $uri = $uri->withQuery($requestUriParts[1]);
            }
        }
        if (!$hasQuery && isset($_SERVER['QUERY_STRING'])) {
            $uri = $uri->withQuery($_SERVER['QUERY_STRING']);
        }
        return $uri;
    }
    public function getServerParams() : array {
        return $this->serverParams;
    }
    public function getUploadedFiles() : array {
        return $this->uploadedFiles;
    }
    public function withUploadedFiles(array $uploadedFiles) : ServerRequestInterface {
        $new = clone $this;
        $new->uploadedFiles = $uploadedFiles;
        return $new;
    }
    public function getCookieParams() : array {
        return $this->cookieParams;
    }
    public function withCookieParams(array $cookies) : ServerRequestInterface {
        $new = clone $this;
        $new->cookieParams = $cookies;
        return $new;
    }
    public function getQueryParams() : array {
        return $this->queryParams;
    }
    public function withQueryParams(array $query) : ServerRequestInterface {
        $new = clone $this;
        $new->queryParams = $query;
        return $new;
    }
    
    /**
     * @return array|object|null
     */
    public function getParsedBody() {
        return $this->parsedBody;
    }
    public function withParsedBody($data) : ServerRequestInterface {
        $new = clone $this;
        $new->parsedBody = $data;
        return $new;
    }
    public function getAttributes() : array {
        return $this->attributes;
    }
    
    /**
     * @return mixed
     */
    public function getAttribute($attribute, $default = null) {
        if (false === array_key_exists($attribute, $this->attributes)) {
            return $default;
        }
        return $this->attributes[$attribute];
    }
    public function withAttribute($attribute, $value) : ServerRequestInterface {
        $new = clone $this;
        $new->attributes[$attribute] = $value;
        return $new;
    }
    public function withoutAttribute($attribute) : ServerRequestInterface {
        if (false === array_key_exists($attribute, $this->attributes)) {
            return $this;
        }
        $new = clone $this;
        unset($new->attributes[$attribute]);
        return $new;
    }

}

Members

Title Sort descending Modifiers Object type Summary Overriden Title
MessageTrait::$headerNames private property @var string[] Map of lowercase header name => original name at registration
MessageTrait::$headers private property @var string[][] Map of all registered headers, as original name => array of values
MessageTrait::$protocol private property @var string
MessageTrait::$stream private property @var StreamInterface|null
MessageTrait::assertHeader private function
MessageTrait::assertValue private function field-value = *( field-content / obs-fold )
field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
field-vchar = VCHAR / obs-text
VCHAR = %x21-7E
obs-text = %x80-FF
obs-fold = CRLF 1*( SP / HTAB )
MessageTrait::getBody public function
MessageTrait::getHeader public function
MessageTrait::getHeaderLine public function
MessageTrait::getHeaders public function
MessageTrait::getProtocolVersion public function
MessageTrait::hasHeader public function
MessageTrait::normalizeHeaderValue private function
MessageTrait::setHeaders private function
MessageTrait::trimAndValidateHeaderValues private function Trims whitespace from the header values.
MessageTrait::withAddedHeader public function
MessageTrait::withBody public function
MessageTrait::withHeader public function
MessageTrait::withoutHeader public function
MessageTrait::withProtocolVersion public function
Request::$method private property @var string
Request::$requestTarget private property @var string|null
Request::$uri private property @var UriInterface
Request::assertMethod private function
Request::getMethod public function Retrieves the HTTP method of the request. Overrides RequestInterface::getMethod
Request::getRequestTarget public function Retrieves the message's request target. Overrides RequestInterface::getRequestTarget
Request::getUri public function Retrieves the URI instance. Overrides RequestInterface::getUri
Request::updateHostFromUri private function
Request::withMethod public function Return an instance with the provided HTTP method. Overrides RequestInterface::withMethod
Request::withRequestTarget public function Return an instance with the specific request-target. Overrides RequestInterface::withRequestTarget
Request::withUri public function Returns an instance with the provided URI. Overrides RequestInterface::withUri
ServerRequest::$attributes private property
ServerRequest::$cookieParams private property
ServerRequest::$parsedBody private property
ServerRequest::$queryParams private property
ServerRequest::$serverParams private property
ServerRequest::$uploadedFiles private property
ServerRequest::createUploadedFileFromSpec private static function Create and return an UploadedFile instance from a $_FILES specification.
ServerRequest::extractHostAndPortFromAuthority private static function
ServerRequest::fromGlobals public static function Return a ServerRequest populated with superglobals:
$_GET
$_POST
$_COOKIE
$_FILES
$_SERVER
ServerRequest::getAttribute public function Overrides ServerRequestInterface::getAttribute
ServerRequest::getAttributes public function Retrieve attributes derived from the request. Overrides ServerRequestInterface::getAttributes
ServerRequest::getCookieParams public function Retrieve cookies. Overrides ServerRequestInterface::getCookieParams
ServerRequest::getParsedBody public function Overrides ServerRequestInterface::getParsedBody
ServerRequest::getQueryParams public function Retrieve query string arguments. Overrides ServerRequestInterface::getQueryParams
ServerRequest::getServerParams public function Retrieve server parameters. Overrides ServerRequestInterface::getServerParams
ServerRequest::getUploadedFiles public function Retrieve normalized file upload data. Overrides ServerRequestInterface::getUploadedFiles
ServerRequest::getUriFromGlobals public static function Get a Uri populated with values from $_SERVER.
ServerRequest::normalizeFiles public static function Return an UploadedFile instance array.
ServerRequest::normalizeNestedFileSpec private static function Normalize an array of file specifications.
ServerRequest::withAttribute public function Return an instance with the specified derived request attribute. Overrides ServerRequestInterface::withAttribute
ServerRequest::withCookieParams public function Return an instance with the specified cookies. Overrides ServerRequestInterface::withCookieParams
ServerRequest::withoutAttribute public function Return an instance that removes the specified derived request attribute. Overrides ServerRequestInterface::withoutAttribute
ServerRequest::withParsedBody public function Return an instance with the specified body parameters. Overrides ServerRequestInterface::withParsedBody
ServerRequest::withQueryParams public function Return an instance with the specified query string arguments. Overrides ServerRequestInterface::withQueryParams
ServerRequest::withUploadedFiles public function Create a new instance with the specified uploaded files. Overrides ServerRequestInterface::withUploadedFiles
ServerRequest::__construct public function Overrides Request::__construct

API Navigation

  • Drupal Core 11.1.x
  • Topics
  • Classes
  • Functions
  • Constants
  • Globals
  • Files
  • Namespaces
  • Deprecated
  • Services
RSS feed
Powered by Drupal