Completed
Pull Request — master (#26)
by
unknown
01:44
created

Verifier::getServiceEndpoint()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 6
rs 9.4285
cc 2
eloc 4
nc 2
nop 0
1
<?php
2
3
namespace Mdb\PayPal\Ipn;
4
5
use Http\Client\HttpClient;
6
use Http\Message\MessageFactory;
7
8
class Verifier
9
{
10
    const STATUS_KEYWORD_VERIFIED = 'VERIFIED';
11
    const STATUS_KEYWORD_INVALID = 'INVALID';
12
13
    /**
14
     * @var HttpClient
15
     */
16
    private $httpClient;
17
18
    /**
19
     * @var MessageFactory
20
     */
21
    private $messageFactory;
22
23
    /**
24
     * @var bool
25
     */
26
    private $useSandbox;
27
28
    public function __construct(HttpClient $httpClient, MessageFactory $messageFactory, $useSandbox = false)
29
    {
30
        $this->httpClient = $httpClient;
31
        $this->messageFactory = $messageFactory;
32
        $this->useSandbox = $useSandbox;
33
    }
34
35
    /**
36
     * @param array $datas
37
     *
38
     * @return bool
39
     *
40
     * @throws \UnexpectedValueException
41
     */
42
    public function verify(array $datas)
43
    {
44
        $body = $this->httpClient->sendRequest($this->createRequest($datas))->getBody();
45
46
        $pattern = sprintf('/(%s|%s)/', self::STATUS_KEYWORD_VERIFIED, self::STATUS_KEYWORD_INVALID);
47
48
        if (!preg_match($pattern, $body)) {
49
            throw new \UnexpectedValueException(sprintf('Unexpected verification status encountered: %s', $body));
50
        }
51
52
        return $body === self::STATUS_KEYWORD_VERIFIED;
53
    }
54
55
    /**
56
     * @param array $datas
57
     *
58
     * @return \Psr\Http\Message\RequestInterface
59
     */
60
    protected function createRequest(array $datas)
61
    {
62
        $body = \GuzzleHttp\Psr7\build_query(['cmd' => '_notify-validate'] + $datas, PHP_QUERY_RFC1738);
63
64
        return $this->messageFactory->createRequest('POST', $this->getServiceEndpoint(), [], $body);
65
    }
66
67
    /**
68
     * @return string
69
     */
70
    protected function getServiceEndpoint()
71
    {
72
        return $this->useSandbox ?
73
            'https://www.sandbox.paypal.com/cgi-bin/webscr' :
74
            'https://www.paypal.com/cgi-bin/webscr';
75
    }
76
}
77