Serialize PHP's $_COOKIE values into a valid HTTP COOKIE string.

@param array<string, string> $cookies if null

@return string|null
546246
public static function getCookiesHeaderLine(array $cookies = null): ?string
    {
        $cookies = $cookies ?? $_COOKIE;
        if (empty($cookies)) {
            return null;
        }

        $cookieParts = [];
        foreach ($cookies as $k => $v) {
            $cookieParts[] = self::serializePHPCookies($k, $v);
        }

        return 'Cookie: '.implode(';', $cookieParts);
    }
609007
public function addCookie($cookie = Array())
    {
        foreach ($cookie as $key => $val) {
            if (isset($this->encryption_key)) {
                $val = $this->encryptor->encrypt($val);
            }

            $this->cookies[$key] = $val;
        }
    }
957793
public List<String> encode(Collection<? extends Cookie> cookies) {
        if (checkNotNull(cookies, "cookies").isEmpty()) {
            return Collections.emptyList();
        }

        List<String> encoded = new ArrayList<String>(cookies.size());
        Map<String, Integer> nameToIndex = strict && cookies.size() > 1 ? new HashMap<String, Integer>() : null;
        int i = 0;
        boolean hasDupdName = false;
        for (Cookie c : cookies) {
            encoded.add(encode(c));
            if (nameToIndex != null) {
                hasDupdName |= nameToIndex.put(c.name(), i++) != null;
            }
        }
        return hasDupdName ? dedup(encoded, nameToIndex) : encoded;
    }
188971
public function with_cookie( $cookie ) {
		if ( is_string( $cookie ) ) {
			$cookie = call_user_func_array( [ $this, 'create_cookie' ], func_get_args() );
		}

		$this->headers->setCookie( $cookie );

		return $this;
	}
475926
public function setCookie(Cookie $cookie) : Response
    {
        $this->cookies[] = $cookie;
        $this->addHeader('Set-Cookie', (string) $cookie);

        return $this;
    }
923703
private function parseCookie($cookie, $host = null, $path = null, $decode = false) {
        // Explode the cookie string using a series of semicolons
        $pieces = array_filter(array_map('trim', explode(';', $cookie)));

        // The name of the cookie (first kvp) must include an equal sign.
        if (empty($pieces) || !strpos($pieces[0], '=')) {
            return false;
        }

        // Create the default return array
        $data = array_merge(array_fill_keys(array_keys(self::$cookieParts), null), array(
            'cookies'   => array(),
            'data'      => array(),
            'path'      => $path ?: '/',
            'http_only' => false,
            'discard'   => false,
            'domain'    => $host
        ));
        $foundNonCookies = 0;

        // Add the cookie pieces into the parsed data array
        foreach ($pieces as $part) {

            $cookieParts = explode('=', $part, 2);
            $key = trim($cookieParts[0]);

            if (count($cookieParts) == 1) {
                // Can be a single value (e.g. secure, httpOnly)
                $value = true;
            } else {
                // Be sure to strip wrapping quotes
                $value = trim($cookieParts[1], " \n\r\t\0\x0B\"");
                if ($decode) {
                    $value = urldecode($value);
                }
            }

            // Only check for non-cookies when cookies have been found
            if (!empty($data['cookies'])) {
                foreach (self::$cookieParts as $mapValue => $search) {
                    if (!strcasecmp($search, $key)) {
                        $data[$mapValue] = $mapValue == 'port' ? array_map('trim', explode(',', $value)) : $value;
                        $foundNonCookies++;
                        continue 2;
                    }
                }
            }

            // If cookies have not yet been retrieved, or this value was not found in the pieces array, treat it as a
            // cookie. IF non-cookies have been parsed, then this isn't a cookie, it's cookie data. Cookies then data.
            $data[$foundNonCookies ? 'data' : 'cookies'][$key] = $value;
        }

        // Calculate the expires date
        if (!$data['expires'] && $data['max_age']) {
            $data['expires'] = time() + (int) $data['max_age'];
        }

        return $data;
    }
