1<?php
2/**
3 * Zend Framework (http://framework.zend.com/)
4 *
5 * @link      http://github.com/zendframework/zf2 for the canonical source repository
6 * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
7 * @license   http://framework.zend.com/license/new-bsd New BSD License
8 */
9
10namespace Zend\Http\Header;
11
12/**
13 * Connection Header
14 *
15 * @link       http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.10
16 */
17class Connection implements HeaderInterface
18{
19    const CONNECTION_CLOSE      = 'close';
20    const CONNECTION_KEEP_ALIVE = 'keep-alive';
21
22    /**
23     * Value of this header
24     *
25     * @var string
26     */
27    protected $value = self::CONNECTION_KEEP_ALIVE;
28
29    /**
30     * @param $headerLine
31     * @return Connection
32     * @throws Exception\InvalidArgumentException
33     */
34    public static function fromString($headerLine)
35    {
36        $header = new static();
37
38        list($name, $value) = GenericHeader::splitHeaderLine($headerLine);
39
40        // check to ensure proper header type for this factory
41        if (strtolower($name) !== 'connection') {
42            throw new Exception\InvalidArgumentException('Invalid header line for Connection string: "' . $name . '"');
43        }
44
45        $header->setValue(trim($value));
46
47        return $header;
48    }
49
50    /**
51     * Set Connection header to define persistent connection
52     *
53     * @param  bool $flag
54     * @return Connection
55     */
56    public function setPersistent($flag)
57    {
58        $this->value = (bool) $flag
59            ? self::CONNECTION_KEEP_ALIVE
60            : self::CONNECTION_CLOSE;
61        return $this;
62    }
63
64    /**
65     * Get whether this connection is persistent
66     *
67     * @return bool
68     */
69    public function isPersistent()
70    {
71        return ($this->value === self::CONNECTION_KEEP_ALIVE);
72    }
73
74    /**
75     * Set arbitrary header value
76     * RFC allows any token as value, 'close' and 'keep-alive' are commonly used
77     *
78     * @param string $value
79     * @return Connection
80     */
81    public function setValue($value)
82    {
83        HeaderValue::assertValid($value);
84        $this->value = strtolower($value);
85        return $this;
86    }
87
88    /**
89     * Connection header name
90     *
91     * @return string
92     */
93    public function getFieldName()
94    {
95        return 'Connection';
96    }
97
98    /**
99     * Connection header value
100     *
101     * @return string
102     */
103    public function getFieldValue()
104    {
105        return $this->value;
106    }
107
108    /**
109     * Return header line
110     *
111     * @return string
112     */
113    public function toString()
114    {
115        return 'Connection: ' . $this->getFieldValue();
116    }
117}
118