SubscriptionsClient   A
last analyzed

Complexity

Total Complexity 12

Size/Duplication

Total Lines 107
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 42.55%

Importance

Changes 2
Bugs 1 Features 1
Metric Value
wmc 12
c 2
b 1
f 1
lcom 1
cbo 4
dl 0
loc 107
rs 10
ccs 20
cts 47
cp 0.4255

8 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A cancel() 0 4 1
A defer() 0 12 1
A refund() 0 4 1
A revokeSubscription() 0 4 1
A sendRequest() 0 3 1
B makeRequest() 0 19 5
A createRequest() 0 10 1
1
<?php
2
/*
3
 * Copyright 2015 Alexey Maslov <[email protected]>
4
 *
5
 * Licensed under the Apache License, Version 2.0 (the "License");
6
 * you may not use this file except in compliance with the License.
7
 * You may obtain a copy of the License at
8
 *
9
 * http://www.apache.org/licenses/LICENSE-2.0
10
 *
11
 * Unless required by applicable law or agreed to in writing, software
12
 * distributed under the License is distributed on an "AS IS" BASIS,
13
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
 * See the License for the specific language governing permissions and
15
 * limitations under the License.
16
 */
17
18
namespace alxmsl\Google\AndroidPublisher\Purchases\Subscriptions;
19
20
use alxmsl\Google\AndroidPublisher\Purchases\Client;
21
use alxmsl\Google\AndroidPublisher\Exception\ErrorException;
22
use alxmsl\Google\AndroidPublisher\Exception\InvalidCredentialsException;
23
use alxmsl\Network\Exception\HttpClientErrorCodeException;
24
use alxmsl\Network\Exception\HttpServerErrorCodeException;
25
use alxmsl\Network\Exception\TransportException;
26
use alxmsl\Network\Http\Request;
27
use UnexpectedValueException;
28
29
/**
30
 * Client for Google Play subscriptions API
31
 * @author alxmsl
32
 */
33
final class SubscriptionsClient extends Client implements SubscriptionsClientInterface {
34 1
    public function __construct() {
35 1
        parent::__construct(self::TYPE_SUBSCRIPTIONS);
36 1
    }
37
38
    /**
39
     * @inheritdoc
40
     */
41
    public function cancel($productId, $token) {
42
        $this->sendRequest('cancel', $productId, $token);
43
        return true;
44
    }
45
46
    /**
47
     * @inheritdoc
48
     */
49
    public function defer($productId, $expectedTimeMillis, $desiredTimeMillis, $token) {
50
        $Request = $this->createRequest('defer', $productId, $token)
51
            ->setPostData(json_encode([
52
                'deferralInfo' => [
53
                    'expectedExpiryTimeMillis' => $expectedTimeMillis,
54
                    'desiredExpiryTimeMillis'  => $desiredTimeMillis,
55
                ],
56
            ]));
57
        $response = $this->makeRequest($Request);
58
        $Object   = json_decode($response);
59
        return $Object->newExpiryTimeMillis;
60
    }
61
62
    /**
63
     * @inheritdoc
64
     */
65
    public function refund($productId, $token) {
66
        $this->sendRequest('refund', $productId, $token);
67
        return true;
68
    }
69
70
    /**
71
     * @inheritdoc
72
     */
73 1
    public function revokeSubscription($productId, $token) {
74 1
        $this->sendRequest('revoke', $productId, $token);
75
        return true;
76
    }
77
78
    /**
79
     * Send command for Purchases Subscriptions API
80
     * @param string $command subscriptions API command
81
     * @param string $productId product identifier
82
     * @param string $token purchase product token
83
     * @return string API response body
84
     * @throws InvalidCredentialsException when access grants is not granted
85
     * @throws ErrorException when API error acquired
86
     * @throws TransportException when HTTP transport error occurred
87
     * @throws UnexpectedValueException when access token is empty for client
88
     */
89 1
    private function sendRequest($command, $productId, $token) {
90 1
        return $this->makeRequest($this->createRequest($command, $productId, $token));
91
    }
92
93
    /**
94
     * Send command for Purchases Subscriptions API
95
     * @param Request $Request request instance
96
     * @return string API response body
97
     * @throws InvalidCredentialsException when access grants is not granted
98
     * @throws ErrorException when API error acquired
99
     * @throws TransportException when HTTP transport error occurred
100
     * @throws UnexpectedValueException when access token is empty for client
101
     */
102 1
    private function makeRequest(Request $Request) {
103 1
        $accessToken = $this->getAccessToken();
104 1
        if (!empty($accessToken)) {
105
            try {
106
                return $Request->send();
107
            } catch (HttpClientErrorCodeException $Ex) {
108
                switch ($Ex->getCode()) {
109
                    case 401:
110
                        throw InvalidCredentialsException::initializeByString($Ex->getMessage());
111
                    default:
112
                        throw ErrorException::initializeByString($Ex->getMessage());
113
                }
114
            } catch (HttpServerErrorCodeException $Ex) {
115
                throw ErrorException::initializeByString($Ex->getMessage());
116
            }
117
        } else {
118 1
            throw new UnexpectedValueException('access token is empty');
119
        }
120
    }
121
122
    /**
123
     * Create request instance for command
124
     * @param string $command subscriptions API command
125
     * @param string $productId product identifier
126
     * @param string $token purchase product token
127
     * @return Request HTTP request instance
128
     */
129 1
    private function createRequest($command, $productId, $token) {
130 1
        $Request = $this->getRequest(self::ENDPOINT_PURCHASES)
131 1
            ->addUrlField('applications', $this->getPackage())
132 1
            ->addUrlField(self::URI_SUBSCRIPTIONS, '')
133 1
            ->addUrlField('products', $productId)
134 1
            ->addUrlField('tokens', sprintf('%s:%s', $token, $command))
135 1
            ->addGetField('access_token', $this->getAccessToken());
136 1
        $Request->setMethod(Request::METHOD_POST);
137 1
        return $Request;
138
    }
139
}
140