Passed
Push — master ( d04c5a...d84490 )
by Mathias
24:28 queued 14:22
created

MailService::getQueue()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
eloc 3
c 0
b 0
f 0
dl 0
loc 7
ccs 0
cts 0
cp 0
rs 10
cc 2
nc 2
nop 0
crap 6
1
<?php
2
/**
3
 * YAWIK
4
 *
5
 * @filesource
6
 * @copyright (c) 2013 - 2016 Cross Solution (http://cross-solution.de)
7
 * @license       MIT
8
 */
9
10
/** */
11
namespace Core\Mail;
12
13
use Core\Exception\MissingDependencyException;
14
use Core\Factory\ContainerAwareInterface;
15
use Core\Queue\Job\MailJob;
16
use Core\Queue\MongoQueue;
17
use Interop\Container\ContainerInterface;
18
use Laminas\I18n\Translator\TranslatorAwareInterface;
19
use Laminas\Mail\Address;
20
use Laminas\Mail\AddressList;
21
use Laminas\Mail\Message as MailMessage;
22
use Laminas\Mail\Transport\TransportInterface;
23
use Laminas\ServiceManager\AbstractPluginManager;
24
use Laminas\ServiceManager\ConfigInterface;
25
use Laminas\ServiceManager\ServiceLocatorInterface;
26
27
/**
28
 * Mail Plugin Manager
29
 *
30
 * @author Mathias Gelhausen <[email protected]>
31
 * @author Mathias Weitz <[email protected]>
32
 * @author Carsten Bleek <[email protected]>
33
 * @author Anthonius Munthi <[email protected]>
34
 */
