Marshal the $_SERVER array

Pre-processes and returns the $_SERVER superglobal.

@param array $server

@return array
517173
public static function normalizeServer(array $server)
    {
        // This seems to be the only way to get the Authorization header on Apache
        if (
            isset($server['HTTP_AUTHORIZATION']) ||
            !\function_exists('\apache_request_headers')
        ) {
            return $server;
        }

        $apacheRequestHeaders = \apache_request_headers();

        if (
            isset($apacheRequestHeaders[$name = 'Authorization']) ||
            isset($apacheRequestHeaders[$name = 'authorization'])
        ) {
            $server['HTTP_AUTHORIZATION'] = $apacheRequestHeaders[$name];

            return $server;
        }

        return $server;
    }
970773
private function processServerVariables(array $server)
    {
        foreach ($server as $key => $value) {
            $this->server[$key] = $value;

            if (strpos($key, 'HTTP_') === 0) {
                $key = str_replace('_', '-', substr($key, 5));

                $this->headers[$key] = $value;
            }
        }

        $uri     = $server['REQUEST_URI'];
        $uriPath = parse_url($uri, PHP_URL_PATH);

        $this->server['REQUEST_URI']      = $uri;
        $this->server['REQUEST_URI_PATH'] = $uriPath;

        $this->isEncrypted = !(empty($server['HTTPS']) || strcasecmp($server['HTTPS'], 'off') === 0);

        $this->server['SERVER_PROTOCOL'] = substr($server['SERVER_PROTOCOL'], -3);

        if (isset($server['CONTENT_LENGTH'])) {
            $this->headers['CONTENT-LENGTH'] = $server['CONTENT_LENGTH'];
        }

        if (isset($server['CONTENT_TYPE'])) {
            $this->headers['CONTENT-TYPE'] = $server['CONTENT_TYPE'];
        }
    }
1371473
private function determineHeader(array $server): MapInterface
    {
        $header = new Map();

        foreach ($server as $name => $value) {
            if (strpos($name, 'HTTP_') === 0) {
                $name = substr($name, 5);
                $name = explode('_', $name);
                $name = array_map('strtolower', $name);
                $name = array_map('ucfirst', $name);
                $name = implode('-', $name);

                $header->set($name, $value);
            }
        }

        return new ReadOnlyMap($header);
    }
