Passed
Push — master ( cd18e5...9103a9 )
by Alexander
01:59
created

MailerInterfaceProvider   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Test Coverage

Coverage 80%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 3
eloc 25
c 1
b 0
f 0
dl 0
loc 46
ccs 16
cts 20
cp 0.8
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 1
A register() 0 27 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace App\Provider;
6
7
use Swift_Transport;
8
use Swift_Plugins_LoggerPlugin;
9
use Psr\Container\ContainerInterface;
10
use Psr\EventDispatcher\EventDispatcherInterface;
11
use Psr\Log\LoggerInterface;
12
use Yiisoft\Aliases\Aliases;
13
use Yiisoft\Di\Container;
14
use Yiisoft\Di\Support\ServiceProvider;
15
use Yiisoft\Mailer\Composer;
16
use Yiisoft\Mailer\FileMailer;
17
use Yiisoft\Mailer\MailerInterface;
18
use Yiisoft\Mailer\MessageFactory;
19
use Yiisoft\Mailer\SwiftMailer\Logger;
20
use Yiisoft\Mailer\SwiftMailer\Mailer;
21
use Yiisoft\Mailer\SwiftMailer\Message;
22
use Yiisoft\View\WebView;
23
24
final class MailerInterfaceProvider extends ServiceProvider
25
{
26
    private string $composerPath;
27
    private bool $writeToFiles;
28
    private string $writeToFilesPath;
29
30 8
    public function __construct(
31
        string $composerPath = '@runtime/mail',
32
        bool $writeToFiles = false,
33
        string $writeToFilesPath = '@runtime/mail'
34
    ) {
35 8
        $this->composerPath = $composerPath;
36 8
        $this->writeToFiles = $writeToFiles;
37 8
        $this->writeToFilesPath = $writeToFilesPath;
38 8
    }
39
40
    /**
41
     * @suppress PhanAccessMethodProtected
42
     */
43 8
    public function register(Container $container): void
44
    {
45 8
        $container->set(MailerInterface::class, function (ContainerInterface $container) {
46 6
            $aliases = $container->get(Aliases::class);
47 6
            $logger = $container->get(LoggerInterface::class);
48 6
            $eventDispatcher = $container->get(EventDispatcherInterface::class);
49 6
            $view = $container->get(WebView::class);
50
51 6
            $messageFactory = new MessageFactory(Message::class);
52
53 6
            $composer = new Composer($view, $aliases->get($this->composerPath));
54
55 6
            if ($this->writeToFiles) {
56 6
                return new FileMailer(
57
                    $messageFactory,
58
                    $composer,
59
                    $eventDispatcher,
60
                    $logger,
61 6
                    $aliases->get($this->writeToFilesPath)
62
                );
63
            }
64
65
            $transport = $container->get(Swift_Transport::class);
66
            $mailer = new Mailer($messageFactory, $composer, $eventDispatcher, $logger, $transport);
67
            $mailer->registerPlugin(new Swift_Plugins_LoggerPlugin(new Logger($logger)));
68
69
            return $mailer;
70 8
        });
71 8
    }
72
}
73