-
Notifications
You must be signed in to change notification settings - Fork 2
/
MailAdapterFactory.php
70 lines (59 loc) · 2.21 KB
/
MailAdapterFactory.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<?php
declare(strict_types=1);
namespace Sendportal\Base\Factories;
use InvalidArgumentException;
use Sendportal\Base\Adapters\MailgunMailAdapter;
use Sendportal\Base\Adapters\MailjetAdapter;
use Sendportal\Base\Adapters\PostmarkMailAdapter;
use Sendportal\Base\Adapters\SendgridMailAdapter;
use Sendportal\Base\Adapters\SesMailAdapter;
use Sendportal\Base\Adapters\SmtpMailAdapter;
use Sendportal\Base\Interfaces\MailAdapterInterface;
use Sendportal\Base\Models\EmailService;
use Sendportal\Base\Models\EmailServiceType;
class MailAdapterFactory
{
/** @var array */
public static $adapterMap = [
EmailServiceType::SES => SesMailAdapter::class,
EmailServiceType::SENDGRID => SendgridMailAdapter::class,
EmailServiceType::MAILGUN => MailgunMailAdapter::class,
EmailServiceType::POSTMARK => PostmarkMailAdapter::class,
EmailServiceType::MAILJET => MailjetAdapter::class,
EmailServiceType::SMTP => SmtpMailAdapter::class
];
/**
* Cache of resolved mail adapters.
*
* @var array
*/
private $adapters = [];
/**
* Get a mail adapter instance.
*/
public function adapter(EmailService $emailService): MailAdapterInterface
{
return $this->adapters[$emailService->id] ?? $this->cache($this->resolve($emailService), $emailService);
}
/**
* Cache a resolved adapter for the given provider.
*/
private function cache(MailAdapterInterface $adapter, EmailService $emailService): MailAdapterInterface
{
return $this->adapters[$emailService->id] = $adapter;
}
/**
* @throws InvalidArgumentException
*/
private function resolve(EmailService $emailService): MailAdapterInterface
{
if (!$emailServiceType = EmailServiceType::resolve($emailService->type_id)) {
throw new InvalidArgumentException("Unable to resolve mail provider type from ID [$emailService->type_id].");
}
$adapterClass = self::$adapterMap[$emailService->type_id] ?? null;
if (!$adapterClass) {
throw new InvalidArgumentException("Mail adapter type [{$emailServiceType}] is not supported.");
}
return new $adapterClass($emailService->settings);
}
}