510911
private function determineRemoteIpAddress(array $server): string
    {
        if (array_key_exists('HTTP_X_FORWARDED_FOR', $server) && filter_var($server['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP)) {
            return $server['HTTP_X_FORWARDED_FOR'];
        } elseif (array_key_exists('HTTP_CLIENT_IP', $server) && filter_var($server['HTTP_CLIENT_IP'], FILTER_VALIDATE_IP)) {
            return $server['HTTP_CLIENT_IP'];
        } elseif (array_key_exists('HTTP_TRUE_CLIENT_IP', $server) && filter_var($server['HTTP_TRUE_CLIENT_IP'], FILTER_VALIDATE_IP)) {
            return $server['HTTP_TRUE_CLIENT_IP'];
        }

        return $server['REMOTE_ADDR'];
    }
141582
public function addServers(array $servers): self
    {
        foreach ($servers as $hostname => $server) {
            if (!$server instanceof Server && is_array($server)) {
                $host = $server['host'];
                $port = $server['port'] ?? null;
                $database = $server['database'] ?? null;
                $username = $server['username'] ?? null;
                $password = $server['password'] ?? null;
                $options = $server['options'] ?? null;

                $server = new Server($host, $port, $database, $username, $password, $options);
            }

            /* @var Server $server */
            if (!is_string($hostname)) {
                $hostname = $server->getHost();
            }

            $this->addServer($hostname, $server);
        }

        return $this;
    }
847482
public static function make(array $server = null)
    {
        if (empty($server)) {
            $server = $_SERVER;
        }
        $headers = [];
        $content = [
            'CONTENT_TYPE'   => 'Content-Type',
            'CONTENT_LENGTH' => 'Content-Length',
            'CONTENT_MD5'    => 'Content-Md5',
        ];
        foreach ($server as $key => $value) {
            if (substr($key, 0, 5) === 'HTTP_') {
                $key = substr($key, 5);
                if (! isset($content[$key]) || ! isset($server[$key])) {
                    $key = str_replace('_', ' ', $key);
                    $key = ucwords(strtolower($key));
                    $key = str_replace(' ', '-', $key);

                    $headers[$key] = $value;
                }
            } elseif (isset($content[$key])) {
                $headers[$content[$key]] = $value;
            }
        }

        return $headers;
    }
141411
private static function fetchHostname(array $server): array
    {
        $server += ['SERVER_PORT' => null];
        if (null !== $server['SERVER_PORT']) {
            $server['SERVER_PORT'] = (int) $server['SERVER_PORT'];
        }

        if (isset($server['HTTP_HOST'])) {
            preg_match(',^(?<host>(\[.*\]|[^:])*)(\:(?<port>[^/?\#]*))?$,x', $server['HTTP_HOST'], $matches);

            return [
                $matches['host'],
                isset($matches['port']) ? (int) $matches['port'] : $server['SERVER_PORT'],
            ];
        }

        if (!isset($server['SERVER_ADDR'])) {
            throw new SyntaxError('The host could not be detected');
        }

        if (false === filter_var($server['SERVER_ADDR'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
            $server['SERVER_ADDR'] = '['.$server['SERVER_ADDR'].']';
        }

        return [$server['SERVER_ADDR'], $server['SERVER_PORT']];
    }
1200062
public function parseMethod(array $server) {
        $method = array_get($server, 'REQUEST_METHOD');

        if (array_has($server, '_method')) {
            $_method = strtoupper(array_get($server, '_method'));

            if (array_contains(HttpRequestMethod::getMethods(), $_method)) {
                return $_method;
            }
        }

        return $method;
    }
307234
public static function fromGlobals(
        array $server = null,
        array $query = null,
        array $body = null,
        array $cookies = null,
        array $files = null
    ) {
        $cookies = new CookieJar($cookies ?: $_COOKIE);
        $server = static::normalizeServer($server ?: $_SERVER);
        $files = static::normalizeFiles($files ?: $_FILES);
        $headers = static::marshalHeaders($server);
        $request = new Request(
            $cookies,
            $server,
            $files,
            static::marshalUriFromServer($server, $headers),
            static::get('REQUEST_METHOD', $server, 'GET'),
            'php://input',
            $headers
        );

        return $request
            ->withQueryParams($query ?: $_GET)
            ->withParsedBody($body ?: $_POST);
    }
1312016
public static function make(array $server = null)
    {
        if (empty($server)) {
            $server = $_SERVER;
        }

        if (isset($server['REQUEST_URI'])) {
            return parse_url($server['REQUEST_URI'], PHP_URL_PATH);
        }
    }
158026
public function getClasses($server)
    {
        $classes = [];

        if ($search = $this->search($server, '(&(objectClass=*))', ['objectclass'])) {
            $entries = $this->getEntries($search);
            foreach ($entries as $objectClass) {
                if (isset($objectClass['objectclass'])) {
                    unset($objectClass['objectclass']['count']);
                    $classes = array_merge($classes, $objectClass['objectclass']);
                }
            }
        }

        return array_unique($classes);
    }
1086770
private function phpInput(array $server) : array
    {
        $contentType = $this->getContentType($server);
        $isFormUrlEncoded = strpos($contentType, self::FORM_URL_ENCODE) !== false;
        if ($isFormUrlEncoded) {
            parse_str(rtrim($this->getRawBody($server)), $put);

            return $put;
        }
        $isApplicationJson = strpos($contentType, self::APPLICATION_JSON) !== false;
        if (! $isApplicationJson) {
            return [];
        }
        $content = json_decode($this->getRawBody($server), true);
        $error = json_last_error();
        if ($error !== JSON_ERROR_NONE) {
            throw new InvalidRequestJsonException(json_last_error_msg());
        }

        return $content;
    }
799226
protected function configureServer($server, array $config)
    {
        if ($handler = $this->parseEventHandler($config)) {
            $server->setEventHandler($handler);
        }

        if (isset($config['listens']) && $config['listens']) {
            $this->configureServerSockets($server, $config['listens']);
        }

        if (isset($config['processes']) && $config['processes']) {
            $this->configureProcesses($server, $config['processes']);
        }

        return $server;
    }
1373282
public static function make(array $server = null)
    {
        $scheme = UriSchemeFactory::make($server);
        $host   = UriHostFactory::make($server);
        $port   = UriPortFactory::make($server);
        $path   = UriPathFactory::make($server);
        $query  = UriQueryFactory::make($server);

        $url = '';
        if ($host) {
            $url .= $scheme . '://' . $host . ':' . $port;
            $path = '/' . ltrim($path, '/');
        }
        $url .= $path;

        if ($query) {
            $url .= '?' . $query;
        }

        $uri = new Uri($url);

        if ($host) {
            return $uri;
        }

        return $uri->withScheme($scheme)->withPort($port);
    }
276113
public static function getServerListByRoles(array $roles)
    {
        $servers = [];
        foreach ($roles as $roleCode) {
            $rolesForCode = RoleManager::getServersByRole($roleCode);

            foreach ($rolesForCode as $serverCode) {
                if (in_array($serverCode, $servers, true)) {
                    continue;
                }

                $servers[] = $serverCode;
            }
        }

        return $servers;
    }
591986
protected function prepareHeaders($server)
    {
        $output = [];

        if (!is_array($server)) {
            return $output;
        }

        foreach ($server as $key => $value) {
            if (is_string($key) && strlen($key) > 5 && strpos($key, 'HTTP_') !== false) {
                $output[substr($key, 5)] = $value;
            }
        }

        return $output;
    }
632861
protected function unifyServerDeclarations($servers)
    {
        // Unify flat declaration
        if (Arr::get($servers, 'host')) {
            return ['servers' => [$servers]];
        }

        // Unify single servers
        if (Arr::get($servers, 'servers.host')) {
            $servers['servers'] = [$servers['servers']];
        }

        // Unify all the things
        if (array_keys($servers) !== ['servers']) {
            $servers = Arr::get($servers, 'servers', $servers);
            $servers = ['servers' => array_values($servers)];
        }

        return $servers;
    }