Contact   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 69
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 6
eloc 24
c 1
b 0
f 0
dl 0
loc 69
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A submit() 0 28 4
A __construct() 0 4 1
A redirectTo() 0 6 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace AbterPhp\Contact\Http\Controllers\Website;
6
7
use AbterPhp\Contact\Domain\Entities\Message; // @phan-suppress-current-line PhanUnreferencedUseNormal
8
use AbterPhp\Contact\Service\Execute\Message as MessageService;
9
use Opulence\Http\Responses\RedirectResponse;
10
use Opulence\Http\Responses\Response;
11
use Opulence\Routing\Controller;
12
use Psr\Log\LoggerInterface;
13
14
class Contact extends Controller
15
{
16
    const LOG_MSG_VALIDATION_ERROR = 'Validating contact message failed.';
17
    const LOG_MSG_SENDING_ERROR    = 'Sending contact message to %s failed.';
18
19
    /** @var MessageService */
20
    protected $messageService;
21
22
    /** @var LoggerInterface */
23
    protected $logger;
24
25
    /**
26
     * Contact constructor.
27
     *
28
     * @param MessageService $service
29
     */
30
    public function __construct(MessageService $service, LoggerInterface $logger)
31
    {
32
        $this->messageService = $service;
33
        $this->logger         = $logger;
34
    }
35
36
    /**
37
     * @param string $formIdentifier
38
     *
39
     * @return Response
40
     * @throws \Opulence\Orm\OrmException
41
     */
42
    public function submit(string $formIdentifier): Response
43
    {
44
        $postData = $this->request->getPost()->getAll();
45
46
        $errors = $this->messageService->validateForm($formIdentifier, $postData);
47
48
        if ($errors) {
49
            $this->logger->info(static::LOG_MSG_VALIDATION_ERROR, $errors);
50
51
            $url = $this->messageService->getForm($formIdentifier)->getFailureUrl();
52
53
            return $this->redirectTo($url);
54
        }
55
56
        /** @var Message $message */
57
        $message = $this->messageService->createEntity('');
58
        $message = $this->messageService->fillEntity($formIdentifier, $message, $postData, []);
59
60
        $url = $message->getForm()->getSuccessUrl();
61
        if ($this->messageService->send($message) < 1) {
62
            $url = $message->getForm()->getFailureUrl();
63
        }
64
65
        foreach ($this->messageService->getFailedRecipients() as $recipient) {
66
            $this->logger->info(sprintf(static::LOG_MSG_SENDING_ERROR, $recipient), $errors);
67
        }
68
69
        return $this->redirectTo($url);
70
    }
71
72
    /**
73
     * @param string $url
74
     *
75
     * @return Response
76
     */
77
    private function redirectTo(string $url): Response
78
    {
79
        $response = new RedirectResponse($url);
80
        $response->send();
81
82
        return $response;
83
    }
84
}
85