Passed
Push — master ( 178a27...59b625 )
by Peter
02:19
created

Message::getText()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 16
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 11
c 1
b 0
f 0
dl 0
loc 16
rs 9.9
cc 2
nc 2
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace AbterPhp\Contact\Service\Execute;
6
7
use AbterPhp\Contact\Constant\Event;
8
use AbterPhp\Contact\Domain\Entities\Form;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, AbterPhp\Contact\Service\Execute\Form. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
9
use AbterPhp\Contact\Domain\Entities\Message as Entity;
10
use AbterPhp\Contact\Orm\FormRepo;
11
use AbterPhp\Contact\Validation\Factory\Message as ValidatorFactory;
12
use AbterPhp\Framework\Domain\Entities\IStringerEntity;
13
use AbterPhp\Framework\Email\Sender;
14
use Opulence\Events\Dispatchers\IEventDispatcher;
15
use Opulence\Orm\OrmException;
16
17
class Message
18
{
19
    /** @var ValidatorFactory */
20
    protected $validatorFactory;
21
22
    /** @var FormRepo */
23
    protected $formRepo;
24
25
    /** @var Sender */
26
    protected $sender;
27
28
    /** @var IEventDispatcher */
29
    protected $eventDispatcher;
30
31
    /** @var Form[] */
32
    protected $forms = [];
33
34
    /**
35
     * Message constructor.
36
     *
37
     * @param FormRepo         $formRepo
38
     * @param ValidatorFactory $validatorFactory
39
     * @param IEventDispatcher $eventDispatcher
40
     * @param Sender           $sender
41
     */
42
    public function __construct(
43
        FormRepo $formRepo,
44
        ValidatorFactory $validatorFactory,
45
        IEventDispatcher $eventDispatcher,
46
        Sender $sender
47
    ) {
48
        $this->formRepo         = $formRepo;
49
        $this->validatorFactory = $validatorFactory;
50
        $this->eventDispatcher  = $eventDispatcher;
51
        $this->sender           = $sender;
52
    }
53
54
    /**
55
     * @param string $formIdentifier
56
     *
57
     * @return Form|null
58
     * @throws \Opulence\Orm\OrmException
59
     */
60
    public function getForm(string $formIdentifier): ?Form
61
    {
62
        if (array_key_exists($formIdentifier, $this->forms)) {
63
            return $this->forms[$formIdentifier];
64
        }
65
66
        try {
67
            $form = $this->formRepo->getByIdentifier($formIdentifier);
68
        } catch (OrmException $e) {
69
            try {
70
                $form = $this->formRepo->getById($formIdentifier);
71
            } catch (OrmException $e) {
72
                return null;
73
            }
74
        }
75
76
        $this->forms[$form->getIdentifier()] = $form;
77
78
        return $form;
79
    }
80
81
    /**
82
     * @param Entity $message
83
     *
84
     * @return int
85
     */
86
    public function send(Entity $message): int
87
    {
88
        $this->eventDispatcher->dispatch(Event::MESSAGE_READY, $message);
89
90
        $form       = $message->getForm();
91
        $recipients = [$form->getToEmail() => $form->getToName()];
92
93
        $replyToAddresses = [$message->getFromEmail() => $message->getFromName()];
94
        $fromAddresses    = $replyToAddresses;
95
96
        $result = $this->sender->send(
97
            $message->getSubject(),
98
            $message->getBody(),
99
            $recipients,
100
            $fromAddresses,
101
            $replyToAddresses
102
        );
103
104
        $this->eventDispatcher->dispatch(Event::MESSAGE_SENT, $message);
105
106
        return $result;
107
    }
108
109
    /**
110
     * @return array
111
     */
112
    public function getFailedRecipients(): array
113
    {
114
        return $this->sender->getFailedRecipients();
115
    }
116
117
    /**
118
     * @param string $formIdentifier
119
     * @param array  $postData
120
     *
121
     * @return array errors
122
     * @throws OrmException
123
     */
124
    public function validateForm(string $formIdentifier, array $postData): array
125
    {
126
        /** @var Form $form */
127
        $form = $this->getForm($formIdentifier);
128
        if (null === $form) {
129
            throw new \InvalidArgumentException();
130
        }
131
132
        $validator = $this->validatorFactory
133
            ->setMaxBodyLength($form->getMaxBodyLength())
134
            ->createValidator();
135
136
        if ($validator->isValid($postData)) {
137
            return [];
138
        }
139
140
        return $validator->getErrors()->getAll();
141
    }
142
143
    /**
144
     * @param string $entityId
145
     *
146
     * @return Entity|IStringerEntity
147
     */
148
    public function createEntity(string $entityId): IStringerEntity
149
    {
150
        $form = new Form('', '', '', '', '', '', '', 0);
151
152
        $message = new Entity($entityId, $form, '', '', '', '');
153
154
        return $message;
155
    }
156
157
    /**
158
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
159
     *
160
     * @param string          $formIdentifier
161
     * @param IStringerEntity $entity
162
     * @param array           $postData
163
     * @param array           $fileData
164
     *
165
     * @return IStringerEntity|Entity
166
     */
167
    public function fillEntity(
168
        string $formIdentifier,
169
        IStringerEntity $entity,
170
        array $postData,
171
        array $fileData
0 ignored issues
show
Unused Code introduced by
The parameter $fileData is not used and could be removed. ( Ignorable by Annotation )

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

171
        /** @scrutinizer ignore-unused */ array $fileData

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
172
    ): IStringerEntity {
173
        assert($entity instanceof Entity, new \InvalidArgumentException('Invalid entity'));
174
175
        $form = $this->getForm($formIdentifier);
176
        if (null === $form) {
177
            return $entity;
178
        }
179
180
        $entity
181
            ->setForm($form)
182
            ->setSubject($postData['subject'])
183
            ->setBody($postData['body'])
184
            ->setFromName($postData['from_name'])
185
            ->setFromEmail($postData['from_email']);
186
187
        return $entity;
188
    }
189
}
190