Completed
Push — master ( 5d5a83...c66fcc )
by Mehdi
02:05
created

IsTrueValidator::validate()   B

Complexity

Conditions 6
Paths 3

Size

Total Lines 27
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 15
c 1
b 0
f 0
nc 3
nop 2
dl 0
loc 27
rs 8.439
1
<?php
2
namespace CoinhiveBundle\Validator;
3
4
use GuzzleHttp\ClientInterface;
5
use Symfony\Component\Validator\Constraint;
6
use Symfony\Component\Validator\ConstraintValidator;
7
8
/**
9
 * Class IsTrueValidator
10
 */
11
class IsTrueValidator extends ConstraintValidator
12
{
13
    /**
14
     * @var
15
     */
16
    private $siteKey;
17
18
    /**
19
     * @var ClientInterface
20
     */
21
    private $client;
22
23
    /**
24
     * @param ClientInterface $client
25
     * @param $siteKey
26
     */
27
    public function __construct(
28
        ClientInterface $client,
29
        $siteKey
30
    )
31
    {
32
33
        $this->siteKey = $siteKey;
34
        $this->client = $client;
35
    }
36
37
    /**
38
     * @param mixed $token
39
     * @param Constraint $constraint
40
     * @return bool
41
     */
42
    public function validate($token, Constraint $constraint)
43
    {
44
        if (isset($token['coinhive-captcha-token']) && $token['coinhive-captcha-token']) {
45
            $res = $this->client
46
                ->request(
47
                    'POST',
48
                    'https://api.coinhive.com/token/verify',
49
                    [
50
                        'headers' => [
51
                            'hashes'     => 256,
52
                            'secret'     => $this->siteKey,
53
                            'token'     => $token['coinhive-captcha-token']
54
                        ]
55
                    ]
56
                )
57
                ->getBody()
58
                ->getContents()
59
            ;
60
61
            $res = json_decode($res, true);
62
63
            if ($res && isset($res['success']) && $res['success']) {
64
                return false;
65
            }
66
        }
67
68
        return $this->context->addViolation($constraint->message);
69
    }
70
}
71