Passed
Push — master ( a0632e...2294fc )
by Peter
03:03
created

Contact::submit()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 28
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 14
c 0
b 0
f 0
dl 0
loc 28
rs 9.7998
cc 4
nc 5
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace AbterPhp\Contact\Http\Controllers\Website;
6
7
use AbterPhp\Contact\Domain\Entities\Form;
8
use AbterPhp\Contact\Domain\Entities\Message;
9
use AbterPhp\Contact\Service\Execute\Message as MessageService;
10
use Opulence\Http\Responses\RedirectResponse;
11
use Opulence\Http\Responses\Response;
12
use Opulence\Routing\Controller;
13
use Psr\Log\LoggerInterface;
14
15
class Contact extends Controller
16
{
17
    const LOG_MSG_VALIDATION_ERROR = 'Validating contact message failed.';
18
    const LOG_MSG_SENDING_ERROR    = 'Sending contact message to %s failed.';
19
20
    /** @var MessageService */
21
    protected $messageService;
22
23
    /** @var LoggerInterface */
24
    protected $logger;
25
26
    /**
27
     * Contact constructor.
28
     *
29
     * @param MessageService $service
30
     */
31
    public function __construct(MessageService $service, LoggerInterface $logger)
32
    {
33
        $this->messageService = $service;
34
        $this->logger         = $logger;
35
    }
36
37
    /**
38
     * @return Response
39
     */
40
    public function submit(string $formIdentifier): Response
41
    {
42
        $postData = $this->request->getPost()->getAll();
43
44
        $errors = $this->messageService->validateForm($formIdentifier, $postData);
45
46
        if ($errors) {
47
            $this->logger->info(static::LOG_MSG_VALIDATION_ERROR, $errors);
48
49
            $url = $this->messageService->getForm($formIdentifier)->getFailureUrl();
50
51
            return $this->redirectTo($url);
52
        }
53
54
        /** @var Message $message */
55
        $message = $this->messageService->createEntity('');
56
        $message = $this->messageService->fillEntity($formIdentifier, $message, $postData, []);
57
58
        $url = $message->getForm()->getSuccessUrl();
59
        if ($this->messageService->send($message) < 1) {
60
            $url = $form->getFailureUrl();
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $form seems to be never defined.
Loading history...
61
        }
62
63
        foreach ($this->messageService->getFailedRecipients() as $recipient) {
64
            $this->logger->info(sprintf(static::LOG_MSG_SENDING_ERROR, $recipient), $errors);
65
        }
66
67
        return $this->redirectTo($url);
68
    }
69
70
    /**
71
     * @param string $url
72
     *
73
     * @return Response
74
     */
75
    private function redirectTo(string $url): Response
76
    {
77
        $response = new RedirectResponse($url);
78
        $response->send();
79
80
        return $response;
81
    }
82
}
83