1159654
function UpdateCookies($cookies)
    {
        if (sizeof($this->cookies) == 0) {
            // no existing cookies: take whatever is new
            if (sizeof($cookies) > 0) {
                $this->debug('Setting new cookie(s)');
                $this->cookies = $cookies;
            }

            return TRUE;
        }
        if (sizeof($cookies) == 0) {
            // no new cookies: keep what we've got
            return TRUE;
        }
        // merge
        foreach ($cookies as $newCookie) {
            if (!is_array($newCookie)) {
                continue;
            }
            if ((!isset($newCookie['name'])) || (!isset($newCookie['value']))) {
                continue;
            }
            $newName = $newCookie['name'];

            $found = FALSE;
            for ($i = 0; $i < count($this->cookies); $i++) {
                $cookie = $this->cookies[$i];
                if (!is_array($cookie)) {
                    continue;
                }
                if (!isset($cookie['name'])) {
                    continue;
                }
                if ($newName != $cookie['name']) {
                    continue;
                }
                $newDomain = isset($newCookie['domain']) ? $newCookie['domain'] : 'NODOMAIN';
                $domain    = isset($cookie['domain']) ? $cookie['domain'] : 'NODOMAIN';
                if ($newDomain != $domain) {
                    continue;
                }
                $newPath = isset($newCookie['path']) ? $newCookie['path'] : 'NOPATH';
                $path    = isset($cookie['path']) ? $cookie['path'] : 'NOPATH';
                if ($newPath != $path) {
                    continue;
                }
                $this->cookies[$i] = $newCookie;
                $found             = TRUE;
                $this->debug('Update cookie ' . $newName . '=' . $newCookie['value']);
                break;
            }
            if (!$found) {
                $this->debug('Add cookie ' . $newName . '=' . $newCookie['value']);
                $this->cookies[] = $newCookie;
            }
        }

        return TRUE;
    }
1282124
private function get_headers($httpType, $cookies)
    {
        // Common header flags.
        $headers = [];
        $headers[] = 'Dnt: 1';
        $headers[] = 'Connection: keep-alive';
        $headers[] = 'Accept-Language: it-IT,it;q=0.8,en-US;q=0.6,en;q=0.4';
        $headers[] = 'User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36';

        // Add additional headers based on the type of request.
        switch ($httpType) {
        case 'origin':
          $headers[] = 'Origin: '.self::MY_TELEGRAM_URL;
          $headers[] = 'Accept-Encoding: gzip, deflate, br';
          $headers[] = 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8';
          $headers[] = 'Accept: application/json, text/javascript, */*; q=0.01';
          $headers[] = 'Referer: '.self::MY_TELEGRAM_URL.'/auth';
          $headers[] = 'X-Requested-With: XMLHttpRequest';
        break;
        case 'refer':
          $headers[] = 'Accept-Encoding: gzip, deflate, sdch, br';
          $headers[] = 'Upgrade-Insecure-Requests: 1';
          $headers[] = 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8';
          $headers[] = 'Referer: '.self::MY_TELEGRAM_URL;
          $headers[] = 'Cache-Control: max-age=0';
        break;
        case 'app':
          $headers[] = 'Origin: '.self::MY_TELEGRAM_URL;
          $headers[] = 'Accept-Encoding: gzip, deflate, br';
          $headers[] = 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8';
          $headers[] = 'Accept: */*';
          $headers[] = 'Referer: '.self::MY_TELEGRAM_URL.'/apps';
          $headers[] = 'X-Requested-With: XMLHttpRequest';
        break;
        }

        // Add every cookie to the header.
        foreach ($cookies as $cookie) {
            $headers[] = 'Cookie: '.$cookie;
        }

        return $headers;
    }
557589
public String encode(Collection<? extends Cookie> cookies) {
        if (checkNotNull(cookies, "cookies").isEmpty()) {
            return null;
        }

        StringBuilder buf = stringBuilder();
        if (strict) {
            if (cookies.size() == 1) {
                encode(buf, cookies.iterator().next());
            } else {
                Cookie[] cookiesSorted = cookies.toArray(new Cookie[0]);
                Arrays.sort(cookiesSorted, COOKIE_COMPARATOR);
                for (Cookie c : cookiesSorted) {
                    encode(buf, c);
                }
            }
        } else {
            for (Cookie c : cookies) {
                encode(buf, c);
            }
        }
        return stripTrailingSeparatorOrNull(buf);
    }
993289
protected function prepareCookies()
    {
        $cookiesString = '';

        foreach ($this->cookies as $cookie => $value) {
            $cookiesString .= $cookie.'='.$value.'; ';
        }

        return $cookiesString;
    }
