diff --git a/src/HypixelPHP.php b/src/HypixelPHP.php index 331c029..de2c51f 100644 --- a/src/HypixelPHP.php +++ b/src/HypixelPHP.php @@ -15,25 +15,24 @@ use Plancke\HypixelPHP\fetch\Fetcher; use Plancke\HypixelPHP\fetch\FetchParams; use Plancke\HypixelPHP\fetch\FetchTypes; -use Plancke\HypixelPHP\fetch\impl\DefaultFetcher; +use Plancke\HypixelPHP\fetch\impl\DefaultCurlFetcher; use Plancke\HypixelPHP\fetch\Response; use Plancke\HypixelPHP\log\impl\NoLogger; use Plancke\HypixelPHP\log\Logger; use Plancke\HypixelPHP\provider\Provider; use Plancke\HypixelPHP\resources\ResourceManager; use Plancke\HypixelPHP\responses\booster\Boosters; +use Plancke\HypixelPHP\responses\counts\Counts; use Plancke\HypixelPHP\responses\friend\Friends; -use Plancke\HypixelPHP\responses\gameCounts\GameCounts; use Plancke\HypixelPHP\responses\guild\Guild; use Plancke\HypixelPHP\responses\KeyInfo; use Plancke\HypixelPHP\responses\Leaderboards; use Plancke\HypixelPHP\responses\player\Player; -use Plancke\HypixelPHP\responses\PlayerCount; +use Plancke\HypixelPHP\responses\PunishmentStats; use Plancke\HypixelPHP\responses\RecentGames; use Plancke\HypixelPHP\responses\Resource; use Plancke\HypixelPHP\responses\skyblock\SkyBlockProfile; use Plancke\HypixelPHP\responses\Status; -use Plancke\HypixelPHP\responses\PunishmentStats; use Plancke\HypixelPHP\util\InputType; use Plancke\HypixelPHP\util\Utilities; use Plancke\HypixelPHP\util\Validator; @@ -60,11 +59,11 @@ class HypixelPHP { * @param string $apiKey * @throws HypixelPHPException */ - public function __construct($apiKey) { + public function __construct(string $apiKey) { $this->setAPIKey($apiKey); $this->setLogger(new NoLogger($this)); - $this->setFetcher(new DefaultFetcher($this)); + $this->setFetcher(new DefaultCurlFetcher($this)); $this->setCacheHandler(new FlatFileCacheHandler($this)); $this->setProvider(new Provider($this)); $this->setResourceManager(new ResourceManager($this)); @@ -73,16 +72,20 @@ public function __construct($apiKey) { /** * @return string */ - public function getAPIKey() { + public function getAPIKey(): string { return $this->apiKey; } + private function getAPIKeyHeader(): string { + return 'API-Key: ' . $this->getAPIKey(); + } + /** * @param string $apiKey * @return $this * @throws HypixelPHPException */ - public function setAPIKey($apiKey) { + public function setAPIKey(string $apiKey): HypixelPHP { $this->validateAPIKey($apiKey); $this->apiKey = $apiKey; return $this; @@ -106,7 +109,7 @@ protected function validateAPIKey($key) { * @param Logger $logger * @return $this */ - public function setLogger(Logger $logger) { + public function setLogger(Logger $logger): HypixelPHP { $this->logger = $logger; return $this; } @@ -114,7 +117,7 @@ public function setLogger(Logger $logger) { /** * @return Logger */ - public function getLogger() { + public function getLogger(): Logger { return $this->logger; } @@ -122,7 +125,7 @@ public function getLogger() { * @param Fetcher $fetcher * @return $this */ - public function setFetcher(Fetcher $fetcher) { + public function setFetcher(Fetcher $fetcher): HypixelPHP { $this->fetcher = $fetcher; return $this; } @@ -130,7 +133,7 @@ public function setFetcher(Fetcher $fetcher) { /** * @return Fetcher */ - public function getFetcher() { + public function getFetcher(): Fetcher { return $this->fetcher; } @@ -138,7 +141,7 @@ public function getFetcher() { * @param CacheHandler $cacheHandler * @return $this */ - public function setCacheHandler(CacheHandler $cacheHandler) { + public function setCacheHandler(CacheHandler $cacheHandler): HypixelPHP { $this->cacheHandler = $cacheHandler; return $this; } @@ -146,7 +149,7 @@ public function setCacheHandler(CacheHandler $cacheHandler) { /** * @return CacheHandler */ - public function getCacheHandler() { + public function getCacheHandler(): CacheHandler { return $this->cacheHandler; } @@ -154,7 +157,7 @@ public function getCacheHandler() { * @param Provider $provider * @return $this */ - public function setProvider(Provider $provider) { + public function setProvider(Provider $provider): HypixelPHP { $this->provider = $provider; return $this; } @@ -162,7 +165,7 @@ public function setProvider(Provider $provider) { /** * @return Provider */ - public function getProvider() { + public function getProvider(): Provider { return $this->provider; } @@ -170,7 +173,7 @@ public function getProvider() { * @param ResourceManager $resourceManager * @return $this */ - public function setResourceManager(ResourceManager $resourceManager) { + public function setResourceManager(ResourceManager $resourceManager): HypixelPHP { $this->resourceManager = $resourceManager; return $this; } @@ -178,7 +181,7 @@ public function setResourceManager(ResourceManager $resourceManager) { /** * @return ResourceManager */ - public function getResourceManager() { + public function getResourceManager(): ResourceManager { return $this->resourceManager; } @@ -215,7 +218,7 @@ public function getUUIDFromVar($value) { * * @return string|null */ - public function getUUID($username) { + public function getUUID(string $username) { $username = trim(strtolower((string)$username)); $cached = $this->getCacheHandler()->getUUID($username); if ($cached != null) { @@ -236,7 +239,7 @@ public function getUUID($username) { } { - // try to use mojang + // try to use Mojang try { $uuidURL = sprintf('https://api.mojang.com/users/profiles/minecraft/%s', $username); $response = $this->getFetcher()->getURLContents($uuidURL); @@ -271,7 +274,11 @@ public function getUUID($username) { } // if all else fails fall back to hypixel - $response = $this->getFetcher()->fetch(FetchTypes::PLAYER, ['key' => $this->getAPIKey(), FetchParams::PLAYER_BY_NAME => $username]); + $response = $this->getFetcher()->fetch( + FetchTypes::PLAYER, + $this->getFetcher()->createUrl(FetchTypes::PLAYER, [FetchParams::PLAYER_BY_NAME => $username]), + ['headers' => [$this->getAPIKeyHeader()]] + ); if ($response->wasSuccessful()) { $obj = [ 'timestamp' => time(), @@ -311,9 +318,13 @@ public function getPlayer($pairs = []) { $val = Utilities::ensureNoDashesUUID($val); return $this->handle( - $this->getCacheHandler()->getPlayer((string)$val), + $this->getCacheHandler()->getPlayer($val), function () use ($key, $val) { - return $this->getFetcher()->fetch(FetchTypes::PLAYER, ['key' => $this->getAPIKey(), $key => $val]); + return $this->getFetcher()->fetch( + FetchTypes::PLAYER, + $this->getFetcher()->createUrl(FetchTypes::PLAYER, [$key => $val]), + ['headers' => [$this->getAPIKeyHeader()]] + ); }, $this->getProvider()->getPlayer() ); @@ -403,7 +414,11 @@ public function getGuild($pairs = []) { } } - $response = $this->getFetcher()->fetch(FetchTypes::FIND_GUILD, ['key' => $this->getAPIKey(), $key => $val]); + $response = $this->getFetcher()->fetch( + FetchTypes::FIND_GUILD, + $this->getFetcher()->createUrl(FetchTypes::FIND_GUILD, [$key => $val]), + ['headers' => [$this->getAPIKeyHeader()]] + ); if ($response->wasSuccessful()) { $content = [ 'timestamp' => time(), @@ -428,7 +443,11 @@ public function getGuild($pairs = []) { } } - $response = $this->getFetcher()->fetch(FetchTypes::FIND_GUILD, ['key' => $this->getAPIKey(), $key => $val]); + $response = $this->getFetcher()->fetch( + FetchTypes::FIND_GUILD, + $this->getFetcher()->createUrl(FetchTypes::FIND_GUILD, [$key => $val]), + ['headers' => [$this->getAPIKeyHeader()]] + ); if ($response->wasSuccessful()) { $content = [ 'timestamp' => time(), @@ -446,7 +465,11 @@ public function getGuild($pairs = []) { return $this->handle( $this->getCacheHandler()->getGuild((string)$val), function () use ($key, $val) { - return $this->getFetcher()->fetch(FetchTypes::GUILD, ['key' => $this->getAPIKey(), $key => $val]); + return $this->getFetcher()->fetch( + FetchTypes::GUILD, + $this->getFetcher()->createUrl(FetchTypes::GUILD, [$key => $val]), + ['headers' => [$this->getAPIKeyHeader()]] + ); }, $this->getProvider()->getGuild() ); @@ -473,9 +496,13 @@ public function getStatus($pairs = []) { $val = Utilities::ensureNoDashesUUID($val); return $this->handle( - $this->getCacheHandler()->getStatus((string)$val), + $this->getCacheHandler()->getStatus($val), function () use ($key, $val) { - return $this->getFetcher()->fetch(FetchTypes::STATUS, ['key' => $this->getAPIKey(), $key => $val]); + return $this->getFetcher()->fetch( + FetchTypes::STATUS, + $this->getFetcher()->createUrl(FetchTypes::STATUS, [$key => $val]), + ['headers' => [$this->getAPIKeyHeader()]] + ); }, $this->getProvider()->getStatus() ); @@ -502,9 +529,13 @@ public function getRecentGames($pairs = []) { $val = Utilities::ensureNoDashesUUID($val); return $this->handle( - $this->getCacheHandler()->getRecentGames((string)$val), + $this->getCacheHandler()->getRecentGames($val), function () use ($key, $val) { - return $this->getFetcher()->fetch(FetchTypes::RECENT_GAMES, ['key' => $this->getAPIKey(), $key => $val]); + return $this->getFetcher()->fetch( + FetchTypes::RECENT_GAMES, + $this->getFetcher()->createUrl(FetchTypes::RECENT_GAMES, [$key => $val]), + ['headers' => [$this->getAPIKeyHeader()]] + ); }, $this->getProvider()->getRecentGames() ); @@ -531,9 +562,13 @@ public function getFriends($pairs = []) { $val = Utilities::ensureNoDashesUUID($val); return $this->handle( - $this->getCacheHandler()->getFriends((string)$val), + $this->getCacheHandler()->getFriends($val), function () use ($key, $val) { - return $this->getFetcher()->fetch(FetchTypes::FRIENDS, ['key' => $this->getAPIKey(), $key => $val]); + return $this->getFetcher()->fetch( + FetchTypes::FRIENDS, + $this->getFetcher()->createUrl(FetchTypes::FRIENDS, [$key => $val]), + ['headers' => [$this->getAPIKeyHeader()]] + ); }, $this->getProvider()->getFriends() ); @@ -549,7 +584,11 @@ public function getBoosters() { return $this->handle( $this->getCacheHandler()->getBoosters(), function () { - return $this->getFetcher()->fetch(FetchTypes::BOOSTERS, ['key' => $this->getAPIKey()]); + return $this->getFetcher()->fetch( + FetchTypes::BOOSTERS, + $this->getFetcher()->createUrl(FetchTypes::BOOSTERS), + ['headers' => [$this->getAPIKeyHeader()]] + ); }, $this->getProvider()->getBoosters() ); @@ -562,7 +601,11 @@ public function getLeaderboards() { return $this->handle( $this->getCacheHandler()->getLeaderboards(), function () { - return $this->getFetcher()->fetch(FetchTypes::LEADERBOARDS, ['key' => $this->getAPIKey()]); + return $this->getFetcher()->fetch( + FetchTypes::LEADERBOARDS, + $this->getFetcher()->createUrl(FetchTypes::LEADERBOARDS), + ['headers' => [$this->getAPIKeyHeader()]] + ); }, $this->getProvider()->getLeaderboards() ); @@ -575,7 +618,11 @@ public function getKeyInfo() { return $this->handle( $this->getCacheHandler()->getKeyInfo($this->getAPIKey()), function () { - return $this->getFetcher()->fetch(FetchTypes::KEY, ['key' => $this->getAPIKey()]); + return $this->getFetcher()->fetch( + FetchTypes::KEY, + $this->getFetcher()->createUrl(FetchTypes::KEY), + ['headers' => [$this->getAPIKeyHeader()]] + ); }, $this->getProvider()->getKeyInfo() ); @@ -588,33 +635,45 @@ public function getPunishmentStats() { return $this->handle( $this->getCacheHandler()->getPunishmentStats(), function () { - return $this->getFetcher()->fetch(FetchTypes::PUNISHMENT_STATS, ['key' => $this->getAPIKey()]); + return $this->getFetcher()->fetch( + FetchTypes::PUNISHMENT_STATS, + $this->getFetcher()->createUrl(FetchTypes::PUNISHMENT_STATS), + ['headers' => [$this->getAPIKeyHeader()]] + ); }, $this->getProvider()->getPunishmentStats() ); } /** - * @return PlayerCount|Response|null + * @return Counts|Response|null */ - public function getPlayerCount() { + public function getCounts() { return $this->handle( - $this->getCacheHandler()->getPlayerCount(), + $this->getCacheHandler()->getCounts(), function () { - return $this->getFetcher()->fetch(FetchTypes::PLAYER_COUNT, ['key' => $this->getAPIKey()]); + return $this->getFetcher()->fetch( + FetchTypes::COUNTS, + $this->getFetcher()->createUrl(FetchTypes::COUNTS), + ['headers' => [$this->getAPIKeyHeader()]] + ); }, - $this->getProvider()->getPlayerCount() + $this->getProvider()->getCounts() ); } /** - * @return GameCounts|Response|null + * @return Counts|Response|null */ public function getGameCounts() { return $this->handle( $this->getCacheHandler()->getGameCounts(), function () { - return $this->getFetcher()->fetch(FetchTypes::GAME_COUNTS, ['key' => $this->getAPIKey()]); + return $this->getFetcher()->fetch( + FetchTypes::GAME_COUNTS, + $this->getFetcher()->createUrl(FetchTypes::GAME_COUNTS), + ['headers' => [$this->getAPIKeyHeader()]] + ); }, $this->getProvider()->getGameCounts() ); @@ -628,7 +687,11 @@ public function getSkyBlockProfile($profile_id) { return $this->handle( $this->getCacheHandler()->getSkyBlockProfile($profile_id), function () use ($profile_id) { - return $this->getFetcher()->fetch(FetchTypes::SKYBLOCK_PROFILE, ['key' => $this->getAPIKey(), 'profile' => $profile_id]); + return $this->getFetcher()->fetch( + FetchTypes::SKYBLOCK_PROFILE, + $this->getFetcher()->createUrl(FetchTypes::SKYBLOCK_PROFILE, ['profile' => $profile_id]), + ['headers' => [$this->getAPIKeyHeader()]] + ); }, $this->getProvider()->getSkyBlockProfile() ); @@ -642,7 +705,10 @@ public function getResource($resource) { return $this->handle( $this->getCacheHandler()->getResource($resource), function () use ($resource) { - return $this->getFetcher()->fetch(FetchTypes::RESOURCES . '/' . $resource); + return $this->getFetcher()->fetch( + FetchTypes::RESOURCES, + $this->getFetcher()->createUrl(FetchTypes::RESOURCES) . '/' . $resource + ); }, function ($HypixelPHP, $data) use ($resource) { return new Resource($HypixelPHP, $data, $resource); diff --git a/src/cache/CacheHandler.php b/src/cache/CacheHandler.php index b6a7031..da89690 100644 --- a/src/cache/CacheHandler.php +++ b/src/cache/CacheHandler.php @@ -7,18 +7,17 @@ use Plancke\HypixelPHP\classes\HypixelObject; use Plancke\HypixelPHP\classes\Module; use Plancke\HypixelPHP\responses\booster\Boosters; +use Plancke\HypixelPHP\responses\counts\Counts; use Plancke\HypixelPHP\responses\friend\Friends; -use Plancke\HypixelPHP\responses\gameCounts\GameCounts; use Plancke\HypixelPHP\responses\guild\Guild; use Plancke\HypixelPHP\responses\KeyInfo; use Plancke\HypixelPHP\responses\Leaderboards; use Plancke\HypixelPHP\responses\player\Player; -use Plancke\HypixelPHP\responses\PlayerCount; +use Plancke\HypixelPHP\responses\PunishmentStats; use Plancke\HypixelPHP\responses\RecentGames; use Plancke\HypixelPHP\responses\Resource; use Plancke\HypixelPHP\responses\skyblock\SkyBlockProfile; use Plancke\HypixelPHP\responses\Status; -use Plancke\HypixelPHP\responses\PunishmentStats; /** * Class CacheHandler @@ -40,13 +39,12 @@ abstract class CacheHandler extends Module { CacheTimes::GUILD_NOT_FOUND => 10 * 60, CacheTimes::LEADERBOARDS => 10 * 60, - CacheTimes::PLAYER_COUNT => 10 * 60, CacheTimes::BOOSTERS => 10 * 60, CacheTimes::STATUS => 10 * 60, CacheTimes::KEY_INFO => 10 * 60, CacheTimes::FRIENDS => 10 * 60, CacheTimes::PUNISHMENT_STATS => 10 * 60, - CacheTimes::GAME_COUNTS => 10 * 60, + CacheTimes::COUNTS => 10 * 60, CacheTimes::SKYBLOCK_PROFILE => 10 * 60 ]; @@ -252,26 +250,15 @@ public abstract function getPunishmentStats(); public abstract function setPunishmentStats(PunishmentStats $punishmentStats); /** - * @return PlayerCount|null - */ - public abstract function getPlayerCount(); - - /** - * @param PlayerCount $playerCount - * @return void - */ - public abstract function setPlayerCount(PlayerCount $playerCount); - - /** - * @return GameCounts|null + * @return Counts|null */ - public abstract function getGameCounts(); + public abstract function getCounts(); /** - * @param GameCounts $gameCounts + * @param Counts $gameCounts * @return void */ - public abstract function setGameCounts(GameCounts $gameCounts); + public abstract function setCounts(Counts $gameCounts); /** * @param $profile_id diff --git a/src/cache/CacheTimes.php b/src/cache/CacheTimes.php index d754010..279c057 100644 --- a/src/cache/CacheTimes.php +++ b/src/cache/CacheTimes.php @@ -16,14 +16,13 @@ abstract class CacheTimes { const GUILD = 'guild'; const GUILD_NOT_FOUND = 'guildNotFound'; const LEADERBOARDS = 'leaderboards'; - const PLAYER_COUNT = 'playerCount'; const BOOSTERS = 'boosters'; const STATUS = 'status'; const RECENT_GAMES = 'recentGames'; const KEY_INFO = 'keyInfo'; const FRIENDS = 'friends'; const PUNISHMENT_STATS = 'punishmentStats'; - const GAME_COUNTS = 'gameCounts'; + const COUNTS = 'counts'; const SKYBLOCK_PROFILE = 'skyblock_profile'; } \ No newline at end of file diff --git a/src/cache/CacheTypes.php b/src/cache/CacheTypes.php index 12139be..642d87f 100644 --- a/src/cache/CacheTypes.php +++ b/src/cache/CacheTypes.php @@ -28,7 +28,6 @@ abstract class CacheTypes { const LEADERBOARDS = 'leaderboards'; const BOOSTERS = 'boosters'; const PUNISHMENT_STATS = 'punishmentStats'; - const PLAYER_COUNT = 'playerCount'; - const GAME_COUNTS = 'gameCounts'; + const COUNTS = 'counts'; } \ No newline at end of file diff --git a/src/cache/impl/FlatFileCacheHandler.php b/src/cache/impl/FlatFileCacheHandler.php index 6db852e..9c1fe79 100644 --- a/src/cache/impl/FlatFileCacheHandler.php +++ b/src/cache/impl/FlatFileCacheHandler.php @@ -7,18 +7,17 @@ use Plancke\HypixelPHP\cache\CacheTimes; use Plancke\HypixelPHP\cache\CacheTypes; use Plancke\HypixelPHP\responses\booster\Boosters; +use Plancke\HypixelPHP\responses\counts\Counts; use Plancke\HypixelPHP\responses\friend\Friends; -use Plancke\HypixelPHP\responses\gameCounts\GameCounts; use Plancke\HypixelPHP\responses\guild\Guild; use Plancke\HypixelPHP\responses\KeyInfo; use Plancke\HypixelPHP\responses\Leaderboards; use Plancke\HypixelPHP\responses\player\Player; -use Plancke\HypixelPHP\responses\PlayerCount; +use Plancke\HypixelPHP\responses\PunishmentStats; use Plancke\HypixelPHP\responses\RecentGames; use Plancke\HypixelPHP\responses\Resource; use Plancke\HypixelPHP\responses\skyblock\SkyBlockProfile; use Plancke\HypixelPHP\responses\Status; -use Plancke\HypixelPHP\responses\PunishmentStats; use Plancke\HypixelPHP\util\CacheUtil; /** @@ -341,39 +340,21 @@ public function setPunishmentStats(PunishmentStats $punishmentStats) { } /** - * @return PlayerCount|null - */ - public function getPlayerCount() { - return $this->wrapProvider( - $this->getHypixelPHP()->getProvider()->getPlayerCount(), - $this->_getCache(CacheTypes::PLAYER_COUNT) - ); - } - - /** - * @param PlayerCount $playerCount - * @throws InvalidArgumentException - */ - public function setPlayerCount(PlayerCount $playerCount) { - $this->_setCache(CacheTypes::PLAYER_COUNT, $playerCount); - } - - /** - * @return GameCounts|null + * @return Counts|null */ - public function getGameCounts() { + public function getCounts() { return $this->wrapProvider( - $this->getHypixelPHP()->getProvider()->getGameCounts(), - $this->_getCache(CacheTypes::GAME_COUNTS) + $this->getHypixelPHP()->getProvider()->getCounts(), + $this->_getCache(CacheTypes::COUNTS) ); } /** - * @param GameCounts $gameCounts + * @param Counts $gameCounts * @throws InvalidArgumentException */ - public function setGameCounts(GameCounts $gameCounts) { - $this->_setCache(CacheTypes::GAME_COUNTS, $gameCounts); + public function setCounts(Counts $gameCounts) { + $this->_setCache(CacheTypes::COUNTS, $gameCounts); } /** diff --git a/src/cache/impl/MongoCacheHandler.php b/src/cache/impl/MongoCacheHandler.php index 8d218ff..2567a7e 100644 --- a/src/cache/impl/MongoCacheHandler.php +++ b/src/cache/impl/MongoCacheHandler.php @@ -207,7 +207,7 @@ public function getGuild($id) { */ public function setGuild(Guild $guild) { $this->selectDB()->selectCollection(CacheTypes::GUILDS)->replaceOne( - ['record._id' => (string)$guild->getID()], $this->objToArray($guild), self::UPDATE_OPTIONS + ['record._id' => $guild->getID()], $this->objToArray($guild), self::UPDATE_OPTIONS ); } diff --git a/src/cache/impl/NoCacheHandler.php b/src/cache/impl/NoCacheHandler.php index a350203..3a6af92 100644 --- a/src/cache/impl/NoCacheHandler.php +++ b/src/cache/impl/NoCacheHandler.php @@ -4,17 +4,16 @@ use Plancke\HypixelPHP\cache\CacheHandler; use Plancke\HypixelPHP\responses\booster\Boosters; +use Plancke\HypixelPHP\responses\counts\Counts; use Plancke\HypixelPHP\responses\friend\Friends; -use Plancke\HypixelPHP\responses\gameCounts\GameCounts; use Plancke\HypixelPHP\responses\guild\Guild; use Plancke\HypixelPHP\responses\KeyInfo; use Plancke\HypixelPHP\responses\Leaderboards; use Plancke\HypixelPHP\responses\player\Player; -use Plancke\HypixelPHP\responses\PlayerCount; +use Plancke\HypixelPHP\responses\PunishmentStats; use Plancke\HypixelPHP\responses\RecentGames; use Plancke\HypixelPHP\responses\skyblock\SkyBlockProfile; use Plancke\HypixelPHP\responses\Status; -use Plancke\HypixelPHP\responses\PunishmentStats; /** * Class NoCacheHandler @@ -110,17 +109,10 @@ function getPunishmentStats() { return null; } - function setPlayerCount(PlayerCount $playerCount) { - } - - function getPlayerCount() { - return null; - } - - function setGameCounts(GameCounts $gameCounts) { + function setCounts(Counts $counts) { } - function getGameCounts() { + function getCounts() { return null; } diff --git a/src/fetch/FetchParams.php b/src/fetch/FetchParams.php index c99d66e..8d1a36d 100644 --- a/src/fetch/FetchParams.php +++ b/src/fetch/FetchParams.php @@ -24,7 +24,7 @@ abstract class FetchParams { /** * @return array */ - public static function values() { + public static function values(): array { return [ self::PLAYER_BY_NAME, self::PLAYER_BY_UUID, diff --git a/src/fetch/FetchTypes.php b/src/fetch/FetchTypes.php index fc02be9..d3b9ae1 100644 --- a/src/fetch/FetchTypes.php +++ b/src/fetch/FetchTypes.php @@ -22,12 +22,12 @@ abstract class FetchTypes { const RECENT_GAMES = 'recentGames'; const KEY = 'key'; const PUNISHMENT_STATS = 'punishmentStats'; - const PLAYER_COUNT = 'playerCount'; + const COUNTS = 'counts'; const GAME_COUNTS = 'gameCounts'; const SKYBLOCK_PROFILE = 'skyblock/profile'; - public static function values() { + public static function values(): array { return [ self::RESOURCES, self::PLAYER, @@ -39,7 +39,7 @@ public static function values() { self::RECENT_GAMES, self::KEY, self::PUNISHMENT_STATS, - self::PLAYER_COUNT, + self::COUNTS, self::GAME_COUNTS, self::SKYBLOCK_PROFILE ]; diff --git a/src/fetch/Fetcher.php b/src/fetch/Fetcher.php index c7c6ce8..7c8faf6 100644 --- a/src/fetch/Fetcher.php +++ b/src/fetch/Fetcher.php @@ -3,7 +3,9 @@ namespace Plancke\HypixelPHP\fetch; use Closure; +use Plancke\HypixelPHP\cache\CacheHandler; use Plancke\HypixelPHP\classes\Module; +use Plancke\HypixelPHP\exceptions\HypixelPHPException; use Plancke\HypixelPHP\fetch\adapter\ResponseAdapter; use Plancke\HypixelPHP\HypixelPHP; @@ -34,7 +36,7 @@ public function __construct(HypixelPHP $HypixelPHP) { * @param Closure $getter * @return $this */ - public function setResponseAdapterGetter(Closure $getter) { + public function setResponseAdapterGetter(Closure $getter): Fetcher { $this->responseAdapterGetter = $getter; $this->responseAdapter = null; return $this; @@ -43,7 +45,7 @@ public function setResponseAdapterGetter(Closure $getter) { /** * @return ResponseAdapter */ - public function getResponseAdapter() { + public function getResponseAdapter(): ResponseAdapter { if ($this->responseAdapter == null) { $getter = $this->responseAdapterGetter; $this->responseAdapter = $getter($this->getHypixelPHP()); @@ -55,7 +57,7 @@ public function getResponseAdapter() { * @param ResponseAdapter $responseAdapter * @return $this */ - public function setResponseAdapter(ResponseAdapter $responseAdapter) { + public function setResponseAdapter(ResponseAdapter $responseAdapter): Fetcher { $this->responseAdapter = $responseAdapter; $this->responseAdapterGetter = null; return $this; @@ -64,7 +66,7 @@ public function setResponseAdapter(ResponseAdapter $responseAdapter) { /** * @return int */ - public function getTimeOut() { + public function getTimeOut(): int { return $this->timeOut; } @@ -72,7 +74,7 @@ public function getTimeOut() { * @param int $timeOut * @return $this */ - public function setTimeOut($timeOut) { + public function setTimeOut(int $timeOut): Fetcher { $this->timeOut = $timeOut; return $this; } @@ -80,13 +82,52 @@ public function setTimeOut($timeOut) { /** * @param string $fetch * @param array $keyValues + * @return string + */ + public function createUrl(string $fetch, $keyValues = []): string { + $requestURL = Fetcher::BASE_URL . $fetch; + if (sizeof($keyValues) > 0) { + $requestURL .= '?'; + foreach ($keyValues as $key => $value) { + $value = urlencode(trim($value)); + $requestURL .= '&' . $key . '=' . $value; + } + } + return $requestURL; + } + + /** + * @param string $fetch + * @param string $url + * @param array $options * @return Response + * @throws HypixelPHPException */ - abstract function fetch($fetch, $keyValues = []); + public function fetch(string $fetch, string $url, $options = []): Response { + if (!is_array($options)) { + throw new HypixelPHPException("options is not an array"); + } + + $this->getHypixelPHP()->getLogger()->log(LOG_DEBUG, 'Starting Fetch: ' . $url); + + $response = $this->getURLContents($url, $options); + if (!$response->wasSuccessful()) { + $this->getHypixelPHP()->getLogger()->log(LOG_DEBUG, 'Fetch Failed! ' . var_export($response, true)); + + // If one fails, stop trying for that status + // ideally also have a cached check before + $this->getHypixelPHP()->getCacheHandler()->setGlobalTime(CacheHandler::MAX_CACHE_TIME); + } else { + $this->getHypixelPHP()->getLogger()->log(LOG_DEBUG, 'Fetch successful!'); + } + + return $this->getResponseAdapter()->adaptResponse($fetch, $response); + } /** * @param string $url + * @param array $options * @return Response */ - abstract function getURLContents($url); + abstract function getURLContents(string $url, $options = []): Response; } \ No newline at end of file diff --git a/src/fetch/adapter/ResponseAdapter.php b/src/fetch/adapter/ResponseAdapter.php index 01f30ae..678230a 100644 --- a/src/fetch/adapter/ResponseAdapter.php +++ b/src/fetch/adapter/ResponseAdapter.php @@ -15,13 +15,12 @@ class ResponseAdapter extends Module { /** - * @param $fetch - * @param $keyValues + * @param string $fetch * @param Response $response * @return Response * @throws HypixelPHPException */ - public function adaptResponse($fetch, $keyValues, Response $response) { + public function adaptResponse(string $fetch, Response $response): Response { if (strpos($fetch, FetchTypes::RESOURCES) === 0) { return $this->wrapRecord($response); } @@ -36,17 +35,15 @@ public function adaptResponse($fetch, $keyValues, Response $response) { case FetchTypes::LEADERBOARDS: return $this->remapField('leaderboards', $response); case FetchTypes::FRIENDS: - return $this->attachKeyValues($keyValues, $this->wrapRecord($response->setData(['list' => $response->getData()['records']]))); - case FetchTypes::STATUS: - return $this->attachKeyValues($keyValues, $this->remapField('session', $response)); - case FetchTypes::RECENT_GAMES: - return $this->attachKeyValues($keyValues, $this->wrapRecord($response)); + return $this->wrapRecord($response->setData(['list' => $response->getData()['records'], 'uuid' => $response->getData()['uuid']])); case FetchTypes::SKYBLOCK_PROFILE: return $this->remapField('profile', $response); + case FetchTypes::STATUS: case FetchTypes::PUNISHMENT_STATS: - case FetchTypes::PLAYER_COUNT: + case FetchTypes::COUNTS: case FetchTypes::GAME_COUNTS: + case FetchTypes::RECENT_GAMES: return $this->wrapRecord($response); case FetchTypes::KEY: @@ -62,7 +59,7 @@ public function adaptResponse($fetch, $keyValues, Response $response) { * @param Response $response * @return Response */ - protected function wrapRecord(Response $response) { + protected function wrapRecord(Response $response): Response { return $response->setData(['record' => $response->getData()]); } @@ -71,22 +68,9 @@ protected function wrapRecord(Response $response) { * @param Response $response * @return Response */ - protected function remapField($key, Response $response) { + protected function remapField($key, Response $response): Response { if (!array_key_exists($key, $response->getData())) return $response; return $response->setData(['record' => $response->getData()[$key]]); } - /** - * @param $keyValues - * @param Response $response - * @return Response - */ - protected function attachKeyValues($keyValues, Response $response) { - $data = $response->getData(); - if (array_key_exists('record', $data) && is_array($data['record'])) { - $data['record'] = array_merge($data['record'], $keyValues); - unset($data['record']['key']); - } - return $response->setData($data); - } } \ No newline at end of file diff --git a/src/fetch/impl/DefaultCurlFetcher.php b/src/fetch/impl/DefaultCurlFetcher.php new file mode 100644 index 0000000..ecf1519 --- /dev/null +++ b/src/fetch/impl/DefaultCurlFetcher.php @@ -0,0 +1,64 @@ +timeOut); + curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, $this->timeOut); + curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); + if (array_key_exists('headers', $options)) { + curl_setopt($ch, CURLOPT_HTTPHEADER, $options['headers']); + } + $curlOut = curl_exec($ch); + + $error = curl_error($ch); + if ($error != null && $error != '') { + throw new CurlException($error); + } + if ($curlOut === false) { + return $response; + } + + $responseCode = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); + if ($responseCode != '200') { + throw new BadResponseCodeException(200, $responseCode); + } + + $data = json_decode($curlOut, true); + if (isset($data['success'])) { + $response->setSuccessful($data['success']); + unset($data['success']); + } else { + $response->setSuccessful(true); + } + $response->setData($data); + } finally { + curl_close($ch); + } + return $response; + } + +} \ No newline at end of file diff --git a/src/fetch/impl/DefaultFGCFetcher.php b/src/fetch/impl/DefaultFGCFetcher.php new file mode 100644 index 0000000..fdfe24e --- /dev/null +++ b/src/fetch/impl/DefaultFGCFetcher.php @@ -0,0 +1,54 @@ + [ + 'timeout' => $this->timeOut / 1000 + ] + ]; + if (array_key_exists('headers', $options)) { + $stream_options['http']['header'] = implode("\r\n", $options['headers']); + } + + $ctx = stream_context_create($stream_options); + + $out = file_get_contents($url, 0, $ctx); + if ($out === false) { + throw new FileGetContentsException($url); + } + + $data = json_decode($out, true); + if (isset($data['success'])) { + $response->setSuccessful($data['success']); + unset($data['success']); + } else { + $response->setSuccessful(true); + } + $response->setData($data); + return $response; + } + +} \ No newline at end of file diff --git a/src/fetch/impl/DefaultFetcher.php b/src/fetch/impl/DefaultFetcher.php deleted file mode 100644 index 8b3538c..0000000 --- a/src/fetch/impl/DefaultFetcher.php +++ /dev/null @@ -1,128 +0,0 @@ -useCurl = $useCurl; - return $this; - } - - /** - * @param string $fetch - * @param array $keyValues - * @return Response - * @throws HypixelPHPException - */ - public function fetch($fetch, $keyValues = []) { - $requestURL = Fetcher::BASE_URL . $fetch; - - $debug = $fetch; - if (is_array($keyValues) && sizeof($keyValues) > 0) { - $requestURL .= '?'; - foreach ($keyValues as $key => $value) { - $value = urlencode(trim($value)); - $requestURL .= '&' . $key . '=' . $value; - $debug .= '&' . $key . '=' . $value; - } - } - - $this->getHypixelPHP()->getLogger()->log(LOG_DEBUG, 'Starting Fetch: ' . $debug); - - $response = $this->getURLContents($requestURL); - if (!$response->wasSuccessful()) { - $this->getHypixelPHP()->getLogger()->log(LOG_DEBUG, 'Fetch Failed! ' . var_export($response, true)); - - // If one fails, stop trying for that status - // ideally also have a cached check before - $this->getHypixelPHP()->getCacheHandler()->setGlobalTime(CacheHandler::MAX_CACHE_TIME); - } else { - $this->getHypixelPHP()->getLogger()->log(LOG_DEBUG, 'Fetch successful!'); - } - - return $this->getResponseAdapter()->adaptResponse($fetch, $keyValues, $response); - } - - /** - * @param string $url - * @return Response - * @throws HypixelPHPException - */ - public function getURLContents($url) { - $response = new Response(); - if ($this->useCurl) { - $ch = curl_init(); - try { - curl_setopt($ch, CURLOPT_URL, $url); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); - curl_setopt($ch, CURLOPT_TIMEOUT_MS, $this->timeOut); - curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, $this->timeOut); - curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); - $curlOut = curl_exec($ch); - - $error = curl_error($ch); - if ($error != null && $error != '') { - throw new CurlException($error); - } - if ($curlOut === false) { - return $response; - } - - $responseCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); - if ($responseCode != '200') { - throw new BadResponseCodeException(200, $responseCode); - } - - $data = json_decode($curlOut, true); - if (isset($data['success'])) { - $response->setSuccessful($data['success']); - unset($data['success']); - } else { - $response->setSuccessful(true); - } - $response->setData($data); - } finally { - curl_close($ch); - } - } else { - $ctx = stream_context_create([ - 'http' => ['timeout' => $this->timeOut / 1000] - ]); - - $out = file_get_contents($url, 0, $ctx); - if ($out === false) { - throw new FileGetContentsException($url); - } - - $data = json_decode($out, true); - if (isset($data['success'])) { - $response->setSuccessful($data['success']); - unset($data['success']); - } else { - $response->setSuccessful(true); - } - $response->setData($data); - } - return $response; - } - -} \ No newline at end of file diff --git a/src/provider/Provider.php b/src/provider/Provider.php index d3cd7d5..bcd14d6 100644 --- a/src/provider/Provider.php +++ b/src/provider/Provider.php @@ -5,17 +5,16 @@ use Closure; use Plancke\HypixelPHP\classes\Module; use Plancke\HypixelPHP\responses\booster\Boosters; +use Plancke\HypixelPHP\responses\counts\Counts; use Plancke\HypixelPHP\responses\friend\Friends; -use Plancke\HypixelPHP\responses\gameCounts\GameCounts; use Plancke\HypixelPHP\responses\guild\Guild; use Plancke\HypixelPHP\responses\KeyInfo; use Plancke\HypixelPHP\responses\Leaderboards; use Plancke\HypixelPHP\responses\player\Player; -use Plancke\HypixelPHP\responses\PlayerCount; +use Plancke\HypixelPHP\responses\PunishmentStats; use Plancke\HypixelPHP\responses\RecentGames; use Plancke\HypixelPHP\responses\skyblock\SkyBlockProfile; use Plancke\HypixelPHP\responses\Status; -use Plancke\HypixelPHP\responses\PunishmentStats; /** * Class Provider @@ -107,18 +106,9 @@ public function getPunishmentStats() { /** * @return Closure */ - public function getPlayerCount() { - return function ($HypixelPHP, $data) { - return new PlayerCount($HypixelPHP, $data); - }; - } - - /** - * @return Closure - */ - public function getGameCounts() { + public function getCounts() { return function ($HypixelPHP, $data) { - return new GameCounts($HypixelPHP, $data); + return new Counts($HypixelPHP, $data); }; } diff --git a/src/responses/PlayerCount.php b/src/responses/PlayerCount.php deleted file mode 100644 index 3909fa3..0000000 --- a/src/responses/PlayerCount.php +++ /dev/null @@ -1,31 +0,0 @@ -getNumber('playerCount'); - } - - /** - * @return string - */ - public function getCacheTimeKey() { - return CacheTimes::PLAYER_COUNT; - } - - public function save() { - $this->getHypixelPHP()->getCacheHandler()->setPlayerCount($this); - } -} \ No newline at end of file diff --git a/src/responses/RecentGames.php b/src/responses/RecentGames.php index 3390802..2e349bd 100644 --- a/src/responses/RecentGames.php +++ b/src/responses/RecentGames.php @@ -18,14 +18,14 @@ public function getUUID() { /** * @return array */ - public function getGames() { + public function getGames(): array { return $this->getArray('games'); } /** * @return string */ - public function getCacheTimeKey() { + public function getCacheTimeKey(): string { return CacheTimes::RECENT_GAMES; } diff --git a/src/responses/Status.php b/src/responses/Status.php index 7817f41..0e49ef7 100644 --- a/src/responses/Status.php +++ b/src/responses/Status.php @@ -21,14 +21,14 @@ public function getUUID() { * @return bool */ public function isOnline() { - return $this->get('online', false); + return $this->get('session.online', false); } /** * @return GameType */ public function getGameType() { - $val = $this->get('gameType'); + $val = $this->get('session.gameType'); if ($val == null) return null; return GameTypes::fromEnum($val); } @@ -37,7 +37,7 @@ public function getGameType() { * @return string */ public function getMode() { - return $this->get('mode'); + return $this->get('session.mode'); } /** diff --git a/src/responses/counts/Counts.php b/src/responses/counts/Counts.php new file mode 100644 index 0000000..25442dd --- /dev/null +++ b/src/responses/counts/Counts.php @@ -0,0 +1,46 @@ +games)) { + $this->games[$gameTypeId] = new GameCount($this->getHypixelPHP(), $this->getArray(GameTypes::fromID($gameTypeId)->getEnum())); + } + return $this->games[$gameTypeId]; + } + + /** + * @return int + */ + public function getPlayerCount(): int { + return $this->playerCount; + } + + /** + * @return string + */ + public function getCacheTimeKey() { + return CacheTimes::COUNTS; + } + + public function save() { + $this->getHypixelPHP()->getCacheHandler()->setCounts($this); + } +} \ No newline at end of file diff --git a/src/responses/gameCounts/GameCount.php b/src/responses/counts/GameCount.php similarity index 85% rename from src/responses/gameCounts/GameCount.php rename to src/responses/counts/GameCount.php index 3aaa8d3..ce6508d 100644 --- a/src/responses/gameCounts/GameCount.php +++ b/src/responses/counts/GameCount.php @@ -1,6 +1,6 @@ counts)) { - $this->counts[$gameTypeId] = new GameCount($this->getHypixelPHP(), $this->getArray(GameTypes::fromID($gameTypeId)->getEnum())); - } - return $this->counts[$gameTypeId]; - } - - /** - * @return string - */ - public function getCacheTimeKey() { - return CacheTimes::GAME_COUNTS; - } - - public function save() { - $this->getHypixelPHP()->getCacheHandler()->setGameCounts($this); - } -} \ No newline at end of file diff --git a/tests/ResponseTest.php b/tests/ResponseTest.php index 5e4eeee..9387ac4 100644 --- a/tests/ResponseTest.php +++ b/tests/ResponseTest.php @@ -4,7 +4,7 @@ use PHPUnit\Framework\TestCase; use Plancke\HypixelPHP\exceptions\HypixelPHPException; -use Plancke\HypixelPHP\responses\PlayerCount; +use Plancke\HypixelPHP\responses\counts\Counts; use Plancke\Tests\util\TestUtil; class ResponseTest extends TestCase { @@ -15,8 +15,8 @@ class ResponseTest extends TestCase { function testPlayerCount() { // basic check to confirm stuff is getting mapped correctly // TODO check api up status or this test will fail - $playerCount = TestUtil::getHypixelPHP()->getPlayerCount(); - $this->assertTrue($playerCount instanceof PlayerCount); + $counts = TestUtil::getHypixelPHP()->getCounts(); + $this->assertTrue($counts instanceof Counts); } } \ No newline at end of file diff --git a/tests/util/TestUtil.php b/tests/util/TestUtil.php index d47d3e0..ba9edc5 100644 --- a/tests/util/TestUtil.php +++ b/tests/util/TestUtil.php @@ -2,9 +2,10 @@ namespace Plancke\Tests\util; +use http\Exception\RuntimeException; use Plancke\HypixelPHP\cache\impl\NoCacheHandler; use Plancke\HypixelPHP\exceptions\HypixelPHPException; -use Plancke\HypixelPHP\fetch\impl\DefaultFetcher; +use Plancke\HypixelPHP\fetch\impl\DefaultFGCFetcher; use Plancke\HypixelPHP\HypixelPHP; use Plancke\HypixelPHP\log\Logger; @@ -14,7 +15,7 @@ class TestUtil { * @return HypixelPHP * @throws HypixelPHPException */ - public static function getHypixelPHP() { + public static function getHypixelPHP(): HypixelPHP { $HypixelPHP = new HypixelPHP(self::getAPIKey()); $HypixelPHP->setLogger(new class ($HypixelPHP) extends Logger { @@ -22,11 +23,9 @@ public function actuallyLog($level, $line) { echo $level . ': ' . $line . "\n"; } }); - $HypixelPHP->setCacheHandler(new NoCacheHandler($HypixelPHP)); - $fetcher = new DefaultFetcher($HypixelPHP); - $fetcher->setUseCurl(false); - $HypixelPHP->setFetcher($fetcher); + $HypixelPHP->setCacheHandler(new NoCacheHandler($HypixelPHP)); + $HypixelPHP->setFetcher(new DefaultFGCFetcher($HypixelPHP)); return $HypixelPHP; }