Completed
Pull Request — master (#21)
by Harry
06:22
created

Gigya::gameMechanics()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
/**
3
 * This file is part of graze/gigya-client
4
 *
5
 * Copyright (c) 2016 Nature Delivered Ltd. <https://www.graze.com>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 *
10
 * @license https://github.com/graze/gigya-client/blob/master/LICENSE.md
11
 * @link    https://github.com/graze/gigya-client
12
 */
13
14
namespace Graze\Gigya;
15
16
use BadMethodCallException;
17
use Graze\Gigya\Auth\CredentialsAuthMiddleware;
18
use Graze\Gigya\Auth\HttpsAuthMiddleware;
19
use Graze\Gigya\Auth\OAuth2\GigyaGrant;
20
use Graze\Gigya\Auth\OAuth2\OAuth2Middleware;
21
use Graze\Gigya\Endpoint\Accounts;
22
use Graze\Gigya\Endpoint\Audit;
23
use Graze\Gigya\Endpoint\Client;
24
use Graze\Gigya\Endpoint\Comments;
25
use Graze\Gigya\Endpoint\DataStore;
26
use Graze\Gigya\Endpoint\GameMechanics;
27
use Graze\Gigya\Endpoint\IdentityStorage;
28
use Graze\Gigya\Endpoint\Reports;
29
use Graze\Gigya\Endpoint\Saml;
30
use Graze\Gigya\Endpoint\Socialize;
31
use Graze\Gigya\Response\ResponseFactoryInterface;
32
use Graze\Gigya\Validation\ResponseValidatorInterface;
33
use Graze\Gigya\Validation\Signature;
34
use Graze\Gigya\Validation\UidSignatureValidator;
35
use GuzzleHttp\Client as GuzzleClient;
36
use GuzzleHttp\ClientInterface;
37
use GuzzleHttp\Handler\CurlHandler;
38
use GuzzleHttp\HandlerStack;
39
40
class Gigya
41
{
42
    const DC_EU = 'eu1';
43
    const DC_US = 'us1';
44
    const DC_AU = 'au1';
45
46
    const NAMESPACE_AUDIT            = 'audit';
47
    const NAMESPACE_ACCOUNTS         = 'accounts';
48
    const NAMESPACE_ACCOUNTS_TFA     = 'accounts.tfa';
49
    const NAMESPACE_SOCIALIZE        = 'socialize';
50
    const NAMESPACE_COMMENTS         = 'comments';
51
    const NAMESPACE_GAME_MECHANICS   = 'gm';
52
    const NAMESPACE_REPORTS          = 'reports';
53
    const NAMESPACE_DATA_STORE       = 'ds';
54
    const NAMESPACE_IDENTITY_STORAGE = 'ids';
55
    const NAMESPACE_FIDM             = 'fidm';
56
    const NAMESPACE_FIDM_SAML        = 'fidm.saml';
57
    const NAMESPACE_FIDM_SAML_IDP    = 'fidm.saml.idp';
58
59
    const CERTIFICATE_FILE = 'cacert.pem';
60
61
    const DATE_TIME_FORMAT = 'Y-m-d\TH:i:s.uP';
62
63
    /**
64
     * Data Center ID to use.
65
     *
66
     * - us1 - for the US datacenter
67
     * - eu1 - for the European datacenter
68
     * - au1 - for the Australian datacenter
69
     *
70
     * @var string (Default: eu1)
71
     */
72
    protected $dataCenter;
73
74
    /**
75
     * Collection of core options to be passed to each api request.
76
     *
77
     * @var array
78
     */
79
    protected $options = [];
80
81
    /**
82
     * Configuration to pass to the constructor of guzzle.
83
     *
84
     * @var array
85
     */
86
    protected $config = [];
87
88
    /**
89
     * @var ResponseValidatorInterface[]
90
     */
91
    protected $validators = [];
92
93
    /**
94
     * @var ResponseFactoryInterface
95
     */
96
    protected $factory = null;
97
98
    /**
99
     * @var ClientInterface
100
     */
101
    private $guzzle;
102
103
    /**
104
     * @param string      $apiKey
105
     * @param string      $secretKey
106
     * @param string|null $dataCenter
107
     * @param string|null $userKey
108
     * @param array       $config     Gigya configuration:
109
     *                                - auth <string> (Default: gigya) Type of authentication, gigya
110
     *                                (HttpsAuthMiddleware) is the default. 'credentials' provides
111
     *                                `client_id,client_secret` params, 'gigya-oauth2' uses an oauth2 access token
112
     *                                - uidValidator <bool> (Default: true) Include Uid Signature Validation
113
     *                                - factory <object> (Default: null) A ResponseFactoryInterface to use, if none is
114
     *                                provided ResponseFactory will be used
115
     *                                - guzzle <array> (Default: []) A configuration to pass to guzzle if required
116
     *                                - options <array> (Default: []) A set of options to pass to each request
117
     */
118 48
    public function __construct($apiKey, $secretKey, $dataCenter = null, $userKey = null, array $config = [])
119
    {
120 48
        $this->guzzleConfig = (isset($config['guzzle'])) ? $config['guzzle'] : [];
0 ignored issues
show
Bug introduced by
The property guzzleConfig does not seem to exist. Did you mean config?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
121
122 48
        if (!isset($this->guzzleConfig['handler'])) {
0 ignored issues
show
Bug introduced by
The property guzzleConfig does not seem to exist. Did you mean config?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
123
            $this->guzzleConfig['handler'] = new HandlerStack(new CurlHandler());
0 ignored issues
show
Bug introduced by
The property guzzleConfig does not seem to exist. Did you mean config?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
124
        }
125 48
        $this->handlerStack = $this->guzzleConfig['handler'];
0 ignored issues
show
Bug introduced by
The property handlerStack does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
Bug introduced by
The property guzzleConfig does not seem to exist. Did you mean config?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
126
127 48
        $this->guzzle = new GuzzleClient($this->guzzleConfig);
0 ignored issues
show
Bug introduced by
The property guzzleConfig does not seem to exist. Did you mean config?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
128
129 48
        if (isset($config['options'])) {
130 3
            $this->addOptions($config['options']);
131
        }
132 48
        $this->addOption('verify', __DIR__ . '/' . static::CERTIFICATE_FILE);
133
134 48
        $this->addHandler(HttpsAuthMiddleware::middleware($apiKey, $secretKey, $userKey));
135 48
        $this->addHandler(CredentialsAuthMiddleware::middleware($apiKey, $secretKey, $userKey));
136
137 48
        $auth = isset($config['auth']) ? $config['auth'] : 'gigya';
138
        switch ($auth) {
139 48
            case 'gigya-oauth2':
140 1
                $this->addOption('auth', 'gigya-oauth2');
141 1
                $this->addHandler(OAuth2Middleware::middleware(new GigyaGrant($this)));
142 1
                break;
143
            default:
144 47
                $this->addOption('auth', $auth);
145 47
                break;
146
        }
147
148 48
        if (!isset($config['uidValidator']) || $config['uidValidator'] === true) {
149 7
            $this->addValidator(new UidSignatureValidator(new Signature(), $secretKey));
150
        }
151
152 48
        if (isset($config['factory'])) {
153 41
            $this->setFactory($config['factory']);
154
        }
155 48
        $this->dataCenter = $dataCenter ?: static::DC_EU;
156 48
    }
157
158
    /**
159
     * Add an option to be passed through to Guzzle for the request.
160
     *
161
     * N.B. This will overwrite any existing options apart from query and verify
162
     *
163
     * @param string $option
164
     * @param mixed  $value
165
     *
166
     * @return $this
167
     */
168 48
    public function addOption($option, $value)
169
    {
170 48
        $this->options[$option] = $value;
171
172 48
        return $this;
173
    }
174
175
    /**
176
     * Add a set of options as key value pairs. These will be passed to the Guzzle request.
177
     *
178
     * N.B. This will overwrite any existing options apart from query and verify
179
     *
180
     * @param array $options
181
     *
182
     * @return $this
183
     */
184 5
    public function addOptions(array $options)
185
    {
186 5
        foreach ($options as $option => $value) {
187 5
            $this->addOption($option, $value);
188
        }
189
190 5
        return $this;
191
    }
192
193
    /**
194
     * @param ResponseValidatorInterface $validator
195
     *
196
     * @return $this
197
     */
198 10
    public function addValidator(ResponseValidatorInterface $validator)
199
    {
200 10
        $this->validators[] = $validator;
201
202 10
        return $this;
203
    }
204
205
    /**
206
     * @param callable $handler
207
     *
208
     * @return $this
209
     */
210 48
    public function addHandler(callable $handler)
211
    {
212 48
        $this->handlerStack->push($handler);
213
214 48
        return $this;
215
    }
216
217
    /**
218
     * @param callable $handler
219
     *
220
     * @return $this
221
     */
222 2
    public function removeHandler(callable $handler)
223
    {
224 2
        $this->handlerStack->remove($handler);
225
226 2
        return $this;
227
    }
228
229
    /**
230
     * @param ResponseFactoryInterface $factory
231
     *
232
     * @return $this
233
     */
234 41
    public function setFactory(ResponseFactoryInterface $factory)
235
    {
236 41
        $this->factory = $factory;
237
238 41
        return $this;
239
    }
240
241
    /**
242
     * @param string $method
243
     * @param array  $arguments
244
     *
245
     * @return Client
246
     */
247 7
    public function __call($method, array $arguments)
248
    {
249 7
        if (count($arguments) > 0) {
250 1
            throw new BadMethodCallException('No Arguments should be supplied for Gigya call');
251
        }
252
253 6
        return $this->endpointFactory($method);
254
    }
255
256
    /**
257
     * @param string $namespace
258
     * @param string $className
259
     *
260
     * @return Client
261
     */
262 47
    private function endpointFactory($namespace, $className = Client::class)
263
    {
264 47
        return new $className(
265 47
            $this->guzzle,
266
            $namespace,
267 47
            $this->dataCenter,
268 47
            $this->config,
269 47
            $this->options,
270 47
            $this->validators,
271 47
            $this->factory
272
        );
273
    }
274
275
    /**
276
     * @return Accounts
277
     */
278 30
    public function accounts()
279
    {
280 30
        return $this->endpointFactory(static::NAMESPACE_ACCOUNTS, Accounts::class);
281
    }
282
283
    /**
284
     * @return Audit
285
     */
286 1
    public function audit()
287
    {
288 1
        return $this->endpointFactory(static::NAMESPACE_AUDIT, Audit::class);
289
    }
290
291
    /**
292
     * @return Socialize
293
     */
294 2
    public function socialize()
295
    {
296 2
        return $this->endpointFactory(static::NAMESPACE_SOCIALIZE, Socialize::class);
297
    }
298
299
    /**
300
     * @return Comments
301
     */
302 1
    public function comments()
303
    {
304 1
        return $this->endpointFactory(static::NAMESPACE_COMMENTS, Comments::class);
305
    }
306
307
    /**
308
     * @return GameMechanics
309
     */
310 1
    public function gameMechanics()
311
    {
312 1
        return $this->endpointFactory(static::NAMESPACE_GAME_MECHANICS, GameMechanics::class);
313
    }
314
315
    /**
316
     * @return Reports
317
     */
318 1
    public function reports()
319
    {
320 1
        return $this->endpointFactory(static::NAMESPACE_REPORTS, Reports::class);
321
    }
322
323
    /**
324
     * @return DataStore
325
     */
326 1
    public function dataStore()
327
    {
328 1
        return $this->endpointFactory(static::NAMESPACE_DATA_STORE, DataStore::class);
329
    }
330
331
    /**
332
     * @return IdentityStorage
333
     */
334 1
    public function identityStorage()
335
    {
336 1
        return $this->endpointFactory(static::NAMESPACE_IDENTITY_STORAGE, IdentityStorage::class);
337
    }
338
339
    /**
340
     * @return Saml
341
     */
342 3
    public function saml()
343
    {
344 3
        return $this->endpointFactory(static::NAMESPACE_FIDM, Saml::class);
345
    }
346
}
347