Completed
Pull Request — master (#31)
by Vitaliy
17:18 queued 14:55
created

XsollaClient::factory()   B

Complexity

Conditions 3
Paths 1

Size

Total Lines 36
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 3

Importance

Changes 4
Bugs 0 Features 1
Metric Value
c 4
b 0
f 1
dl 0
loc 36
ccs 19
cts 19
cp 1
rs 8.8571
cc 3
eloc 26
nc 1
nop 1
crap 3
1
<?php
2
3
namespace Xsolla\SDK\API;
4
5
use Guzzle\Common\Collection;
6
use Guzzle\Common\Event;
7
use Guzzle\Http\Exception\BadResponseException;
8
use Guzzle\Service\Client;
9
use Guzzle\Service\Description\ServiceDescription;
10
use Xsolla\SDK\API\PaymentUI\TokenRequest;
11
use Xsolla\SDK\Exception\API\XsollaAPIException;
12
use Xsolla\SDK\Version;
13
14
/**
15
 * @method array CreatePaymentUIToken(array $args = array()) Create payment UI token. http://developers.xsolla.com/api.html#payment-ui
16
 *
17
 * @method array CreateSubscriptionPlan(array $args = array()) Create a recurrent plan. http://developers.xsolla.com/api.html#create-a-plan
18
 * @method array UpdateSubscriptionPlan(array $args = array()) Update a recurrent plan. http://developers.xsolla.com/api.html#update-a-plan
19
 * @method void DeleteSubscriptionPlan(array $args = array()) Delete a recurrent plan. http://developers.xsolla.com/api.html#delete-a-plan
20
 * @method void DisableSubscriptionPlan(array $args = array()) Disable a recurrent plan. http://developers.xsolla.com/api.html#disable-a-plan
21
 * @method void EnableSubscriptionPlan(array $args = array()) Enable a recurrent plan. http://developers.xsolla.com/api.html#enable-a-plan
22
 * @method array ListSubscriptionPlans(array $args = array()) List all recurrent plans. http://developers.xsolla.com/api.html#list-all-plans
23
 * @method array CreateSubscriptionProduct(array $args = array()) Create a product. http://developers.xsolla.com/api.html#create-a-product
24
 * @method array UpdateSubscriptionProduct(array $args = array()) Update a product. http://developers.xsolla.com/api.html#update-a-product
25
 * @method void DeleteSubscriptionProduct(array $args = array()) Delete a product. http://developers.xsolla.com/api.html#delete-a-product
26
 * @method array ListSubscriptionProducts(array $args = array()) List all recurrent products. http://developers.xsolla.com/api.html#list-all-products
27
 * @method array UpdateSubscription(array $args = array()) Update a recurrent subscription. It's available to update the status of subscription (active or canceled) and to postpone the date of the next charge for current subscription. http://developers.xsolla.com/api.html#update-subscription
28
 * @method array ListSubscriptions(array $args = array()) List all recurrent subscriptions. http://developers.xsolla.com/api.html#list-all-subscriptions
29
 * @method array ListSubscriptionPayments(array $args = array()) List all recurrent payments. http://developers.xsolla.com/api.html#list-all-payments
30
 * @method array ListUserSubscriptionPayments(array $args = array()) List all recurrent payments by user. http://developers.xsolla.com/api.html#list-all-payments-by-user
31
 * @method array ListSubscriptionCurrencies(array $args = array()) List all recurrent currencies. http://developers.xsolla.com/api.html#list-all-currencies
32
 *
33
 * @method array ListUserAttributes(array $args = array()) Get list of user attributes. http://developers.xsolla.com/api.html#list-all-user-attributes
34
 * @method array GetUserAttribute(array $args = array()) Show a user attribute. http://developers.xsolla.com/api.html#get-user-attribute
35
 * @method array CreateUserAttribute(array $args = array()) Create user attribute. http://developers.xsolla.com/api.html#create-user-attribute
36
 * @method void UpdateUserAttribute(array $args = array()) Update user attribute. http://developers.xsolla.com/api.html#update-user-attribute
37
 * @method void DeleteUserAttribute(array $args = array()) Delete a user attribute. http://developers.xsolla.com/api.html#delete-user-attribute
38
 *
39
 * @method array CreateVirtualItem(array $args = array()) Create a virtual item. http://developers.xsolla.com/api.html#create-an-item
40
 * @method array GetVirtualItem(array $args = array()) Get a virtual item. http://developers.xsolla.com/api.html#get-an-item
41
 * @method void UpdateVirtualItem(array $args = array()) Update a virtual item. http://developers.xsolla.com/api.html#update-an-item
42
 * @method void DeleteVirtualItem(array $args = array()) Delete a virtual item. http://developers.xsolla.com/api.html#delete-an-item
43
 * @method array ListVirtualItems(array $args = array()) List a virtual items. http://developers.xsolla.com/api.html#list-all-items
44
 * @method array CreateVirtualItemsGroup(array $args = array()) Create a virtual items group. http://developers.xsolla.com/api.html#create-a-group
45
 * @method array GetVirtualItemsGroup(array $args = array()) Get a virtual items group. http://developers.xsolla.com/api.html#get-a-group
46
 * @method void UpdateVirtualItemsGroup(array $args = array()) Update a virtual items group. http://developers.xsolla.com/api.html#update-a-group
47
 * @method void DeleteVirtualItemsGroup(array $args = array()) Delete a virtual items group. http://developers.xsolla.com/api.html#delete-a-group
48
 * @method array ListVirtualItemsGroups(array $args = array()) List all virtual items groups. http://developers.xsolla.com/api.html#list-all-groups
49
 * @method void UpdateVirtualItemOrderInGroup(array $args = array()) Update items order in group. http://developers.xsolla.com/api.html#change-an-items-order
50
 *
51
 * @method array GetProjectVirtualCurrencySettings(array $args = array()) Get project virtual currency settings. http://developers.xsolla.com/api.html#list-the-currency-package
52
 * @method void UpdateProjectVirtualCurrencySettings(array $args = array()) Update project virtual currency settings. http://developers.xsolla.com/api.html#update-the-currency-package
53
 *
54
 * @method void CreateWalletUser(array $args = array()) Create a new user. http://developers.xsolla.com/api.html#create-a-new-user
55
 * @method array GetWalletUser(array $args = array()) Retrieve a user data. http://developers.xsolla.com/api.html#get-a-user
56
 * @method void UpdateWalletUser(array $args = array()) Update user's information. http://developers.xsolla.com/api.html#update-an-user
57
 * @method array ListWalletUsers(array $args = array()) List all users. http://developers.xsolla.com/api.html#list-all-users
58
 * @method array ListWalletUserOperations(array $args = array()) List all operations. http://developers.xsolla.com/api.html#list-all-operations
59
 * @method array RechargeWalletUserBalance(array $args = array()) Change a balance. http://developers.xsolla.com/api.html#change-a-balance
60
 * @method array ListWalletUserVirtualItems(array $args = array()) Get user's virtual items. http://developers.xsolla.com/api.html#list-all-virtual-items
61
 * @method void AddVirtualItemToWalletUser(array $args = array()) Add the virtual items to the user's account. http://developers.xsolla.com/api.html#add-items-to-the-user
62
 * @method void DeleteVirtualItemFromWalletUser(array $args = array()) Delete the virtual items from the user's account. http://developers.xsolla.com/api.html#delete-items-from-the-user
63
 *
64
 * @method array GetCoupon(array $args = array()) Get information about coupon by code. http://developers.xsolla.com/api.html#get-a-coupon
65
 * @method array RedeemCoupon(array $args = array()) Redeem coupon by code. http://developers.xsolla.com/api.html#redeem-a-coupon
66
 *
67
 * @method array CreatePromotion(array $args = array()) Create a new promotion. http://developers.xsolla.com/api.html#create-a-new-promotion
68
 * @method array GetPromotion(array $args = array()) Get a promotion. http://developers.xsolla.com/api.html#get-the-promotion
69
 * @method void UpdatePromotion(array $args = array()) Update a promotion. If the promotion is read-only (read_only = true), you are not allowed to change "project_id" parameter. http://developers.xsolla.com/api.html#update-the-promotion
70
 * @method array ReviewPromotion(array $args = array()) Check the promotion, if it is ready for activation. This method returns the list of errors (if they exist). http://developers.xsolla.com/api.html#review-the-promotion
71
 * @method void TogglePromotion(array $args = array()) Toggle the promotion. Change the status of promotion from enabled to disabled and vice versa. http://developers.xsolla.com/api.html#toggle-the-promotion
72
 * @method void DeletePromotion(array $args = array()) Delete a promotion. Only disabled promotion is allowed to delete (enabled = false). http://developers.xsolla.com/api.html#delete-the-promotion
73
 * @method array ListPromotions(array $args = array()) List all promotions. http://developers.xsolla.com/api.html#list-all-promotions
74
 * @method array GetPromotionSubject(array $args = array()) Get the subject of the promotion. http://developers.xsolla.com/api.html#get-the-subject
75
 * @method void SetPromotionSubject(array $args = array()) Set the subject of the promotion. If the promotion is read-only (read_only = true), you are not allowed to update the subject. The subject can take the following values: "purchase", or "items", or "packages". http://developers.xsolla.com/api.html#set-the-subject
76
 * @method array GetPromotionPaymentSystems(array $args = array()) Get the payment systems of the promotion. If the payment systems list is empty, the promotion will be valid for all payment systems. http://developers.xsolla.com/api.html#get-the-payment-systems
77
 * @method void SetPromotionPaymentSystems(array $args = array()) Set the payment systems of the promotion. If the payment systems list is empty, the promotion will be applied for all payment systems. If the promotion is read-only (read_only = true), you are not allowed to call this command. http://developers.xsolla.com/api.html#set-the-payment-systems
78
 * @method array GetPromotionPeriods(array $args = array()) Get the periods of the promotion. http://developers.xsolla.com/api.html#get-the-periods
79
 * @method void SetPromotionPeriods(array $args = array()) Set the periods of the promotion. If the promotion is read-only (read_only = true), you are not allowed to edit existing periods, add new periods only. http://developers.xsolla.com/api.html#set-the-periods
80
 * @method array GetPromotionRewards(array $args = array()) Get the rewards of the promotion. http://developers.xsolla.com/api.html#get-the-rewards
81
 * @method void SetPromotionRewards(array $args = array()) Set the rewards to the promotion. If the promotion is read-only (read_only = true), you are not allowed to update the rewards. http://developers.xsolla.com/api.html#set-the-rewards
82
 *
83
 * @method array ListEvents(array $args = array()) List all events from Xsolla Event System. http://developers.xsolla.com/api.html#list-all-events
84
 *
85
 * @method array SearchPaymentsRegistry(array $args = array()) Get a transaction list based on specific search parameters. JSON, CSV or XML will be returned in response from the API. http://developers.xsolla.com/api.html#search-all-transactions
86
 * @method array ListPaymentsRegistry(array $args = array()) Get information about all transactions for specified data range/transfer/report in different data formats. JSON, CSV or XML will be returned in response from the API. http://developers.xsolla.com/api.html#list-all-transactions
87
 * @method array ListTransfersRegistry(array $args = array()) List all transfers. http://developers.xsolla.com/api.html#list-all-transfers
88
 * @method array ListReportsRegistry(array $args = array()) Get a list of finance reports for specified data range. http://developers.xsolla.com/api.html#list-all-reports
89
 * @method void CreateRefundRequest(array $args = array()) Send a refund request. Money will be returned to user. http://developers.xsolla.com/api.html#send-a-refund-request
90
 *
91
 * @method array ListSupportTickets(array $args = array()) List all tickets. http://developers.xsolla.com/api.html#list-all-tickets
92
 * @method array ListSupportTicketComments(array $args = array()) List all comments. http://developers.xsolla.com/api.html#list-all-comments
93
 *
94
 * @method array CreateGameDeliveryEntity(array $args = array()) Create game delivery entity http://developers.xsolla.com/api.html#create-game-delivery-entity
95
 * @method array GetGameDeliveryEntity(array $args = array()) Get a game delivery entity http://developers.xsolla.com/api.html#get-a-game-delivery-entity
96
 * @method void UpdateGameDeliveryEntity(array $args = array()) Update a game delivery entity http://developers.xsolla.com/api.html#update-a-game-delivery-entity
97
 * @method array ListGameDeliveryEntities(array $args = array()) List all game delivery entities http://developers.xsolla.com/api.html#list-all-game-delivery-entities
98
 * @method array ListGameDeliveryDrmPlatforms(array $args = array()) List available DRM platforms http://developers.xsolla.com/api.html#list-available-drm-platforms
99
 *
100
 * @method array GetPaystationVirtualCurrency(array $args = array()) Get virtual currency packages http://developers.xsolla.com/api.html#list-virtual-currency-packages
101
 * @method array GetPaystationVirtualGroups(array $args = array()) Get virtual items groups http://developers.xsolla.com/api.html#list-item-groups
102
 * @method array GetPaystationVirtualItems(array $args = array()) Get virtual items http://developers.xsolla.com/api.html#list-virtual-items
103
 * @method array GetPaystationSubscriptions(array $args = array()) Get available subscriptions http://developers.xsolla.com/api.html#list-subscription-plans
104
 * @method array GetPaystationBonus(array $args = array()) Get the information about active promotion http://developers.xsolla.com/api.html#list-promotions
105
 */
106
class XsollaClient extends Client
107
{
108
    /**
109
     * @var int
110
     */
111
    protected $merchantId;
112
113
    /**
114
     * @var Client
115
     */
116
    protected $guzzleClient;
117
118
    /**
119
     * @internal
120
     * @param  mixed  $value
121
     * @return string
122
     */
123 29
    public static function jsonEncode($value)
124
    {
125 29
        $flags = 0;
126 29
        if (defined('JSON_PRETTY_PRINT')) {
127 29
            $flags = JSON_PRETTY_PRINT;
128
        }
129
130 29
        return json_encode($value, $flags);
131
    }
132
133
    /**
134
     * @param  array  $config
135
     * @return static
136
     */
137 75
    public static function factory($config = array())
138
    {
139
        $default = array(
140 75
            'ssl.certificate_authority' => 'system',
141
        );
142
        $required = array(
143 75
            'merchant_id',
144
            'api_key',
145
        );
146 75
        $config = Collection::fromConfig($config, $default, $required);
147 75
        $client = new static(isset($config['base_url']) ? $config['base_url'] : null, $config);
148 75
        $client->setDescription(ServiceDescription::factory(__DIR__.'/Resources/xsolla-2015-07-23.php'));
149 75
        $client->setDefaultOption('auth', array($config['merchant_id'], $config['api_key'], 'Basic'));
150 75
        $client->setDefaultOption('headers', array('Accept' => 'application/json', 'Content-Type' => 'application/json'));
151 75
        $client->setDefaultOption('command.params', array('merchant_id' => $config['merchant_id']));
152 75
        $client->setUserAgent(Version::getVersion());
153 75
        $exceptionCb = function (Event $event) {
154 1
            $previous = $event['exception'];
155 1
            if ($previous instanceof BadResponseException) {
156 1
                $e = XsollaAPIException::fromBadResponse($previous);
157
            } else {
158
                /* @var \Exception $previous */
159
                $e = new XsollaAPIException(
160
                    'XsollaClient Exception: '.$previous->getMessage().' Please check troubleshooting section in README.md https://github.com/xsolla/xsolla-sdk-php#troubleshooting',
161
                    0,
162
                    $previous
163
                );
164
            }
165 1
            throw $e;
166 75
        };
167
        /* @var \Symfony\Component\EventDispatcher\EventDispatcherInterface $dispatcher */
168 75
        $dispatcher = $client->getEventDispatcher();
169 75
        $dispatcher->addListener('request.exception', $exceptionCb);
170
171 75
        return $client;
172
    }
173
174
    /**
175
     * @param  int    $projectId
176
     * @param  string $userId
177
     * @param  bool   $sandboxMode
178
     * @return string
179
     */
180 1
    public function createCommonPaymentUIToken($projectId, $userId, $sandboxMode = false)
181
    {
182 1
        $tokenRequest = new TokenRequest($projectId, $userId);
183 1
        $tokenRequest->setSandboxMode($sandboxMode);
184
185 1
        return $this->createPaymentUITokenFromRequest($tokenRequest);
186
    }
187
188
    /**
189
     * @param  TokenRequest $tokenRequest
190
     * @return string
191
     */
192 2
    public function createPaymentUITokenFromRequest(TokenRequest $tokenRequest)
193
    {
194 2
        $parsedResponse = $this->CreatePaymentUIToken(array('request' => $tokenRequest->toArray()));
195
196 2
        return $parsedResponse['token'];
197
    }
198
}
199