3 * Zend Framework (http://framework.zend.com/)
5 * @link http://github.com/zendframework/zf2 for the canonical source repository
6 * @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
7 * @license http://framework.zend.com/license/new-bsd New BSD License
10 namespace Zend\Mail\Header
;
12 use Zend\Mail\Headers
;
14 class ContentType
implements HeaderInterface
24 protected $parameters = array();
26 public static function fromString($headerLine)
28 $headerLine = iconv_mime_decode($headerLine, ICONV_MIME_DECODE_CONTINUE_ON_ERROR
, 'UTF-8');
29 list($name, $value) = GenericHeader
::splitHeaderLine($headerLine);
31 // check to ensure proper header type for this factory
32 if (strtolower($name) !== 'content-type') {
33 throw new Exception\
InvalidArgumentException('Invalid header line for Content-Type string');
36 $value = str_replace(Headers
::FOLDING
, " ", $value);
37 $values = preg_split('#\s*;\s*#', $value);
38 $type = array_shift($values);
40 $header = new static();
41 $header->setType($type);
44 foreach ($values as $keyValuePair) {
45 list($key, $value) = explode('=', $keyValuePair, 2);
46 $value = trim($value, "'\" \t\n\r\0\x0B");
47 $header->addParameter($key, $value);
54 public function getFieldName()
56 return 'Content-Type';
59 public function getFieldValue($format = HeaderInterface
::FORMAT_RAW
)
61 $prepared = $this->type
;
62 if (empty($this->parameters
)) {
66 $values = array($prepared);
67 foreach ($this->parameters
as $attribute => $value) {
68 $values[] = sprintf('%s="%s"', $attribute, $value);
71 return implode(';' . Headers
::FOLDING
, $values);
74 public function setEncoding($encoding)
76 // This header must be always in US-ASCII
80 public function getEncoding()
85 public function toString()
87 return 'Content-Type: ' . $this->getFieldValue();
91 * Set the content type
94 * @throws Exception\InvalidArgumentException
97 public function setType($type)
99 if (!preg_match('/^[a-z-]+\/[a-z0-9.+-]+$/i', $type)) {
100 throw new Exception\
InvalidArgumentException(sprintf(
101 '%s expects a value in the format "type/subtype"; received "%s"',
111 * Retrieve the content type
115 public function getType()
121 * Add a parameter pair
123 * @param string $name
124 * @param string $value
125 * @return ContentType
127 public function addParameter($name, $value)
129 $name = strtolower($name);
130 $this->parameters
[$name] = (string) $value;
139 public function getParameters()
141 return $this->parameters
;
145 * Get a parameter by name
147 * @param string $name
148 * @return null|string
150 public function getParameter($name)
152 $name = strtolower($name);
153 if (isset($this->parameters
[$name])) {
154 return $this->parameters
[$name];
160 * Remove a named parameter
162 * @param string $name
165 public function removeParameter($name)
167 $name = strtolower($name);
168 if (isset($this->parameters
[$name])) {
169 unset($this->parameters
[$name]);