1294172
private static function serializePHPCookies(string $cookieName, $cookieValue): string
    {
        $cookieParts = [];
        $urlEncodedCookieName = urlencode($cookieName);
        $valueType = gettype($cookieValue);
        switch ($valueType) {
            case 'integer':
            case 'double':
            case 'string':
                $urlEncodedCookieValue = urlencode((string) $cookieValue);
                $cookieParts[] = "$urlEncodedCookieName=$urlEncodedCookieValue";
                break;

            case 'array':
                foreach ($cookieValue as $cookieValueKey => $cookieValueValue) {
                    $cookieParts[] = self::serializePHPCookies($cookieName."[$cookieValueKey]", $cookieValueValue);
                }
                break;

            case 'NULL':
                $cookieParts[] = "$urlEncodedCookieName=";
                break;

            case 'boolean':
                $cookieParts[] = "$urlEncodedCookieName=".((bool) $cookieValue ? '1' : '0');
                break;

            // It's a security risk to serialize an object and send it as a cookie
            case 'object':
                // Intentional fallthrough
            default:
                $cookieParts[] = "$urlEncodedCookieName=".self::UNSUPPORTED_TYPE_VALUE;
                break;
        }

        return implode(';', $cookieParts);
    }
987262
public function addCookie(Cookie $cookie): Response
    {
        $this->cookies[$cookie->name()] = $cookie;
        return $this;
    }
96650
public function setCookies($cookies = [])
    {

        $this->cookies = ($cookies instanceof Parameters) ? $cookies : new Parameters("cookies", (array)$cookies);

        return $this;
    }
456596
public function get($cookie)
    {
        if (!$this->has($cookie)) {
            if ($this->getRequest()) {
                return $this->getRequest()->getCookie($cookie);
            }
            
            return null;
        }
        
        return $this->_cookies[$cookie]['value'];
    }
210409
public static String encodeCookie( Cookie cookie ) {

        StringBuilder buf = new StringBuilder(cookie.getName());
        buf.append("=");
        buf.append(cookie.getValue());

        String comment = cookie.getComment();
        if (comment != null) {
            buf.append("; Comment=\"");
            buf.append(comment);
            buf.append("\"");
        }

        String domain = cookie.getDomain();
        if (domain != null) {
            buf.append("; Domain=\"");
            buf.append(domain);
            buf.append("\"");
        }

        int age = cookie.getMaxAge();
        if (age >= 0) {
            buf.append("; Max-Age=\"");
            buf.append(age);
            buf.append("\"");
        }

        String path = cookie.getPath();
        if (path != null) {
            buf.append("; Path=\"");
            buf.append(path);
            buf.append("\"");
        }

        if (cookie.getSecure()) {
            buf.append("; Secure");
        }

        int version = cookie.getVersion();
        if (version > 0) {
            buf.append("; Version=\"");
            buf.append(version);
            buf.append("\"");
        }

        return (buf.toString());
    }
425044
protected function serveCookies($cookies)
    {
        foreach ($cookies as $cookie) {
            if ($cookie->hasChanged()) {
                $expiration = $cookie->getExpiration();
                if (isset($expiration)) {
                    $expiration = $expiration->getTimestamp();
                } else {
                    $expiration = 0;
                }
                setcookie(
                    $cookie->getName(),
                    $cookie->get(),
                    $expiration,
                    $cookie->getPath(),
                    $cookie->getDomain(),
                    $cookie->isSecure(),
                    $cookie->isHttpOnly()
                );
            }
        }
    }
227012
public static function parseCookie($cookie)
    {
        // PSR-7 `getHeaderLine('Cookies')` will return multiple
        // cookie header comma-seperated. Multiple cookie headers
        // are not allowed according to https://tools.ietf.org/html/rfc6265#section-5.4
        if (strpos($cookie, ',') !== false) {
            return false;
        }
        $cookieArray = explode(';', $cookie);
        $result = array();
        foreach ($cookieArray as $pair) {
            $pair = trim($pair);
            $nameValuePair = explode('=', $pair, 2);
            if (count($nameValuePair) === 2) {
                $key = urldecode($nameValuePair[0]);
                $value = urldecode($nameValuePair[1]);
                $result[$key] = $value;
            }
        }
        return $result;
    }