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\Mail\Header;
11
12use Zend\Mime\Mime;
13
14/**
15 * Subject header class methods.
16 *
17 * @see https://tools.ietf.org/html/rfc2822 RFC 2822
18 * @see https://tools.ietf.org/html/rfc2047 RFC 2047
19 */
20class Subject implements UnstructuredInterface
21{
22    /**
23     * @var string
24     */
25    protected $subject = '';
26
27    /**
28     * Header encoding
29     *
30     * @var null|string
31     */
32    protected $encoding;
33
34    public static function fromString($headerLine)
35    {
36        list($name, $value) = GenericHeader::splitHeaderLine($headerLine);
37        $value = HeaderWrap::mimeDecodeValue($value);
38
39        // check to ensure proper header type for this factory
40        if (strtolower($name) !== 'subject') {
41            throw new Exception\InvalidArgumentException('Invalid header line for Subject string');
42        }
43
44        $header = new static();
45        $header->setSubject($value);
46
47        return $header;
48    }
49
50    public function getFieldName()
51    {
52        return 'Subject';
53    }
54
55    public function getFieldValue($format = HeaderInterface::FORMAT_RAW)
56    {
57        if (HeaderInterface::FORMAT_ENCODED === $format) {
58            return HeaderWrap::wrap($this->subject, $this);
59        }
60
61        return $this->subject;
62    }
63
64    public function setEncoding($encoding)
65    {
66        $this->encoding = $encoding;
67        return $this;
68    }
69
70    public function getEncoding()
71    {
72        if (! $this->encoding) {
73            $this->encoding = Mime::isPrintable($this->subject) ? 'ASCII' : 'UTF-8';
74        }
75
76        return $this->encoding;
77    }
78
79    public function setSubject($subject)
80    {
81        $subject = (string) $subject;
82
83        if (! HeaderWrap::canBeEncoded($subject)) {
84            throw new Exception\InvalidArgumentException(
85                'Subject value must be composed of printable US-ASCII or UTF-8 characters.'
86            );
87        }
88
89        $this->subject  = $subject;
90        $this->encoding = null;
91
92        return $this;
93    }
94
95    public function toString()
96    {
97        return 'Subject: ' . $this->getFieldValue(HeaderInterface::FORMAT_ENCODED);
98    }
99}
100