Passed
Push — trunk ( 9f8579...29fffa )
by Christian
13:21 queued 11s
created

MailAttachmentsBuilder::mappingAttachments()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 10
nc 3
nop 3
dl 0
loc 18
rs 9.9332
c 1
b 0
f 0
1
<?php declare(strict_types=1);
2
3
namespace Shopware\Core\Content\Mail\Service;
4
5
use Doctrine\DBAL\Connection;
6
use Shopware\Core\Checkout\Document\Service\DocumentGenerator;
7
use Shopware\Core\Content\MailTemplate\MailTemplateEntity;
0 ignored issues
show
Bug introduced by
The type Shopware\Core\Content\Ma...late\MailTemplateEntity was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
8
use Shopware\Core\Content\MailTemplate\Subscriber\MailSendSubscriberConfig;
9
use Shopware\Core\Content\Media\MediaCollection;
10
use Shopware\Core\Content\Media\MediaEntity;
0 ignored issues
show
Bug introduced by
The type Shopware\Core\Content\Media\MediaEntity was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
11
use Shopware\Core\Content\Media\MediaService;
12
use Shopware\Core\Framework\Context;
13
use Shopware\Core\Framework\DataAbstractionLayer\Doctrine\FetchModeHelper;
14
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
15
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
16
use Shopware\Core\Framework\Uuid\Uuid;
17
18
/**
19
 * @internal
20
 *
21
 * @phpstan-type MailAttachments array<int, array{id?: string, content: string, fileName: string, mimeType: string|null}>
22
 */
23
class MailAttachmentsBuilder
24
{
25
    private MediaService $mediaService;
26
27
    private EntityRepository $mediaRepository;
28
29
    private DocumentGenerator $documentGenerator;
30
31
    private Connection $connection;
32
33
    public function __construct(
34
        MediaService $mediaService,
35
        EntityRepository $mediaRepository,
36
        DocumentGenerator $documentGenerator,
37
        Connection $connection
38
    ) {
39
        $this->mediaService = $mediaService;
40
        $this->mediaRepository = $mediaRepository;
41
        $this->documentGenerator = $documentGenerator;
42
        $this->connection = $connection;
43
    }
44
45
    /**
46
     * @param array<string, mixed> $eventConfig
47
     *
48
     * @return MailAttachments
49
     */
50
    public function buildAttachments(
51
        Context $context,
52
        MailTemplateEntity $mailTemplate,
53
        MailSendSubscriberConfig $extensions,
54
        array $eventConfig,
55
        ?string $orderId
56
    ): array {
57
        $attachments = [];
58
59
        foreach ($mailTemplate->getMedia() ?? [] as $mailTemplateMedia) {
60
            if ($mailTemplateMedia->getMedia() === null || $mailTemplateMedia->getLanguageId() !== $context->getLanguageId()) {
61
                continue;
62
            }
63
64
            $attachments[] = $this->mediaService->getAttachment(
65
                $mailTemplateMedia->getMedia(),
66
                $context
67
            );
68
        }
69
70
        $documentIds = $extensions->getDocumentIds();
71
72
        if (!empty($eventConfig['documentTypeIds']) && \is_array($eventConfig['documentTypeIds']) && $orderId) {
73
            $latestDocuments = $this->getLatestDocumentsOfTypes($orderId, $eventConfig['documentTypeIds']);
74
75
            $documentIds = array_unique(array_merge($documentIds, $latestDocuments));
76
        }
77
78
        if (!empty($documentIds)) {
79
            $extensions->setDocumentIds($documentIds);
80
            $attachments = $this->mappingAttachments($documentIds, $attachments, $context);
81
        }
82
83
        if (empty($extensions->getMediaIds())) {
84
            return $attachments;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $attachments returns the type array|array<mixed,array<string,mixed|string>> which is incompatible with the documented return type Shopware\Core\Content\Mail\Service\MailAttachments.
Loading history...
85
        }
86
87
        $criteria = new Criteria($extensions->getMediaIds());
88
        $criteria->setTitle('send-mail::load-media');
89
90
        /** @var MediaCollection<MediaEntity> $entities */
91
        $entities = $this->mediaRepository->search($criteria, $context);
92
93
        foreach ($entities as $media) {
94
            $attachments[] = $this->mediaService->getAttachment($media, $context);
0 ignored issues
show
Bug introduced by
$media of type array is incompatible with the type Shopware\Core\Content\Media\MediaEntity expected by parameter $media of Shopware\Core\Content\Me...ervice::getAttachment(). ( Ignorable by Annotation )

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

94
            $attachments[] = $this->mediaService->getAttachment(/** @scrutinizer ignore-type */ $media, $context);
Loading history...
95
        }
96
97
        return $attachments;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $attachments returns the type array|array<mixed,array<string,mixed|string>> which is incompatible with the documented return type Shopware\Core\Content\Mail\Service\MailAttachments.
Loading history...
98
    }
99
100
    /**
101
     * @param array<string> $documentTypeIds
102
     *
103
     * @return array<string>
104
     */
105
    private function getLatestDocumentsOfTypes(string $orderId, array $documentTypeIds): array
106
    {
107
        $documents = $this->connection->fetchAllAssociative(
108
            'SELECT
109
                LOWER(hex(`document`.`document_type_id`)) as doc_type,
110
                LOWER(hex(`document`.`id`)) as doc_id
111
            FROM `document`
112
            WHERE `document`.`order_id` = :orderId
113
            AND `document`.`document_type_id` IN (:documentTypeIds)
114
            ORDER BY `document`.`created_at` ASC',
115
            [
116
                'orderId' => Uuid::fromHexToBytes($orderId),
117
                'documentTypeIds' => Uuid::fromHexToBytesList($documentTypeIds),
118
            ],
119
            [
120
                'documentTypeIds' => Connection::PARAM_STR_ARRAY,
121
            ]
122
        );
123
124
        return array_column(FetchModeHelper::groupUnique($documents), 'doc_id');
125
    }
126
127
    /**
128
     * @param array<string> $documentIds
129
     * @param MailAttachments $attachments
130
     *
131
     * @return MailAttachments
132
     */
133
    private function mappingAttachments(array $documentIds, array $attachments, Context $context): array
134
    {
135
        foreach ($documentIds as $documentId) {
136
            $document = $this->documentGenerator->readDocument($documentId, $context);
137
138
            if ($document === null) {
139
                continue;
140
            }
141
142
            $attachments[] = [
143
                'id' => $documentId,
144
                'content' => $document->getContent(),
145
                'fileName' => $document->getName(),
146
                'mimeType' => $document->getContentType(),
147
            ];
148
        }
149
150
        return $attachments;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $attachments returns the type array|array<mixed,array<string,string>> which is incompatible with the documented return type Shopware\Core\Content\Mail\Service\MailAttachments.
Loading history...
151
    }
152
}
153