-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
BaseAPI.php
1325 lines (1164 loc) · 37.6 KB
/
BaseAPI.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Copyright (C) 2016-2020 Daniel Dolejška
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace RiotAPI\Base;
use RiotAPI\Base\Definitions\AsyncRequest;
use RiotAPI\Base\Definitions\CallCacheControl;
use RiotAPI\Base\Definitions\ICallCacheControl;
use RiotAPI\Base\Definitions\IPlatform;
use RiotAPI\Base\Definitions\Platform;
use RiotAPI\Base\Definitions\IRegion;
use RiotAPI\Base\Definitions\Region;
use RiotAPI\Base\Definitions\IRateLimitControl;
use RiotAPI\Base\Definitions\RateLimitControl;
use RiotAPI\Base\Exceptions\GeneralException;
use RiotAPI\Base\Exceptions\RequestException;
use RiotAPI\Base\Exceptions\ServerException;
use RiotAPI\Base\Exceptions\ServerLimitException;
use RiotAPI\Base\Exceptions\SettingsException;
use RiotAPI\Base\Exceptions\DataNotFoundException;
use RiotAPI\Base\Exceptions\ForbiddenException;
use RiotAPI\Base\Exceptions\UnauthorizedException;
use RiotAPI\Base\Exceptions\UnsupportedMediaTypeException;
use RiotAPI\Base\Objects\IApiObjectExtension;
use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;
use GuzzleHttp\Promise\PromiseInterface;
use GuzzleHttp\Promise\FulfilledPromise;
use GuzzleHttp\Promise\Utils;
use GuzzleHttp\Exception as GuzzleHttpExceptions;
use Psr\Cache\CacheItemPoolInterface;
use Psr\Http\Message\ResponseInterface;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
/**
* Class BaseAPI
*
* @package BaseAPI
*/
abstract class BaseAPI
{
/**
* Constants for cURL requests.
*/
const
METHOD_GET = 'GET',
METHOD_POST = 'POST',
METHOD_PUT = 'PUT',
METHOD_DELETE = 'DELETE';
/**
* Settings constants.
*/
const
SET_REGION = 'SET_REGION',
SET_ORIG_REGION = 'SET_ORIG_REGION',
SET_PLATFORM = 'SET_PLATFORM', /** Set internally by setting region **/
SET_VERIFY_SSL = 'SET_VERIFY_SSL', /** Specifies whether or not to verify SSL (verification often fails on localhost) **/
SET_KEY = 'SET_KEY', /** API key used by default **/
SET_KEY_INCLUDE_TYPE = 'SET_KEY_INCLUDE_TYPE', /** API key request include type (header, query) **/
SET_CACHE_PROVIDER = 'SET_CACHE_PROVIDER', /** Specifies CacheProvider class name **/
SET_CACHE_PROVIDER_PARAMS = 'SET_CACHE_PROVIDER_PARAMS', /** Specifies parameters passed to CacheProvider class when initializing **/
SET_CACHE_RATELIMIT = 'SET_CACHE_RATELIMIT', /** Used to set whether or not to saveCallData and check API key's rate limit **/
SET_CACHE_CALLS = 'SET_CACHE_CALLS', /** Used to set whether or not to temporary saveCallData API call's results **/
SET_CACHE_CALLS_LENGTH = 'SET_CACHE_CALLS_LENGTH', /** Specifies for how long are call results saved **/
SET_EXTENSIONS = 'SET_EXTENSIONS', /** Specifies ApiObject's extensions **/
SET_GUZZLE_CLIENT_CFG = 'SET_GUZZLE_CLIENT_CFG', /** Specifies configuration passed to Guzzle library client. */
SET_GUZZLE_REQ_CFG = 'SET_GUZZLE_REQ_CFG', /** Specifies configuration passed to Guzzle request. */
SET_CALLBACKS_BEFORE = 'SET_CALLBACKS_BEFORE',
SET_CALLBACKS_AFTER = 'SET_CALLBACKS_AFTER',
SET_API_BASEURL = 'SET_API_BASEURL',
SET_USE_DUMMY_DATA = 'SET_USE_DUMMY_DATA',
SET_SAVE_DUMMY_DATA = 'SET_SAVE_DUMMY_DATA',
SET_DEBUG = 'SET_DEBUG';
/**
* Available API key inclusion options.
*/
const
KEY_AS_QUERY_PARAM = 'keyInclude:query',
KEY_AS_HEADER = 'keyInclude:header';
/**
* Cache constants used to identify cache target.
*/
const
CACHE_KEY_RLC = 'rate-limit.cache',
CACHE_KEY_CCC = 'api-calls.cache';
/**
* Available API headers.
*/
const
HEADER_API_KEY = 'X-Riot-Token',
HEADER_RATELIMIT_TYPE = 'X-Rate-Limit-Type',
HEADER_METHOD_RATELIMIT = 'X-Method-Rate-Limit',
HEADER_METHOD_RATELIMIT_COUNT = 'X-Method-Rate-Limit-Count',
HEADER_APP_RATELIMIT = 'X-App-Rate-Limit',
HEADER_APP_RATELIMIT_COUNT = 'X-App-Rate-Limit-Count',
HEADER_DEPRECATION = 'X-Riot-Deprecated';
const
// List of required setting keys
SETTINGS_REQUIRED = [
self::SET_KEY,
self::SET_REGION,
],
// List of allowed setting keys
SETTINGS_ALLOWED = [
self::SET_KEY,
self::SET_REGION,
self::SET_VERIFY_SSL,
self::SET_KEY_INCLUDE_TYPE,
self::SET_CACHE_PROVIDER,
self::SET_CACHE_PROVIDER_PARAMS,
self::SET_CACHE_RATELIMIT,
self::SET_CACHE_CALLS,
self::SET_CACHE_CALLS_LENGTH,
self::SET_USE_DUMMY_DATA,
self::SET_SAVE_DUMMY_DATA,
self::SET_EXTENSIONS,
self::SET_GUZZLE_CLIENT_CFG,
self::SET_GUZZLE_REQ_CFG,
self::SET_CALLBACKS_BEFORE,
self::SET_CALLBACKS_AFTER,
self::SET_API_BASEURL,
self::SET_DEBUG,
],
SETTINGS_INIT_ONLY = [
self::SET_API_BASEURL,
self::SET_CACHE_PROVIDER,
self::SET_CACHE_PROVIDER_PARAMS,
];
/**
* Available resource list.
*
* @var array $resources
*/
protected $resources = [];
/**
* Contains current settings.
*
* @var array $settings
*/
protected $settings = array(
self::SET_API_BASEURL => '.api.riotgames.com',
self::SET_KEY_INCLUDE_TYPE => self::KEY_AS_HEADER,
self::SET_USE_DUMMY_DATA => false,
self::SET_SAVE_DUMMY_DATA => false,
self::SET_VERIFY_SSL => true,
self::SET_DEBUG => false,
self::SET_GUZZLE_CLIENT_CFG => [],
self::SET_GUZZLE_REQ_CFG => [],
);
/** @var IRegion $regions */
public $regions;
/** @var IPlatform $platforms */
public $platforms;
/** @var CacheItemPoolInterface $cache */
protected $cache;
/** @var IRateLimitControl $rlc */
protected $rlc;
/** @var int $rlc_savetime */
protected $rlc_savetime = 3600;
/** @var ICallCacheControl $ccc */
protected $ccc;
/** @var int $ccc_savetime */
protected $ccc_savetime = 60;
/** @var string $used_key */
protected $used_key = self::SET_KEY;
/** @var string $used_method */
protected $used_method;
/** @var string $endpoint */
protected $endpoint;
/** @var string $resource */
protected $resource;
/** @var string $resource_endpoint */
protected $resource_endpoint;
/** @var Client $guzzle */
protected $guzzle;
/** @var Client[] $async_clients */
protected $async_clients = [];
/** @var AsyncRequest[] $async_requests */
protected $async_requests = [];
/** @var AsyncRequest $next_async_request */
protected $next_async_request;
/** @var array $query_data */
protected $query_data = [];
/** @var array $post_data */
protected $post_data = [];
/** @var array $result_data */
protected $result_data;
/** @var string $result_data */
protected $result_data_raw;
/** @var array $result_headers */
protected $result_headers;
/** @var int $result_code */
protected $result_code;
/** @var callable[] $beforeCall */
protected $beforeCall = [];
/** @var callable[] $afterCall */
protected $afterCall = [];
/**
* BaseAPI constructor.
*
* @param array $settings
* @param IRegion $custom_regionDataProvider
* @param IPlatform $custom_platformDataProvider
*
* @throws SettingsException
* @throws GeneralException
*/
public function __construct(array $settings, IRegion $custom_regionDataProvider = null, IPlatform $custom_platformDataProvider = null)
{
// Checks if required settings are present
$settings_required = array_merge(self::SETTINGS_REQUIRED, $this::SETTINGS_REQUIRED);
foreach ($settings_required as $key)
if (array_search($key, array_keys($settings), true) === false)
throw new SettingsException("Required settings parameter '$key' is missing!");
// Assigns allowed settings
$settings_allowed = array_merge(self::SETTINGS_ALLOWED, $this::SETTINGS_ALLOWED);
foreach ($settings_allowed as $key)
if (isset($settings[$key]))
$this->settings[$key] = $settings[$key];
// Checks SET_KEY_INCLUDE_TYPE value
if (isset($settings[self::SET_KEY_INCLUDE_TYPE])
&& in_array($settings[self::SET_KEY_INCLUDE_TYPE], [self::KEY_AS_HEADER, self::KEY_AS_QUERY_PARAM], true) == false)
{
throw new SettingsException("Value of settings parameter '" . self::SET_KEY_INCLUDE_TYPE . "' is not valid.");
}
$this->regions = $custom_regionDataProvider ?: new Region();
$this->platforms = $custom_platformDataProvider ?: new Platform();
$this->guzzle = new Client($this->getSetting(self::SET_GUZZLE_CLIENT_CFG));
$this->_setupDefaultCacheProviderSettings();
// Setup API object extension classes
if ($this->isSettingSet(self::SET_EXTENSIONS))
$this->_setupExtensions();
// Some caching will be made, let's set up cache provider
if ($this->isSettingSet(self::SET_CACHE_CALLS) || $this->isSettingSet(self::SET_CACHE_RATELIMIT))
$this->_setupCacheProvider();
// Call data are going to be cached
if ($this->isSettingSet(self::SET_CACHE_CALLS))
$this->_setupCacheCalls();
// Set up before calls callbacks
$this->_setupBeforeCalls();
// Set up afterl calls callbacks
$this->_setupAfterCalls();
// Sets platform based on current region
$this->setSetting(self::SET_PLATFORM, $this->platforms->getPlatformNameOfRegion($this->getSetting(self::SET_REGION)));
}
/**
* Initializes library cache provider.
*
* @throws SettingsException
*/
protected function _setupExtensions()
{
if (!is_array($this->getSetting(self::SET_EXTENSIONS)))
throw new SettingsException("Value of settings parameter '" . self::SET_EXTENSIONS . "' is not valid. Array expected.");
foreach ($this->getSetting(self::SET_EXTENSIONS) as $api_object => $extender)
{
try
{
$ref = new \ReflectionClass($extender);
if ($ref->implementsInterface(IApiObjectExtension::class) == false)
throw new SettingsException("ObjectExtender '$extender' does not implement IApiObjectExtension interface.");
if ($ref->isInstantiable() == false)
throw new SettingsException("ObjectExtender '$extender' is not instantiable.");
}
catch (\ReflectionException $ex)
{
throw new SettingsException("Value of settings parameter '" . self::SET_EXTENSIONS . "' is not valid.", 0, $ex);
}
}
}
protected function _setupDefaultCacheProviderSettings()
{
// If something should be cached
if (!$this->isSettingSet(self::SET_CACHE_PROVIDER))
{
$this->settings[self::SET_CACHE_PROVIDER] = FilesystemAdapter::class;
}
if ($this->getSetting(self::SET_CACHE_PROVIDER) === FilesystemAdapter::class
&& !$this->isSettingSet(self::SET_CACHE_PROVIDER_PARAMS))
{
$this->settings[self::SET_CACHE_PROVIDER_PARAMS] = [
"RiotAPI-Default", // namespace
0, // default lifetime
sys_get_temp_dir() . "/RiotAPI" // directory
];
}
}
/**
* Initializes library cache provider.
*
* @throws SettingsException
*/
protected function _setupCacheProvider()
{
$this->cache = $this->_initializeCacheProvider(
$this->getSetting(self::SET_CACHE_PROVIDER),
$this->getSetting(self::SET_CACHE_PROVIDER_PARAMS, [])
);
// Loads existing cache or creates new storages
$this->loadCache();
}
/**
* @param $cacheProviderClass
* @param array $params
*
* @return CacheItemPoolInterface
*
* @throws SettingsException
*/
protected function _initializeCacheProvider($cacheProviderClass, array $params): CacheItemPoolInterface
{
try
{
if (is_object($cacheProviderClass) && $cacheProviderClass instanceof CacheItemPoolInterface) {
return $cacheProviderClass;
}
// Creates reflection of specified cache provider (can be user-made)
$cacheProvider = new \ReflectionClass($cacheProviderClass);
// Checks if this cache provider implements required interface
if (!$cacheProvider->implementsInterface(CacheItemPoolInterface::class))
throw new SettingsException("Provided CacheProvider does not implement Psr\Cache\CacheItemPoolInterface (PSR-6)");
// and creates new instance of this cache provider
/** @var CacheItemPoolInterface $instance */
$instance = $cacheProvider->newInstanceArgs($params);
return $instance;
}
catch (\ReflectionException $ex)
{
// probably problem when instantiating the class
throw new SettingsException("Failed to initialize CacheProvider class: {$ex->getMessage()}.", $ex->getCode(), $ex);
}
catch (\Throwable $ex)
{
// something went wrong when initializing the class - invalid settings, etc.
throw new SettingsException("CacheProvider class failed to be initialized: {$ex->getMessage()}.", $ex->getCode(), $ex);
}
}
/**
* Initializes library call caching.
*
* @throws SettingsException
*/
public function _setupCacheCalls()
{
if ($this->isSettingSet(self::SET_CACHE_CALLS_LENGTH))
{
$lengths = $this->getSetting(self::SET_CACHE_CALLS_LENGTH);
// Resource caching lengths are specified
if (is_array($lengths))
{
array_walk($lengths, function ($value, $key) {
if ((!is_integer($value) && !is_null($value)) || strpos($key, ':') == false)
throw new SettingsException("Value of settings parameter '" . self::SET_CACHE_CALLS_LENGTH . "' is not valid.");
});
}
elseif (!is_integer($lengths))
throw new SettingsException("Value of settings parameter '" . self::SET_CACHE_CALLS_LENGTH . "' is not valid.");
if (is_array($lengths))
{
// The value is array, let's check it
$new_value = [];
$resources = $this->resources;
foreach ($resources as $resource)
{
if (isset($lengths[$resource]))
{
if ($lengths[$resource] > $this->ccc_savetime)
$this->ccc_savetime = $lengths[$resource];
$new_value[$resource] = $lengths[$resource];
}
else
$new_value[$resource] = null;
}
$this->setSetting(self::SET_CACHE_CALLS_LENGTH, $new_value);
}
else
{
// The value is numeric, lets set the same limit to all resources
$new_value = [];
$resources = $this->resources;
$this->ccc_savetime = $lengths;
foreach ($resources as $resource)
$new_value[$resource] = $lengths;
$this->setSetting(self::SET_CACHE_CALLS_LENGTH, $new_value);
}
}
}
/**
* Sets up internal callbacks - before the call is made.
*
* @throws SettingsException
*/
protected function _setupBeforeCalls()
{
// API rate limit check before call is made
$this->beforeCall[] = function () {
if ($this->getSetting(self::SET_CACHE_RATELIMIT) && $this->rlc != false)
if ($this->rlc->canCall($this->getSetting($this->used_key), $this->getSetting(self::SET_REGION), $this->getResource(), $this->getResourceEndpoint()) == false)
throw new ServerLimitException('API call rate limit would be exceeded by this call.');
};
$callbacks = $this->getSetting(self::SET_CALLBACKS_BEFORE, []);
if (is_array($callbacks) == false)
$callbacks = [$callbacks];
foreach ($callbacks as $c)
{
if (is_callable($c) == false)
throw new SettingsException("Provided value of '" . self::SET_CALLBACKS_BEFORE . "' option is not valid.");
$this->beforeCall[] = $c;
}
}
/**
* Sets up internal callbacks - after the call is made.
*
* @throws SettingsException
*/
protected function _setupAfterCalls()
{
$this->afterCall[] = function () {
if ($this->isSettingSet(self::SET_CACHE_RATELIMIT) && $this->rlc != false)
{
// Save ratelimits received with this request if RateLimit cache is enabled
$this->rlc->registerLimits($this->getSetting($this->used_key), $this->getSetting(self::SET_REGION), $this->getResourceEndpoint(), @$this->result_headers[self::HEADER_APP_RATELIMIT], @$this->result_headers[self::HEADER_METHOD_RATELIMIT]);
// Register, that call has been made if RateLimit cache is enabled
$this->rlc->registerCall($this->getSetting($this->used_key), $this->getSetting(self::SET_REGION), $this->getResourceEndpoint(), @$this->result_headers[self::HEADER_APP_RATELIMIT_COUNT], @$this->result_headers[self::HEADER_METHOD_RATELIMIT_COUNT]);
}
};
// Save result data, if CallCache is enabled and when the old result has expired
$this->afterCall[] = function () {
$requestHash = func_get_arg(2);
if ($this->getSetting(self::SET_CACHE_CALLS, false) && $this->ccc != false && $this->ccc->isCallCached($requestHash) == false)
{
// Get information for how long to save the data
if ($timeInterval = @$this->getSetting(self::SET_CACHE_CALLS_LENGTH)[$this->getResource()])
$this->ccc->saveCallData($requestHash, $this->result_data_raw, $timeInterval);
}
};
// Save result data as new DummyData if enabled and if data does not already exist
$this->afterCall[] = function () {
$dummyData_file = func_get_arg(3);
if ($this->getSetting(self::SET_SAVE_DUMMY_DATA, false) && file_exists($dummyData_file) == false)
$this->_saveDummyData($dummyData_file);
};
// Save newly cached data
$this->afterCall[] = function () {
if ($this->getSetting(self::SET_CACHE_CALLS, false) || $this->getSetting(self::SET_CACHE_RATELIMIT, false))
$this->saveCache();
};
$callbacks = $this->getSetting(self::SET_CALLBACKS_AFTER, []);
if (is_array($callbacks) == false)
$callbacks = [$callbacks];
foreach ($callbacks as $c)
{
if (is_callable($c) == false)
throw new SettingsException("Provided value of '" . self::SET_CALLBACKS_AFTER . "' option is not valid.");
$this->afterCall[] = $c;
}
}
/**
* LeagueAPI destructor.
* Saves cache files (if needed) before destroying the object.
*/
public function __destruct()
{
$this->saveCache();
}
/**
* Loads required cache objects
*
* @internal
*/
protected function loadCache()
{
if ($this->getSetting(self::SET_CACHE_RATELIMIT, false))
{
// ratelimit cache enabled, try to load already existing object
$rlc = $this->cache->getItem(self::CACHE_KEY_RLC);
if ($rlc->isHit())
{
// nothing loaded, creating new instance
$rlc = $rlc->get();
}
else
{
// nothing loaded, creating new instance
$rlc = new RateLimitControl($this->regions);
}
$this->rlc = $rlc;
}
if ($this->getSetting(self::SET_CACHE_CALLS, false))
{
// call cache enabled, try to load already existing object
$ccc = $this->cache->getItem(self::CACHE_KEY_CCC);
if ($ccc->isHit())
{
// nothing loaded, creating new instance
$ccc = $ccc->get();
}
else
{
// nothing loaded, creating new instance
$ccc = new CallCacheControl();
}
$this->ccc = $ccc;
}
}
/**
* Saves required cache objects.
*
* @internal
*/
protected function saveCache(): bool
{
if (!$this->cache)
return false;
if ($this->getSetting(self::SET_CACHE_RATELIMIT, false))
{
// Save RateLimitControl
$rlc = $this->cache->getItem(self::CACHE_KEY_RLC);
$rlc->set($this->rlc);
$rlc->expiresAfter($this->rlc_savetime);
$this->cache->saveDeferred($rlc);
}
if ($this->getSetting(self::SET_CACHE_CALLS, false))
{
// Save CallCacheControl
$ccc = $this->cache->getItem(self::CACHE_KEY_CCC);
$ccc->set($this->ccc);
$ccc->expiresAfter($this->ccc_savetime);
$this->cache->saveDeferred($ccc);
}
return $this->cache->commit();
}
/**
* Removes all cached data.
*
* @return bool
*/
public function clearCache(): bool
{
if ($this->rlc)
$this->rlc->clear();
if ($this->ccc)
$this->ccc->clear();
return $this->cache->clear();
}
/**
* Returns vaue of requested key from settings.
*
* @param string $name
* @param mixed|null $defaultValue
*
* @return mixed
*/
public function getSetting(string $name, $defaultValue = null)
{
return $this->isSettingSet($name)
? $this->settings[$name]
: $defaultValue;
}
/**
* Sets new value for specified key in settings.
*
* @param string $name
* @param mixed $value
*
* @return $this
* @throws SettingsException
*/
public function setSetting(string $name, $value)
{
if (in_array($name, self::SETTINGS_INIT_ONLY + $this::SETTINGS_INIT_ONLY))
throw new SettingsException("Settings option '$name' can only be set on initialization of the library.");
$this->settings[$name] = $value;
return $this;
}
/**
* Sets new values for specified set of keys in settings.
*
* @param array $values
*
* @return $this
* @throws SettingsException
*/
public function setSettings(array $values)
{
foreach ($values as $name => $value)
$this->setSetting($name, $value);
return $this;
}
/**
* Checks if specified settings key is set.
*
* @param string $name
*
* @return bool
*/
public function isSettingSet(string $name): bool
{
return isset($this->settings[$name]) && !is_null($this->settings[$name]);
}
/**
* Sets new region to be used on API calls.
*
* @param string $region
*
* @return $this
* @throws SettingsException
* @throws GeneralException
*/
public function setRegion(string $region)
{
$this->setSetting(self::SET_REGION, $this->regions->getRegionName($region));
$this->setSetting(self::SET_PLATFORM, $this->platforms->getPlatformNameOfRegion($region));
return $this;
}
/**
* Sets temporary region to be used on API calls. Saves current region.
*
* @param string $tempRegion
*
* @return $this
* @throws SettingsException
* @throws GeneralException
*/
public function setTemporaryRegion(string $tempRegion)
{
$this->setSetting(self::SET_ORIG_REGION, $this->getSetting(self::SET_REGION));
$this->setSetting(self::SET_REGION, $this->regions->getRegionName($tempRegion));
$this->setSetting(self::SET_PLATFORM, $this->platforms->getPlatformNameOfRegion($tempRegion));
return $this;
}
/**
* Unets temporary region and returns original region.
*
* @return $this
* @throws SettingsException
* @throws GeneralException
*/
public function unsetTemporaryRegion()
{
if ($this->isSettingSet(self::SET_ORIG_REGION))
{
$region = $this->getSetting(self::SET_ORIG_REGION);
$this->setSetting(self::SET_REGION, $region);
$this->setSetting(self::SET_PLATFORM, $this->platforms->getPlatformNameOfRegion($region));
$this->setSetting(self::SET_ORIG_REGION, null);
}
return $this;
}
/**
* The AMERICAS routing value serves NA, BR, LAN, LAS, and OCE.
* The ASIA routing value serves KR and JP.
* The EUROPE routing value serves EUNE, EUW, TR, and RU.
*
* @param string $platform
*
* @throws GeneralException
* @throws SettingsException
*/
public function setTemporaryContinentRegionForPlatform(string $platform)
{
$current_platform = $this->getSetting(self::SET_PLATFORM);
$continent_region = $this->platforms->getCorrespondingContinentRegion($current_platform);
$this->setTemporaryRegion($continent_region);
}
/**
* Sets API key type for next API call.
*
* @param string $keyType
*
* @return $this
*/
protected function useKey(string $keyType)
{
$this->used_key = $this->isSettingSet($keyType) ? $keyType : self::SET_KEY;
return $this;
}
/**
* Sets call target for script.
*
* @param string $endpoint
*
* @return $this
*/
protected function setEndpoint(string $endpoint)
{
$this->endpoint = $endpoint;
return $this;
}
/**
* Sets call resource for target endpoint.
*
* @param string $resource
* @param string $endpoint
*
* @return $this
*/
protected function setResource(string $resource, string $endpoint)
{
$this->resource = $resource;
$this->resource_endpoint = $endpoint;
return $this;
}
/**
* Returns call resource for last call.
*
* @return string
*/
protected function getResource(): string
{
return $this->resource;
}
/**
* Returns call resource and endpoint for last call.
*
* @return string
*/
protected function getResourceEndpoint(): string
{
return $this->resource . $this->resource_endpoint;
}
/**
* Adds GET parameter to called URL.
*
* @param string $name
* @param string|null $value
*
* @return $this
*/
protected function addQuery(string $name, $value)
{
if (!is_null($value))
{
$this->query_data[$name] = $value;
}
return $this;
}
/**
* Sets POST/PUT data.
*
* @param string $data
*
* @return $this
*/
protected function setData(string $data)
{
$this->post_data = $data;
return $this;
}
/**
* Returns raw getResult data from the last call.
*
* @return mixed
*/
public function getResult()
{
return $this->result_data;
}
/**
* Returns HTTP response headers from the last call.
*
* @return array
*/
public function getResultHeaders()
{
return $this->result_headers;
}
/**
* Returns current API request limits.
*
* @return array
*/
public function getCurrentLimits()
{
return $this->rlc->getCurrentStatus($this->getSetting($this->used_key), $this->getSetting(self::SET_REGION), $this->getResourceEndpoint());
}
/**
* Adds next API call to given async request group. Sending needs to be
* initiated by calling commitAsync function.
*
* @param callable|null $onFulfilled
* @param callable|null $onRejected
* @param string $group
*
* @return $this
*/
public function nextAsync(callable $onFulfilled = null, callable $onRejected = null, string $group = "default")
{
$client = @$this->async_clients[$group];
if (!$client)
$this->async_clients[$group] = $client = new Client($this->getSetting(self::SET_GUZZLE_CLIENT_CFG));
$this->async_requests[$group][] = $this->next_async_request = new AsyncRequest($client);
$this->next_async_request->onFulfilled = $onFulfilled;
$this->next_async_request->onRejected = $onRejected;
return $this;
}
/**
* Initiates async requests from given group. Waits until completed.
*
* @param string $group
*/
public function commitAsync(string $group = "default")
{
/** @var AsyncRequest[] $requests */
$requests = @$this->async_requests[$group] ?: [];
$promises = array_map(function ($r) { return $r->getPromise(); }, $requests);
Utils::settle($promises);
unset($this->async_clients[$group]);
unset($this->async_requests[$group]);
}
/**
* @internal
*
* @param PromiseInterface $promise
* @param callable $resultCallback
*
* @return null
*/
function resolveOrEnqueuePromise(PromiseInterface $promise, callable $resultCallback = null)
{
if ($this->next_async_request)
{
$promise = $promise->then(function($result) use ($resultCallback) {
return $resultCallback ? $resultCallback($result) : null;
});
$this->next_async_request->setPromise($promise);
return $this->next_async_request = null;
}
return $resultCallback ? $resultCallback($promise->wait()) : null;
}
/**
* @internal
*
* Makes call to LeagueAPI.
*
* @param string|null $overrideRegion
* @param string $method
*
* @return PromiseInterface
* @throws RequestException
* @throws ServerException
* @throws ServerLimitException
* @throws SettingsException
* @throws GeneralException
*/
protected function makeCall(string $overrideRegion = null, string $method = self::METHOD_GET): PromiseInterface
{
if ($overrideRegion)
$this->setTemporaryRegion($overrideRegion);
$this->used_method = $method;
$requestHeaders = [];
$requestPromise = null;
$url = $this->_getCallUrl($requestHeaders);
$requestHash = md5($url);
$this->_beforeCall($url, $requestHash);
if (!$requestPromise && $this->getSetting(self::SET_USE_DUMMY_DATA, false))
{
// DummyData are supposed to be used
try
{
// try loading the data