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