-
Notifications
You must be signed in to change notification settings - Fork 0
/
plugin.php
215 lines (187 loc) · 6.55 KB
/
plugin.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
<?php
declare(strict_types=1);
use herbie\Config;
use herbie\Plugin;
use herbie\Translator;
use herbie\TwigRenderer;
use herbie\UrlManager;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Tebe\HttpFactory\HttpFactory;
use Twig\TwigFunction;
class SimplecontactPlugin extends Plugin
{
private Config $config;
private array $errors = [];
private ServerRequestInterface $request;
private ResponseFactoryInterface $responseFactory;
private Translator $translator;
private TwigRenderer $twigRenderer;
private UrlManager $urlManager;
public function __construct(
Config $config,
ServerRequestInterface $request,
ResponseFactoryInterface $responseFactory,
Translator $translator,
TwigRenderer $twigRenderer,
UrlManager $urlManager
) {
$this->config = $config;
$this->request = $request;
$this->responseFactory = $responseFactory;
$this->translator = $translator;
$this->twigRenderer = $twigRenderer;
$this->urlManager = $urlManager;
}
public function twigFunctions(): array
{
return [
new TwigFunction('simplecontact', [$this, 'simplecontact'], ['is_safe' => ['html']])
];
}
public function simplecontact(): string
{
$status = $this->getQueryParam('status');
[$route] = $this->urlManager->parseRequest();
$formData = [];
$formErrors = [];
if ($this->formSubmitted()) {
$formData = $this->filterFormData($this->getFormData());
$formErrors = $this->validateFormData($formData);
if (empty($formErrors)) {
$recipient = $this->config->getAsString('plugins.simplecontact.config.recipient'); // validate email
$status = $this->sendEmail($formData, $recipient);
if ($status) {
$response = $this->createRedirectResponse($route, 'successful');
} else {
$response = $this->createRedirectResponse($route, 'failed');
}
$this->emitResponse($response);
exit;
}
}
if($this->formReset()) {
$formData = [];
$formErrors = [];
}
$template = $this->config->get('plugins.simplecontact.config.template', function () {
return $this->getComposerOrLocalTemplatesPath('form.twig');
});
return $this->twigRenderer->renderTemplate($template, [
'data' => $formData,
'errors' => $formErrors,
'status' => $status,
'route' => $route
]);
}
private function getFormData(): array
{
return $this->request->getParsedBody();
}
private function formSubmitted(): bool
{
if (!$this->isPostRequest()) {
return false;
}
$body = $this->request->getParsedBody();
return isset($body['button']) && ($body['button'] === 'submit');
}
private function formReset(): bool
{
if (!$this->isPostRequest()) {
return false;
}
$body = $this->request->getParsedBody();
return isset($body['button']) && ($body['button'] === 'reset');
}
private function isPostRequest(): bool
{
return $this->request->getMethod() === 'POST';
}
private function getQueryParam(string $name, string $default = ''): string
{
$params = $this->request->getQueryParams();
return (string)($params[$name] ?? $default);
}
private function validateFormData(array $data): array
{
extract($data); // name, email, message, antispam
$errors = [];
if (empty($name)) {
$errors['name'] = $this->translator->t('simplecontact', 'errorEmptyField');
}
if (empty($email)) {
$errors['email'] = $this->translator->t('simplecontact', 'errorEmptyField');
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors['email'] = $this->translator->t('simplecontact', 'errorInvalidEmail');
}
if (empty($message)) {
$errors['message'] = $this->translator->t('simplecontact', 'errorEmptyField');
}
return $errors;
}
/**
* @return array
*/
private function filterFormData(array $input): array
{
$defaults = [
'name' => '',
'email' => '',
'message' => '',
'antispam' => ''
];
$definition = [
'name' => FILTER_SANITIZE_STRING,
'email' => FILTER_SANITIZE_EMAIL,
'message' => FILTER_SANITIZE_STRING,
'antispam' => FILTER_SANITIZE_STRING
];
$filtered = (array)filter_var_array($input, $definition);
return array_merge($defaults, $filtered);
}
/**
* @return bool
*/
private function sendEmail(array $data, string $recipient): bool
{
// Antispam
if (!empty($data['antispam'])) {
return true;
}
$subject = $this->translator->t('simplecontact', 'mailSubject');
$message = "{$data['message']}\n\n";
$message .= "Name: {$data['name']}\n";
$message .= "Email: {$data['email']}\n\n";
$headers = "From: {$data['name']} <{$data['email']}>";
return mail($recipient, $subject, $message, $headers); // TODO replace with an smtp mailer
}
private function createRedirectResponse(string $route, string $status): ResponseInterface
{
$url = $this->urlManager->createAbsoluteUrl($route) . '?status=' . $status;
return $this->responseFactory->createResponse()->withHeader('Location', $url);
}
/**
* @param ResponseInterface $response
*/
private function emitResponse(ResponseInterface $response): void
{
$statusCode = $response->getStatusCode();
http_response_code($statusCode);
foreach ($response->getHeaders() as $k => $values) {
foreach ($values as $v) {
header(sprintf('%s: %s', $k, $v), false);
}
}
echo $response->getBody();
}
private function getComposerOrLocalTemplatesPath(string $name): string
{
$composerPath = '@vendor/getherbie/plugin-simplecontact/templates/' . $name;
$localPath = '@plugin/plugin-simplecontact/templates/' . $name;
return $this->twigRenderer->getTwigEnvironment()->getLoader()->exists($composerPath)
? $composerPath
: $localPath;
}
}