35
class MailService extends AbstractPluginManager
36
{
37
    /**
38
     * Define transport type to use
39
     */
40
    const TRANSPORT_SMTP        = 'smtp';
41
    const TRANSPORT_FILE        = 'file';
42
    const TRANSPORT_SENDMAIL    = 'sendmail';
43
44
    /**
45
     * The mail Transport
46
     *
47
     * @var TransportInterface
48
     */
49
    protected $transport;
50
51
    /**
52
     * Default from address to use if no from address is set in the mail.
53
     *
54
     * @var string
55
     */
56
    protected $from;
57
58
    /**
59
     * Value for the X-Mailer header.
60
     *
61
     * @var string
62
     */
63
    protected $mailer;
64
65
    /**
66
     * If set, all mails are send to the addresses in this list
67
     *
68
     * This is useful when developing.
69
     *
70
     * @var AddressList|null
71
     */
72
    protected $overrideRecipient;
73
74
    protected $language;
75
76
    protected $shareByDefault = false;
77
78
    protected $invokableClasses = array(
79
        'simple'         => '\Laminas\Mail\Message',
80
        'stringtemplate' => '\Core\Mail\StringTemplateMessage',
81
    );
82
83
    protected $factories = array(
84
        'htmltemplate'   => [HTMLTemplateMessage::class,'factory'],
85
    );
86
87
    protected $queue;
88
89
    /**
90
     * Creates an instance.
91
     *
92
     * Adds two default initializers:
93
     * - Inject the translator to mails implementing TranslatorAwareInterface
94 17
     * - Call init() method on Mails if such method exists.
95
     *
96 17
     * @param ContainerInterface $container
97
     * @param mixed $configuration
98 17
     */
99
    public function __construct($container, $configuration = [])
100 1
    {
101 1
        parent::__construct($container, $configuration);
102 1
103 1
        $this->addInitializer(
104 1
            function ($context, $instance) {
105
                if ($instance instanceof TranslatorAwareInterface) {
106 1
                    $translator = $context->get('translator');
107
                    $instance->setTranslator($translator);
108 1
                    if (null === $instance->getTranslatorTextDomain()) {
0 ignored issues
show
introduced by
The condition null === $instance->getTranslatorTextDomain() is always false.
Loading history...
109
                        $instance->setTranslatorTextDomain();
110
                    }
111 17
                    $instance->setTranslatorEnabled(true);
112
                }
113
                if ($instance instanceof ContainerAwareInterface) {
114
                    $instance->setContainer($context);
115
                }
116
            }
117
        );
118
119
        //@TODO: [ZF3] verify that removing this lines is save
120
        //$this->addInitializer(
121
        //   function ($context,$instance) {
122
        //        if (method_exists($instance, 'setServiceLocator')) {
123 17
        //            //$instance->setServiceLocator($this);
124
        //        }
125 1
        //   }
126 1
        //);
127
128 17
        $this->addInitializer(
129
            function ($context, $instance) {
130
                if (method_exists($instance, 'init')) {
131
                    $instance->init();
132
                }
133
            }
134
        );
135
    }
136
137 3
    /**
138
     * Checks that a plugin is a child of an email message.
139 3
     *
140 1
     * @throws \InvalidArgumentException
141 1
     */
142 1
    public function validate($plugin)
143 1
    {
144
        if (!$plugin instanceof MailMessage) {
145
            throw new \InvalidArgumentException(
146
                sprintf(
147
                    'Expected instance of \Laminas\Mail\Message but received %s',
148
                    get_class($plugin)
149
                )
150
            );
151
        }
152
    }
153
154 5
    /**
155
     * Gets the default from address
156 5
     *
157
     * @return null|String|Address|AddressList|array
158
     */
159
    public function getFrom()
160
    {
161
        return $this->from;
162
    }
163
164
    /**
165
     * Sets the default from address.
166
     *
167 9
     * @param string|AddressList|Address $email
168
     * @param String|null                $name
169 9
     *
170 2
     * @return self
171
     */
172 9
    public function setFrom($email, $name = null)
173 8
    {
174 1
        if (is_array($email)) {
0 ignored issues
show
introduced by
The condition is_array($email) is always false.
Loading history...
175
            $this->from = [$email['email'] => $email['name']];
176
        } else {
177 9
            $this->from = is_object($email) || null === $name
178
                ? $email
179
                : array($email => $name);
180
        }
181
182
        return $this;
183
    }
184
185
    /**
186
     * Sets override recipients.
187 2
     *
188
     * @param AddressList $recipients
189 2
     *
190
     * @return self
191 2
     */
192
    public function setOverrideRecipient(AddressList $recipients)
193
    {
194
        $this->overrideRecipient = $recipients;
195
196
        return $this;
197
    }
198
199
    /**
200
     * Sends a mail.
201
     *
202 5
     * Sets default values where needed.
203
     *
204 5
     * @param string|MailMessage $mail
205 1
     * @param array          $options
206
     */
207
    public function send($mail, array $options = array())
208 5
    {
209 5
        if (!$mail instanceof MailMessage) {
210
            $mail = $this->get($mail, $options);
211 5
        }
212 1
213
        $headers   = $mail->getHeaders();
214
        $transport = $this->getTransport();
215 5
216 1
        if (!$mail->isValid() && $this->from) {
217 1
            $mail->setFrom($this->from);
218 1
        }
219 1
220
        if ($this->overrideRecipient instanceof AddressList) {
221 1
            $originalRecipient = $headers->get('to')->toString();
0 ignored issues
show
Bug introduced by
The method toString() does not exist on ArrayIterator. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

221
            $originalRecipient = $headers->get('to')->/** @scrutinizer ignore-call */ toString();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
222 1
            if ($headers->has('cc')) {
223 1
                $originalRecipient .= '; ' . $headers->get('cc')->toString();
224
                $headers->removeHeader('cc');
225 1
            }
226 1
            if ($headers->has('bcc')) {
227
                $originalRecipient .= '; ' . $headers->get('bcc')->toString();
228
                $headers->removeHeader('bcc');
229 5
            }
230 5
            $headers->addHeaderLine('X-Original-Recipients', $originalRecipient);
231 5
            $mail->setTo($this->overrideRecipient);
232 5
        }
233
234
        if (!$headers->has('X-Mailer')) {
235
            $mailerHeader = new \Laminas\Mail\Header\GenericHeader('X-Mailer', $this->getMailer());
236
            $headers->addHeader($mailerHeader);
237
            $mailerHeader->setEncoding('ASCII'); // get rid of other encodings for this header!
238
        }
239 5
240
        /* Allow HTMLTemplateMails to alter subject in the view script.
241
         * As the Zend Transport class build subject before the getBodyText call,
242
         * we have to call it here.
243 5
         */
244
        if ($mail instanceof \Core\Mail\HTMLTemplateMessage) {
245
            $mail->getBodyText();
246
        }
247
248
        $transport->send($mail);
249
    }
250
251 6
    public function queue($mail, $queueOptions = null)
252
    {
253 6
        $this->queue->push(MailJob::create($mail), $queueOptions);
254
    }
255
    /**
256
     * Gets the transport.
257
     *
258
     * @return TransportInterface $transport
259
     */
260
    public function getTransport()
261
    {
262
        return $this->transport;
263 8
    }
264
265 8
    /**
266
     * Sets the transport
267 8
     *
268
     * @param TransportInterface $transport
269
     *
270
     * @return self
271
     */
272
    public function setTransport(TransportInterface $transport)
273
    {
274
        $this->transport = $transport;
275 6
276
        return $this;
277 6
    }
278
279
    /**
280
     * Gest the value of the X-Mailer header.
281
     *
282
     * @return string
283
     */
284
    public function getMailer()
285
    {
286
        return $this->mailer;
287 4
    }
288
289 4
    /**
290
     * Sets the value for the X-Mailer header
291 4
     *
292
     * @param string $mailer
293
     *
294
     * @return $this
295
     */
296
    public function setMailer($mailer)
297
    {
298
        $this->mailer = $mailer;
299
300
        return $this;
301
    }
302
303
    /**
304
     * Get queue
305
     *
306
     * @return MongoQueue
307
     */
308
    public function getQueue()
309
    {
310
        if (!$this->queue) {
311
            throw new MissingDependencyException(MongoQueue::class, $this);
312
        }
313
314
        return $this->queue;
315
    }
316
317
    /**
318
     * Set queue
319
     *
320
     * @param MongoQueue $queue
321
     */
322
    public function setQueue(MongoQueue $queue): void
323
    {
324
        $this->queue = $queue;
325
    }
326
}
327