Passed
Pull Request — feature/eco-2295/dev (#1)
by Aleksey
05:36 queued 03:07
created

CrefoPayApiResponseValidator   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 17
dl 0
loc 62
rs 10
c 0
b 0
f 0
wmc 8

4 Methods

Rating   Name   Duplication   Size   Complexity  
A isResultCodeSuccess() 0 5 2
A __construct() 0 4 1
A validateMac() 0 9 2
A validateResponse() 0 7 3
1
<?php
2
3
/**
4
 * MIT License
5
 * For full license information, please view the LICENSE file that was distributed with this source code.
6
 */
7
8
namespace SprykerEco\Zed\CrefoPayApi\Business\Response\Validator;
9
10
use SprykerEco\Service\CrefoPayApi\CrefoPayApiServiceInterface;
11
use SprykerEco\Zed\CrefoPayApi\Dependency\External\Guzzle\Response\CrefoPayApiGuzzleResponseInterface;
12
13
class CrefoPayApiResponseValidator implements CrefoPayApiResponseValidatorInterface
14
{
15
    protected const API_HEADER_MAC = 'X-Payco-HMAC';
16
    protected const API_RESPONSE_FIELD_RESULT_CODE = 'resultCode';
17
    protected const RESULT_CODE_OK = 0;
18
    protected const RESULT_CODE_REDIRECT = 1;
19
20
    /**
21
     * @var \SprykerEco\Service\CrefoPayApi\CrefoPayApiServiceInterface
22
     */
23
    protected $service;
24
25
    /**
26
     * @param \SprykerEco\Service\CrefoPayApi\CrefoPayApiServiceInterface $service
27
     */
28
    public function __construct(
29
        CrefoPayApiServiceInterface $service
30
    ) {
31
        $this->service = $service;
32
    }
33
34
    /**
35
     * @param \SprykerEco\Zed\CrefoPayApi\Dependency\External\Guzzle\Response\CrefoPayApiGuzzleResponseInterface $response
36
     * @param array|null $responseData
37
     *
38
     * @return bool
39
     */
40
    public function validateResponse(
41
        CrefoPayApiGuzzleResponseInterface $response,
42
        ?array $responseData
43
    ): bool {
44
        return $responseData !== null
45
            && $this->isResultCodeSuccess($responseData)
46
            && $this->validateMac($response);
47
    }
48
49
    /**
50
     * @param array $responseData
51
     *
52
     * @return bool
53
     */
54
    protected function isResultCodeSuccess(array $responseData): bool
55
    {
56
        $resultCode = $responseData[static::API_RESPONSE_FIELD_RESULT_CODE] ?? null;
57
58
        return $resultCode === static::RESULT_CODE_OK || $resultCode === static::RESULT_CODE_REDIRECT;
59
    }
60
61
    /**
62
     * @param \SprykerEco\Zed\CrefoPayApi\Dependency\External\Guzzle\Response\CrefoPayApiGuzzleResponseInterface $response
63
     *
64
     * @return bool
65
     */
66
    protected function validateMac(CrefoPayApiGuzzleResponseInterface $response): bool
67
    {
68
        $mac = $response->getHeader(static::API_HEADER_MAC);
69
        if ($mac === null) {
70
            return false;
71
        }
72
73
        return $this->service
74
            ->validateMac([$response->getResponseBody()], $mac);
75
    }
76
}
77