EmailTransport::resolveBody()   A
last analyzed

Complexity

Conditions 4
Paths 3

Size

Total Lines 15
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 7
c 1
b 0
f 0
dl 0
loc 15
rs 10
cc 4
nc 3
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Setono\SyliusStockMovementPlugin\Transport;
6
7
use Setono\SyliusStockMovementPlugin\Mailer\Emails;
8
use Setono\SyliusStockMovementPlugin\Model\ReportConfigurationInterface;
9
use Setono\SyliusStockMovementPlugin\Model\ReportInterface;
10
use Sylius\Component\Mailer\Sender\SenderInterface;
11
use Symfony\Component\Routing\RouterInterface;
12
13
final class EmailTransport implements TransportInterface
14
{
15
    /** @var SenderInterface */
16
    private $sender;
17
18
    /** @var RouterInterface */
19
    private $router;
20
21
    public function __construct(SenderInterface $sender, RouterInterface $router)
22
    {
23
        $this->sender = $sender;
24
        $this->router = $router;
25
    }
26
27
    public function send(string $file, array $configuration, ReportInterface $report, ReportConfigurationInterface $reportConfiguration): void
28
    {
29
        $this->sender->send(Emails::REPORT, $configuration['to'], [
30
            'subject' => $this->resolveSubject($configuration['subject'] ?? null, $report),
31
            'body' => $this->resolveBody($configuration['body'] ?? null, $report),
32
        ]);
33
    }
34
35
    // todo these private methods should be put out in their own service, maybe Resolver/EmailContentResolverInterface
36
37
    private function resolveSubject(?string $subject, ReportInterface $report): string
38
    {
39
        if (null === $subject) {
40
            return 'Stock movement report ' . $report->getId();
41
        }
42
43
        return $this->resolvePlaceholders($subject, $report);
44
    }
45
46
    private function resolveBody(?string $body, ReportInterface $report): string
47
    {
48
        $reportUrl = $this->router->generate('setono_sylius_stock_movement_report_download', ['uuid' => $report->getUuid()], RouterInterface::ABSOLUTE_URL);
49
50
        if (null === $body || '' === $body) {
51
            return "Hi\n\nDownload the stock movement report here:\n\n$reportUrl";
52
        }
53
54
        if (strpos($body, '%report_url%') === false) {
55
            $body .= "\n\n%report_url%";
56
        }
57
58
        $body = str_replace('%report_url%', $reportUrl, $body);
59
60
        return $this->resolvePlaceholders($body, $report);
61
    }
62
63
    private function resolvePlaceholders(string $str, ReportInterface $report): string
64
    {
65
        return str_replace('%report_id%', $report->getId(), $str);
66
    }
67
}
68