This repository was archived by the owner on Jun 17, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathSpamChecker.php
52 lines (44 loc) · 1.65 KB
/
SpamChecker.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
<?php
namespace App;
use App\Entity\Comment;
use Symfony\Contracts\HttpClient\HttpClientInterface;
class SpamChecker
{
private $client;
private $endpoint;
public function __construct(HttpClientInterface $client, string $akismetKey)
{
$this->client = $client;
$this->endpoint = sprintf('https://%s.rest.akismet.com/1.1/comment-check', $akismetKey);
}
/**
* @return int Spam score: 0: not spam, 1: maybe spam, 2: blatant spam
*
* @throws \RuntimeException if the call did not work
*/
public function getSpamScore(Comment $comment, array $context): int
{
$response = $this->client->request('POST', $this->endpoint, [
'body' => array_merge($context, [
'blog' => 'https://guestbook.example.com',
'comment_type' => 'comment',
'comment_author' => $comment->getAuthor(),
'comment_author_email' => $comment->getEmail(),
'comment_content' => $comment->getText(),
'comment_date_gmt' => $comment->getCreatedAt()->format('c'),
'blog_lang' => 'en',
'blog_charset' => 'UTF-8',
'is_test' => true,
]),
]);
$headers = $response->getHeaders();
if ('discard' === ($headers['x-akismet-pro-tip'][0] ?? '')) {
return 2;
}
$content = $response->getContent();
if (isset($headers['x-akismet-debug-help'][0])) {
throw new \RuntimeException(sprintf('Unable to check for spam: %s (%s).', $content, $headers['x-akismet-debug-help'][0]));
}
return 'true' === $content ? 1 : 0;
}
}