diff --git a/.gitignore b/.gitignore index 1cd656e..6ba895d 100644 --- a/.gitignore +++ b/.gitignore @@ -8,6 +8,4 @@ composer.phar # You may choose to ignore a library lock file http://getcomposer.org/doc/02-libraries.md#lock-file composer.lock -/tests/cache/ - /.phpunit.* \ No newline at end of file diff --git a/README.md b/README.md index 4bc27ac..69bbd0d 100644 --- a/README.md +++ b/README.md @@ -41,8 +41,4 @@ $player = $HypixelPHP->getPlayer([FetchParams::PLAYER_BY_NAME => 'Plancke']); if ($player instanceof Player) { echo $player->getName(); } -``` - -## Old Version - -You can find the old 1 file version in the [old branch](https://github.com/Plancke/hypixel-php/tree/old), this won't be updated and as such is most likely broken. +``` \ No newline at end of file diff --git a/composer.json b/composer.json index 68379d0..8665c83 100644 --- a/composer.json +++ b/composer.json @@ -6,12 +6,15 @@ "authors": [ { "name": "Plancke", - "email": "pl@ncke.io", + "email": "admin@plancke.io", "role": "Developer" } ], "keywords": [ - "hypixel", "plancke", "api", "wrapper" + "hypixel", + "plancke", + "api", + "wrapper" ], "support": { "issues": "https://github.com/Plancke/hypixel-php/issues" @@ -22,7 +25,8 @@ "ext-json": "*" }, "suggest": { - "mongodb/mongodb": "^1.0.0" + "ext-mongodb": "^1.4.2", + "mongodb/mongodb": "^1.4.2" }, "autoload": { "psr-4": { @@ -31,7 +35,8 @@ }, "require-dev": { "phpunit/phpunit": "8.0.6", - "ext-mbstring": "*" + "ext-mongodb": "^1.4.2", + "mongodb/mongodb": "^1.4.2" }, "autoload-dev": { "psr-4": { diff --git a/resources/game_info/README.md b/resources/game_info/README.md index a928627..5d6c5c5 100644 --- a/resources/game_info/README.md +++ b/resources/game_info/README.md @@ -1,3 +1,5 @@ This contains some files that have data for gamemodes -It includes some of my custom data needed for generators/stats page on my website \ No newline at end of file +It includes some of my custom data needed for generators/stats page on my website + +This data format could change at any point but if it does, the project version will also change. \ No newline at end of file diff --git a/src/HypixelPHP.php b/src/HypixelPHP.php index b3b63bc..5486e97 100644 --- a/src/HypixelPHP.php +++ b/src/HypixelPHP.php @@ -17,9 +17,8 @@ use Plancke\HypixelPHP\fetch\FetchTypes; use Plancke\HypixelPHP\fetch\impl\DefaultFetcher; use Plancke\HypixelPHP\fetch\Response; -use Plancke\HypixelPHP\log\impl\DefaultLogger; +use Plancke\HypixelPHP\log\impl\NoLogger; use Plancke\HypixelPHP\log\Logger; -use Plancke\HypixelPHP\options\Options; use Plancke\HypixelPHP\provider\Provider; use Plancke\HypixelPHP\resources\ResourceManager; use Plancke\HypixelPHP\responses\booster\Boosters; @@ -61,8 +60,9 @@ class HypixelPHP { public function __construct($apiKey) { $this->setAPIKey($apiKey); + // set the getters, we don't instantiate objects until we need to $this->setLoggerGetter(function ($HypixelPHP) { - return new DefaultLogger($HypixelPHP); + return new NoLogger($HypixelPHP); }); $this->setFetcherGetter(function ($HypixelPHP) { return new DefaultFetcher($HypixelPHP); @@ -78,6 +78,61 @@ public function __construct($apiKey) { }); } + /** + * @return string + */ + public function getAPIKey() { + return $this->apiKey; + } + + /** + * @param string $apiKey + * @return $this + * @throws HypixelPHPException + */ + public function setAPIKey($apiKey) { + $this->validateAPIKey($apiKey); + $this->apiKey = $apiKey; + return $this; + } + + /** + * Check whether or not given key is valid + * + * @param $key + * @throws HypixelPHPException + */ + protected function validateAPIKey($key) { + if ($key == null) { + throw new HypixelPHPException("API Key can't be null!", ExceptionCodes::NO_KEY); + } elseif (!Validator::isValidAPIKey($key)) { + throw new HypixelPHPException("API Key is invalid!", ExceptionCodes::INVALID_KEY); + } + } + + /** + * @return Logger + */ + public function getLogger() { + if ($this->logger == null) { + $getter = $this->loggerGetter; + $this->logger = $getter($this); + } + return $this->logger; + } + + /** + * @param Logger $logger + * @return $this + */ + public function setLogger(Logger $logger) { + $this->logger = $logger; + $this->loggerGetter = function () use ($logger) { + return $logger; + }; + return $this; + } + /** * @param Closure $getter * @return $this @@ -88,6 +143,29 @@ public function setLoggerGetter(Closure $getter) { return $this; } + /** + * @return Fetcher + */ + public function getFetcher() { + if ($this->fetcher == null) { + $getter = $this->fetcherGetter; + $this->fetcher = $getter($this); + } + return $this->fetcher; + } + + /** + * @param Fetcher $fetcher + * @return $this + */ + public function setFetcher(Fetcher $fetcher) { + $this->fetcher = $fetcher; + $this->fetcherGetter = function () use ($fetcher) { + return $fetcher; + }; + return $this; + } + /** * @param Closure $getter * @return $this @@ -99,22 +177,23 @@ public function setFetcherGetter(Closure $getter) { } /** - * @param Closure $getter - * @return $this + * @return CacheHandler */ - public function setCacheHandlerGetter(Closure $getter) { - $this->cacheHandlerGetter = $getter; - $this->cacheHandler = null; - return $this; + public function getCacheHandler() { + if ($this->cacheHandler == null) { + $getter = $this->cacheHandlerGetter; + $this->cacheHandler = $getter($this); + } + return $this->cacheHandler; } /** - * @param Closure $getter + * @param CacheHandler $cacheHandler * @return $this */ - public function setProviderGetter(Closure $getter) { - $this->providerGetter = $getter; - $this->provider = null; + public function setCacheHandler(CacheHandler $cacheHandler) { + $this->cacheHandler = $cacheHandler; + $this->cacheHandlerGetter = null; return $this; } @@ -122,25 +201,40 @@ public function setProviderGetter(Closure $getter) { * @param Closure $getter * @return $this */ - public function setResourceManagerGetter(Closure $getter) { - $this->resourceManagerGetter = $getter; - $this->resourceManager = null; + public function setCacheHandlerGetter(Closure $getter) { + $this->cacheHandlerGetter = $getter; + $this->cacheHandler = null; return $this; } /** - * @return Options + * @return Provider + */ + public function getProvider() { + if ($this->provider == null) { + $getter = $this->providerGetter; + $this->provider = $getter($this); + } + return $this->provider; + } + + /** + * @param Provider $provider + * @return $this */ - public function getOptions() { - return $this->options; + public function setProvider(Provider $provider) { + $this->provider = $provider; + $this->providerGetter = null; + return $this; } /** - * @param $options + * @param Closure $getter * @return $this */ - public function setOptions(Options $options) { - $this->options = $options; + public function setProviderGetter(Closure $getter) { + $this->providerGetter = $getter; + $this->provider = null; return $this; } @@ -162,12 +256,95 @@ public function getResourceManager() { */ public function setResourceManager(ResourceManager $resourceManager) { $this->resourceManager = $resourceManager; - $this->resourceManagerGetter = function () use ($resourceManager) { - return $resourceManager; - }; + $this->resourceManagerGetter = null; + return $this; + } + + /** + * @param Closure $getter + * @return $this + */ + public function setResourceManagerGetter(Closure $getter) { + $this->resourceManagerGetter = $getter; + $this->resourceManager = null; return $this; } + /** + * Handles cache expiry checks, + * fetching new objects if needed and + * loads cached extra data if applicable + * + * @param $responseSupplier + * @param $constructor + * @param HypixelObject $cached + * + * @return HypixelObject|Response|null + * @throws HypixelPHPException + */ + protected function handle($cached, $responseSupplier, $constructor) { + if ($cached instanceof HypixelObject && !$cached->isCacheExpired()) { + return $cached; + } + + $response = $responseSupplier(); + if ($response instanceof Response) { + if ($response->wasSuccessful()) { + $data = $response->getData(); + if (!array_key_exists('record', $data)) { + $data = ['record' => $data]; + } + $fetched = $constructor($this, $data); + if ($fetched instanceof HypixelObject) { + if ($cached instanceof HypixelObject) { + // update with cached extra, only locally + // since we are already saving the whole thing later + $fetched->_setExtra($cached->getExtra()); + } + + $fetched->handleNew($cached); + + $this->getCacheHandler()->setCache($fetched); + + return $fetched; + } + } else { + // fetch was not successful, attach response or + // return it so we can get the error + if ($cached != null) { + $cached->attachResponse($response); + } else { + return $response; + } + } + } + + return $cached; + } + + /** + * @param $pairs + * @throws NoPairsException + */ + protected function checkPairs($pairs) { + if ($pairs == null || sizeof($pairs) == 0) { + throw new NoPairsException(); + } + } + + /** + * @param $in + * @return Response|null + */ + public function getResponse($in) { + if ($in instanceof HypixelObject) { + return $in->getResponse(); + } else if ($in instanceof Response) { + return $in; + } + return null; + } + /** * @param array $pairs * @return null|Response|Player @@ -188,7 +365,7 @@ public function getPlayer($pairs = []) { $val = Utilities::ensureNoDashesUUID($val); return $this->handle( - $this->getCacheHandler()->getCachedPlayer((string)$val), + $this->getCacheHandler()->getPlayer((string)$val), function () use ($key, $val) { return $this->getFetcher()->fetch(FetchTypes::PLAYER, [$key => $val]); }, @@ -200,15 +377,9 @@ function () use ($key, $val) { } /** - * @param $pairs - * @throws NoPairsException + * @param $value + * @return string|null */ - protected function checkPairs($pairs) { - if ($pairs == null || sizeof($pairs) == 0) { - throw new NoPairsException(); - } - } - public function getUUIDFromVar($value) { switch (InputType::getType($value)) { case InputType::USERNAME: @@ -243,7 +414,7 @@ public function getUUID($username) { 'name_lowercase' => $username, 'uuid' => null ]; - $this->getLogger()->log("Failed getting UUID for '" . $username . "' saving null!"); + $this->getLogger()->log(LOG_DEBUG, "Failed getting UUID for '" . $username . "' saving null!"); $this->getCacheHandler()->setPlayerUUID($username, $obj); return null; } @@ -260,7 +431,7 @@ public function getUUID($username) { 'name_lowercase' => $username, 'uuid' => Utilities::ensureNoDashesUUID((string)$response->getData()['id']) ]; - $this->getLogger()->log("Received UUID from Mojang for '" . $username . "': " . $obj['uuid']); + $this->getLogger()->log(LOG_DEBUG, "Received UUID from Mojang for '" . $username . "': " . $obj['uuid']); $this->getCacheHandler()->setPlayerUUID($username, $obj); return $obj['uuid']; } @@ -275,7 +446,7 @@ public function getUUID($username) { 'name_lowercase' => $username, 'uuid' => null ]; - $this->getLogger()->log("Received empty content (doesn't exist) while getting UUID for '" . $username . "' saving null!"); + $this->getLogger()->log(LOG_DEBUG, "Received empty content (doesn't exist) while getting UUID for '" . $username . "' saving null!"); $this->getCacheHandler()->setPlayerUUID($username, $obj); return null; } else { @@ -291,7 +462,7 @@ public function getUUID($username) { 'name_lowercase' => $username, 'uuid' => Utilities::ensureNoDashesUUID((string)$response->getData()['record']['uuid']) ]; - $this->getLogger()->log("Received UUID from Hypixel for '" . $username . "': " . $obj['uuid']); + $this->getLogger()->log(LOG_DEBUG, "Received UUID from Hypixel for '" . $username . "': " . $obj['uuid']); $this->getCacheHandler()->setPlayerUUID($username, $obj); return $obj['uuid']; } @@ -304,152 +475,6 @@ public function getUUID($username) { return null; } - /** - * @return CacheHandler - */ - public function getCacheHandler() { - if ($this->cacheHandler == null) { - $getter = $this->cacheHandlerGetter; - $this->cacheHandler = $getter($this); - } - return $this->cacheHandler; - } - - /** - * @param CacheHandler $cacheHandler - * @return $this - */ - public function setCacheHandler(CacheHandler $cacheHandler) { - $this->cacheHandler = $cacheHandler; - $this->cacheHandlerGetter = function () use ($cacheHandler) { - return $cacheHandler; - }; - return $this; - } - - /** - * @return Logger - */ - public function getLogger() { - if ($this->logger == null) { - $getter = $this->loggerGetter; - $this->logger = $getter($this); - } - return $this->logger; - } - - /** - * @param Logger $logger - * @return $this - */ - public function setLogger(Logger $logger) { - $this->logger = $logger; - $this->loggerGetter = function () use ($logger) { - return $logger; - }; - return $this; - } - - /** - * @return Fetcher - */ - public function getFetcher() { - if ($this->fetcher == null) { - $getter = $this->fetcherGetter; - $this->fetcher = $getter($this); - } - return $this->fetcher; - } - - /** - * @param Fetcher $fetcher - * @return $this - */ - public function setFetcher(Fetcher $fetcher) { - $this->fetcher = $fetcher; - $this->fetcherGetter = function () use ($fetcher) { - return $fetcher; - }; - return $this; - } - - /** - * Handles cache expiry checks, - * fetching new objects if needed and - * loads cached extra data if applicable - * - * @param $responseSupplier - * @param $constructor - * @param HypixelObject $cached - * - * @return HypixelObject|Response|null - * @throws HypixelPHPException - */ - protected function handle($cached, $responseSupplier, $constructor) { - if ($cached instanceof HypixelObject && !$cached->isCacheExpired()) { - $this->getLogger()->log("Cached valid"); - return $cached; - } - - $response = $responseSupplier(); - if ($response instanceof Response) { - if ($response->wasSuccessful()) { - $data = $response->getData(); - if (!array_key_exists('record', $data)) { - $data = ['record' => $data]; - } - $fetched = $constructor($this, $data); - if ($fetched instanceof HypixelObject) { - if ($cached instanceof HypixelObject) { - // update with cached extra, only locally - // since we are already saving the whole thing later - $fetched->_setExtra($cached->getExtra()); - } - - $fetched->handleNew($cached); - - $this->getCacheHandler()->_setCache($fetched); - - return $fetched; - } - } else { - // fetch was not successful, attach response or - // return it so we can get the error - if ($cached != null) { - $this->getLogger()->log("Attaching response"); - $cached->attachResponse($response); - } else { - return $response; - } - } - } - - return $cached; - } - - /** - * @return Provider - */ - public function getProvider() { - if ($this->provider == null) { - $getter = $this->providerGetter; - $this->provider = $getter($this); - } - return $this->provider; - } - - /** - * @param Provider $provider - * @return $this - */ - public function setProvider(Provider $provider) { - $this->provider = $provider; - $this->providerGetter = function () use ($provider) { - return $provider; - }; - return $this; - } - /** * @param array $pairs * @return null|Response|Guild @@ -525,7 +550,7 @@ public function getGuild($pairs = []) { if ($key == FetchParams::GUILD_BY_ID) { return $this->handle( - $this->getCacheHandler()->getCachedGuild((string)$val), + $this->getCacheHandler()->getGuild((string)$val), function () use ($key, $val) { return $this->getFetcher()->fetch(FetchTypes::GUILD, [$key => $val]); }, @@ -554,7 +579,7 @@ public function getSession($pairs = []) { $val = Utilities::ensureNoDashesUUID($val); return $this->handle( - $this->getCacheHandler()->getCachedSession((string)$val), + $this->getCacheHandler()->getSession((string)$val), function () use ($key, $val) { return $this->getFetcher()->fetch(FetchTypes::SESSION, [$key => $val]); }, @@ -583,7 +608,7 @@ public function getFriends($pairs = []) { $val = Utilities::ensureNoDashesUUID($val); return $this->handle( - $this->getCacheHandler()->getCachedFriends((string)$val), + $this->getCacheHandler()->getFriends((string)$val), function () use ($key, $val) { return $this->getFetcher()->fetch(FetchTypes::FRIENDS, [$key => $val]); }, @@ -600,7 +625,7 @@ function () use ($key, $val) { */ public function getBoosters() { return $this->handle( - $this->getCacheHandler()->getCachedBoosters(), + $this->getCacheHandler()->getBoosters(), function () { return $this->getFetcher()->fetch(FetchTypes::BOOSTERS); }, @@ -614,7 +639,7 @@ function () { */ public function getLeaderboards() { return $this->handle( - $this->getCacheHandler()->getCachedLeaderboards(), + $this->getCacheHandler()->getLeaderboards(), function () { return $this->getFetcher()->fetch(FetchTypes::LEADERBOARDS); }, @@ -628,7 +653,7 @@ function () { */ public function getKeyInfo() { return $this->handle( - $this->getCacheHandler()->getCachedKeyInfo($this->getAPIKey()), + $this->getCacheHandler()->getKeyInfo($this->getAPIKey()), function () { return $this->getFetcher()->fetch(FetchTypes::KEY); }, @@ -636,31 +661,13 @@ function () { ); } - /** - * @return string - */ - public function getAPIKey() { - return $this->apiKey; - } - - /** - * @param string $apiKey - * @return $this - * @throws HypixelPHPException - */ - public function setAPIKey($apiKey) { - $this->validateAPIKey($apiKey); - $this->apiKey = $apiKey; - return $this; - } - /** * @return WatchdogStats|Response|null * @throws HypixelPHPException */ public function getWatchdogStats() { return $this->handle( - $this->getCacheHandler()->getCachedWatchdogStats(), + $this->getCacheHandler()->getWatchdogStats(), function () { return $this->getFetcher()->fetch(FetchTypes::WATCHDOG_STATS); }, @@ -674,7 +681,7 @@ function () { */ public function getPlayerCount() { return $this->handle( - $this->getCacheHandler()->getCachedPlayerCount(), + $this->getCacheHandler()->getPlayerCount(), function () { return $this->getFetcher()->fetch(FetchTypes::PLAYER_COUNT); }, @@ -688,49 +695,11 @@ function () { */ public function getGameCounts() { return $this->handle( - $this->getCacheHandler()->getCachedGameCounts(), + $this->getCacheHandler()->getGameCounts(), function () { return $this->getFetcher()->fetch(FetchTypes::GAME_COUNTS); }, $this->getProvider()->getGameCounts() ); } - - /** - * @param $in - * @return HypixelObject|null - */ - public function ignoreResponse($in) { - if ($in instanceof HypixelObject) { - return $in; - } - return null; - } - - /** - * @param $in - * @return Response|null - */ - public function getResponse($in) { - if ($in instanceof HypixelObject) { - return $in->getResponse(); - } else if ($in instanceof Response) { - return $in; - } - return null; - } - - /** - * Check whether or not given key is valid - * - * @param $key - * @throws HypixelPHPException - */ - protected function validateAPIKey($key) { - if ($key == null) { - throw new HypixelPHPException("API Key can't be null!", ExceptionCodes::NO_KEY); - } elseif (!Validator::isValidAPIKey($key)) { - throw new HypixelPHPException("API Key is invalid!", ExceptionCodes::INVALID_KEY); - } - } } \ No newline at end of file diff --git a/src/cache/CacheHandler.php b/src/cache/CacheHandler.php index 2ba9db7..4b33aca 100644 --- a/src/cache/CacheHandler.php +++ b/src/cache/CacheHandler.php @@ -8,7 +8,6 @@ use Plancke\HypixelPHP\exceptions\ExceptionCodes; use Plancke\HypixelPHP\exceptions\HypixelPHPException; use Plancke\HypixelPHP\exceptions\InvalidArgumentException; -use Plancke\HypixelPHP\fetch\Response; use Plancke\HypixelPHP\responses\booster\Boosters; use Plancke\HypixelPHP\responses\friend\Friends; use Plancke\HypixelPHP\responses\gameCounts\GameCounts; @@ -48,7 +47,6 @@ abstract class CacheHandler extends Module { CacheTimes::WATCHDOG => 10 * 60, CacheTimes::GAME_COUNTS => 10 * 60 ]; - protected $globalTime = 0; /** @@ -94,215 +92,213 @@ public function setCacheTime($for, $int) { return $this; } + /** + * Convert given input to an array in order to cache it + * + * @param $obj + * @return array + * @throws InvalidArgumentException + */ + protected function objToArray($obj) { + if ($obj instanceof HypixelObject) { + return $obj->getRaw(); + } else if (is_array($obj)) { + return $obj; + } + throw new InvalidArgumentException(); + } + + /** + * @param Closure $provider + * @param $data + * @return mixed|null + */ + protected function wrapProvider(Closure $provider, $data) { + if ($data == null) return null; + return $provider($this->getHypixelPHP(), $data); + } + /** * @param HypixelObject $hypixelObject * @throws HypixelPHPException */ - public function _setCache($hypixelObject) { + public function setCache($hypixelObject) { if ($hypixelObject instanceof Player) { - $this->setCachedPlayer($hypixelObject); + $this->setPlayer($hypixelObject); } elseif ($hypixelObject instanceof Guild) { - $this->setCachedGuild($hypixelObject); + $this->setGuild($hypixelObject); } elseif ($hypixelObject instanceof Friends) { - $this->setCachedFriends($hypixelObject); + $this->setFriends($hypixelObject); } elseif ($hypixelObject instanceof Session) { - $this->setCachedSession($hypixelObject); + $this->setSession($hypixelObject); } elseif ($hypixelObject instanceof KeyInfo) { - $this->setCachedKeyInfo($hypixelObject); + $this->setKeyInfo($hypixelObject); } elseif ($hypixelObject instanceof Leaderboards) { - $this->setCachedLeaderboards($hypixelObject); + $this->setLeaderboards($hypixelObject); } elseif ($hypixelObject instanceof Boosters) { - $this->setCachedBoosters($hypixelObject); + $this->setBoosters($hypixelObject); } elseif ($hypixelObject instanceof WatchdogStats) { - $this->setCachedWatchdogStats($hypixelObject); + $this->setWatchdogStats($hypixelObject); } elseif ($hypixelObject instanceof PlayerCount) { - $this->setCachedPlayerCount($hypixelObject); + $this->setPlayerCount($hypixelObject); } elseif ($hypixelObject instanceof GameCounts) { - $this->setCachedGameCounts($hypixelObject); + $this->setGameCounts($hypixelObject); } else { throw new HypixelPHPException("Invalid HypixelObject", ExceptionCodes::INVALID_HYPIXEL_OBJECT); } } /** - * @param Player $player - * @return void + * @param $uuid + * @return Player|null */ - abstract function setCachedPlayer(Player $player); + public abstract function getPlayer($uuid); /** - * @param Guild $guild + * @param Player $player * @return void */ - abstract function setCachedGuild(Guild $guild); + public abstract function setPlayer(Player $player); /** - * @param Friends $friends - * @return void + * @param $username + * @return string|null */ - abstract function setCachedFriends(Friends $friends); + public abstract function getUUID($username); /** - * @param Session $session + * @param $username + * @param $uuid * @return void */ - abstract function setCachedSession(Session $session); + public abstract function setPlayerUUID($username, $uuid); /** - * @param KeyInfo $keyInfo - * @return void + * @param $id + * @return Guild|null */ - abstract function setCachedKeyInfo(KeyInfo $keyInfo); + public abstract function getGuild($id); /** - * @param Leaderboards $leaderboards + * @param Guild $guild * @return void */ - abstract function setCachedLeaderboards(Leaderboards $leaderboards); + public abstract function setGuild(Guild $guild); /** - * @param Boosters $boosters - * @return void + * @param $uuid + * @return Guild|string|null */ - abstract function setCachedBoosters(Boosters $boosters); + public abstract function getGuildIDForUUID($uuid); /** - * @param WatchdogStats $watchdogStats + * @param $uuid + * @param $id * @return void */ - abstract function setCachedWatchdogStats(WatchdogStats $watchdogStats); + public abstract function setGuildIDForUUID($uuid, $id); /** - * @param PlayerCount $playerCount - * @return void + * @param $name + * @return Guild|string|null */ - abstract function setCachedPlayerCount(PlayerCount $playerCount); + public abstract function getGuildIDForName($name); /** - * @param GameCounts $gameCounts + * @param $name + * @param $id * @return void */ - abstract function setCachedGameCounts(GameCounts $gameCounts); + public abstract function setGuildIDForName($name, $id); /** * @param $uuid - * @return null|Response|Player + * @return Friends|null */ - abstract function getCachedPlayer($uuid); + public abstract function getFriends($uuid); /** - * @param $username - * @param $uuid + * @param Friends $friends * @return void */ - abstract function setPlayerUUID($username, $uuid); - - /** - * @param $username - * @return string - */ - abstract function getUUID($username); + public abstract function setFriends(Friends $friends); /** - * @param $id - * @return null|Response|Guild + * @param $uuid + * @return Session|null */ - abstract function getCachedGuild($id); + public abstract function getSession($uuid); /** - * @param $uuid - * @param $id + * @param Session $session * @return void */ - abstract function setGuildIDForUUID($uuid, $id); + public abstract function setSession(Session $session); /** - * @param $uuid - * @return mixed + * @param $key + * @return KeyInfo|null */ - abstract function getGuildIDForUUID($uuid); + public abstract function getKeyInfo($key); /** - * @param $name - * @param $id + * @param KeyInfo $keyInfo * @return void */ - abstract function setGuildIDForName($name, $id); + public abstract function setKeyInfo(KeyInfo $keyInfo); /** - * @param $name - * @return mixed + * @return Leaderboards|null */ - abstract function getGuildIDForName($name); + public abstract function getLeaderboards(); /** - * @param $uuid - * @return null|Response|Friends - */ - abstract function getCachedFriends($uuid); - - /** - * @param $uuid - * @return null|Response|Session + * @param Leaderboards $leaderboards + * @return void */ - abstract function getCachedSession($uuid); + public abstract function setLeaderboards(Leaderboards $leaderboards); /** - * @param $key - * @return null|Response|KeyInfo + * @return Boosters|null */ - abstract function getCachedKeyInfo($key); + public abstract function getBoosters(); /** - * @return null|Response|Leaderboards + * @param Boosters $boosters + * @return void */ - abstract function getCachedLeaderboards(); + public abstract function setBoosters(Boosters $boosters); /** - * @return null|Response|Boosters + * @return WatchdogStats|null */ - abstract function getCachedBoosters(); + public abstract function getWatchdogStats(); /** - * @return null|Response|WatchdogStats + * @param WatchdogStats $watchdogStats + * @return void */ - abstract function getCachedWatchdogStats(); + public abstract function setWatchdogStats(WatchdogStats $watchdogStats); /** - * @return null|Response|PlayerCount + * @return PlayerCount|null */ - abstract function getCachedPlayerCount(); + public abstract function getPlayerCount(); /** - * @return null|Response|GameCounts + * @param PlayerCount $playerCount + * @return void */ - abstract function getCachedGameCounts(); + public abstract function setPlayerCount(PlayerCount $playerCount); /** - * Convert given input to an array in order to cache it - * - * @param $obj - * @return array - * @throws InvalidArgumentException + * @return GameCounts|null */ - protected function objToArray($obj) { - if ($obj instanceof HypixelObject) { - return $obj->getRaw(); - } else if (is_array($obj)) { - return $obj; - } - throw new InvalidArgumentException(); - } + public abstract function getGameCounts(); /** - * @param Closure $provider - * @param $data - * @return mixed|null + * @param GameCounts $gameCounts + * @return void */ - protected function wrapProvider(Closure $provider, $data) { - if ($data == null) { - return null; - } - return $provider($this->getHypixelPHP(), $data); - } + public abstract function setGameCounts(GameCounts $gameCounts); } \ No newline at end of file diff --git a/src/cache/impl/FlatFileCacheHandler.php b/src/cache/impl/FlatFileCacheHandler.php index 8e7b1ce..02a2c5d 100644 --- a/src/cache/impl/FlatFileCacheHandler.php +++ b/src/cache/impl/FlatFileCacheHandler.php @@ -5,9 +5,7 @@ use Plancke\HypixelPHP\cache\CacheHandler; use Plancke\HypixelPHP\cache\CacheTimes; use Plancke\HypixelPHP\cache\CacheTypes; -use Plancke\HypixelPHP\classes\HypixelObject; use Plancke\HypixelPHP\exceptions\InvalidArgumentException; -use Plancke\HypixelPHP\fetch\Response; use Plancke\HypixelPHP\responses\booster\Boosters; use Plancke\HypixelPHP\responses\friend\Friends; use Plancke\HypixelPHP\responses\gameCounts\GameCounts; @@ -19,7 +17,6 @@ use Plancke\HypixelPHP\responses\Session; use Plancke\HypixelPHP\responses\WatchdogStats; use Plancke\HypixelPHP\util\CacheUtil; -use Plancke\HypixelPHP\util\Utilities; /** * Implementation for CacheHandler, stores data flat file @@ -52,73 +49,62 @@ public function setBaseDirectory($baseDirectory) { } /** - * @param Player $player - * @throws InvalidArgumentException - */ - function setCachedPlayer(Player $player) { - $this->setObjCache(CacheTypes::PLAYERS . DIRECTORY_SEPARATOR . CacheUtil::getCacheFileName($player->getUUID()), $player); - } - - /** - * Save {@link HypixelObject} to file. + * Save given array to file * * @param $filename - * @param HypixelObject $obj + * @param $obj * @throws InvalidArgumentException */ - protected function setObjCache($filename, HypixelObject $obj) { - $this->setCache($filename, $this->objToArray($obj)); + protected function _setCache($filename, $obj) { + $filename = $this->baseDirectory . DIRECTORY_SEPARATOR . $filename . '.json'; + $content = json_encode($this->objToArray($obj)); + + if (!file_exists(dirname($filename))) { + // create directory + @mkdir(dirname($filename), 0744, true); + } + file_put_contents($filename, $content); } /** - * Save given array to file - * * @param $filename - * @param array $obj - * @throws InvalidArgumentException + * @return array|null */ - protected function setCache($filename, $obj) { - Utilities::setFileContent($this->baseDirectory . DIRECTORY_SEPARATOR . $filename . '.json', json_encode($this->objToArray($obj))); + protected function _getCache($filename) { + $filename = $this->baseDirectory . DIRECTORY_SEPARATOR . $filename . '.json'; + if (!file_exists($filename)) return null; + + $content = file_get_contents($filename); + if ($content == null) return null; + + return json_decode($content, true); } /** * @param $uuid - * @return null|Response|Player + * @return Player|null */ - function getCachedPlayer($uuid) { + public function getPlayer($uuid) { return $this->wrapProvider( $this->getHypixelPHP()->getProvider()->getPlayer(), - $data = $this->getCache(CacheTypes::PLAYERS . DIRECTORY_SEPARATOR . CacheUtil::getCacheFileName($uuid)) + $data = $this->_getCache(CacheTypes::PLAYERS . DIRECTORY_SEPARATOR . CacheUtil::getCacheFileName($uuid)) ); } /** - * @param $filename - * @return array|null - */ - protected function getCache($filename) { - $content = Utilities::getFileContent($this->baseDirectory . DIRECTORY_SEPARATOR . $filename . '.json'); - if ($content == null) { - return null; - } - return json_decode($content, true); - } - - /** - * @param $username - * @param $obj + * @param Player $player * @throws InvalidArgumentException */ - function setPlayerUUID($username, $obj) { - $this->setCache(CacheTypes::PLAYER_UUID . DIRECTORY_SEPARATOR . CacheUtil::getCacheFileName($username), $obj); + public function setPlayer(Player $player) { + $this->_setCache(CacheTypes::PLAYERS . DIRECTORY_SEPARATOR . CacheUtil::getCacheFileName($player->getUUID()), $player); } /** * @param $username - * @return mixed|null|string + * @return string|null */ - function getUUID($username) { - $data = $this->getCache(CacheTypes::PLAYER_UUID . DIRECTORY_SEPARATOR . CacheUtil::getCacheFileName($username)); + public function getUUID($username) { + $data = $this->_getCache(CacheTypes::PLAYER_UUID . DIRECTORY_SEPARATOR . CacheUtil::getCacheFileName($username)); if ($data != null) { if (isset($data['uuid']) && $data['uuid'] != null && $data['uuid'] != '') { $cacheTime = $this->getCacheTime(CacheTimes::UUID); @@ -128,7 +114,7 @@ function getUUID($username) { $timestamp = array_key_exists('timestamp', $data) ? $data['timestamp'] : 0; $diff = time() - $cacheTime - $timestamp; - $this->getHypixelPHP()->getLogger()->log("Found name match in PLAYER_UUID! '$diff'"); + $this->getHypixelPHP()->getLogger()->log(LOG_DEBUG, "Found name match in PLAYER_UUID! '$diff'"); if ($diff < 0) { return $data['uuid']; @@ -139,202 +125,233 @@ function getUUID($username) { } /** - * @param Guild $guild + * @param $username + * @param $obj * @throws InvalidArgumentException */ - function setCachedGuild(Guild $guild) { - $this->setObjCache(CacheTypes::GUILDS . DIRECTORY_SEPARATOR . CacheUtil::getCacheFileName($guild->getID()), $guild); + public function setPlayerUUID($username, $obj) { + $this->_setCache(CacheTypes::PLAYER_UUID . DIRECTORY_SEPARATOR . CacheUtil::getCacheFileName($username), $obj); } /** * @param $id - * @return null|Response|Guild + * @return Guild|null */ - function getCachedGuild($id) { + public function getGuild($id) { return $this->wrapProvider( $this->getHypixelPHP()->getProvider()->getGuild(), - $data = $this->getCache(CacheTypes::GUILDS . DIRECTORY_SEPARATOR . CacheUtil::getCacheFileName($id)) + $data = $this->_getCache(CacheTypes::GUILDS . DIRECTORY_SEPARATOR . CacheUtil::getCacheFileName($id)) ); } /** - * @param $uuid - * @param $obj + * @param Guild $guild * @throws InvalidArgumentException */ - function setGuildIDForUUID($uuid, $obj) { - $this->setCache(CacheTypes::GUILDS_UUID . DIRECTORY_SEPARATOR . CacheUtil::getCacheFileName($uuid), $obj); + public function setGuild(Guild $guild) { + $this->_setCache(CacheTypes::GUILDS . DIRECTORY_SEPARATOR . CacheUtil::getCacheFileName($guild->getID()), $guild); } /** * @param $uuid - * @return array|mixed|null + * @return string|null */ - function getGuildIDForUUID($uuid) { - return $this->getCache(CacheTypes::GUILDS_UUID . DIRECTORY_SEPARATOR . CacheUtil::getCacheFileName($uuid)); + public function getGuildIDForUUID($uuid) { + $cached = $this->_getCache(CacheTypes::GUILDS_UUID . DIRECTORY_SEPARATOR . CacheUtil::getCacheFileName($uuid)); + if ($cached == null) return null; + + if (isset($cached['uuid']) && $cached['uuid'] != null && $cached['uuid'] != '') { + $cacheTime = $this->getCacheTime(CacheTimes::GUILD); + } else { + $cacheTime = $this->getCacheTime(CacheTimes::GUILD_NOT_FOUND); + } + $timestamp = array_key_exists('timestamp', $cached) ? $cached['timestamp'] : 0; + if (CacheUtil::isExpired($timestamp, $cacheTime)) return null; + return $cached['guild']; } /** - * @param $name + * @param $uuid * @param $obj * @throws InvalidArgumentException */ - function setGuildIDForName($name, $obj) { - $this->setCache(CacheTypes::GUILDS_NAME . DIRECTORY_SEPARATOR . CacheUtil::getCacheFileName($name), $obj); + public function setGuildIDForUUID($uuid, $obj) { + $this->_setCache(CacheTypes::GUILDS_UUID . DIRECTORY_SEPARATOR . CacheUtil::getCacheFileName($uuid), $obj); } /** * @param $name - * @return array|mixed|null + * @return string|null */ - function getGuildIDForName($name) { - return $this->getCache(CacheTypes::GUILDS_NAME . DIRECTORY_SEPARATOR . CacheUtil::getCacheFileName($name)); + public function getGuildIDForName($name) { + $cached = $this->_getCache(CacheTypes::GUILDS_NAME . DIRECTORY_SEPARATOR . CacheUtil::getCacheFileName($name)); + if ($cached == null) return null; + + if (isset($cached['name_lower']) && $cached['name_lower'] != null && $cached['name_lower'] != '') { + $cacheTime = $this->getCacheTime(CacheTimes::GUILD); + } else { + $cacheTime = $this->getCacheTime(CacheTimes::GUILD_NOT_FOUND); + } + + $timestamp = array_key_exists('timestamp', $cached) ? $cached['timestamp'] : 0; + if (CacheUtil::isExpired($timestamp, $cacheTime)) return null; + return $cached['guild']; } /** - * @param Friends $friends + * @param $name + * @param $obj * @throws InvalidArgumentException */ - function setCachedFriends(Friends $friends) { - $this->setObjCache(CacheTypes::FRIENDS . DIRECTORY_SEPARATOR . CacheUtil::getCacheFileName($friends->getUUID()), $friends); + public function setGuildIDForName($name, $obj) { + $this->_setCache(CacheTypes::GUILDS_NAME . DIRECTORY_SEPARATOR . CacheUtil::getCacheFileName($name), $obj); } /** * @param $uuid - * @return null|Response|Friends + * @return Friends|null */ - function getCachedFriends($uuid) { + public function getFriends($uuid) { return $this->wrapProvider( $this->getHypixelPHP()->getProvider()->getFriends(), - $this->getCache(CacheTypes::FRIENDS . DIRECTORY_SEPARATOR . CacheUtil::getCacheFileName($uuid)) + $this->_getCache(CacheTypes::FRIENDS . DIRECTORY_SEPARATOR . CacheUtil::getCacheFileName($uuid)) ); } /** - * @param Session $session + * @param Friends $friends * @throws InvalidArgumentException */ - function setCachedSession(Session $session) { - $this->setObjCache(CacheTypes::SESSIONS . DIRECTORY_SEPARATOR . CacheUtil::getCacheFileName($session->getUUID()), $session); + public function setFriends(Friends $friends) { + $this->_setCache(CacheTypes::FRIENDS . DIRECTORY_SEPARATOR . CacheUtil::getCacheFileName($friends->getUUID()), $friends); } /** * @param $uuid - * @return null|Response|Session + * @return Session|null */ - function getCachedSession($uuid) { + public function getSession($uuid) { return $this->wrapProvider( $this->getHypixelPHP()->getProvider()->getSession(), - $this->getCache(CacheTypes::SESSIONS . DIRECTORY_SEPARATOR . CacheUtil::getCacheFileName($uuid)) + $this->_getCache(CacheTypes::SESSIONS . DIRECTORY_SEPARATOR . CacheUtil::getCacheFileName($uuid)) ); } /** - * @param KeyInfo $keyInfo + * @param Session $session * @throws InvalidArgumentException */ - function setCachedKeyInfo(KeyInfo $keyInfo) { - $this->setObjCache(CacheTypes::API_KEYS . DIRECTORY_SEPARATOR . CacheUtil::getCacheFileName($keyInfo->getKey()), $keyInfo); + public function setSession(Session $session) { + $this->_setCache(CacheTypes::SESSIONS . DIRECTORY_SEPARATOR . CacheUtil::getCacheFileName($session->getUUID()), $session); } /** * @param $key - * @return null|Response|KeyInfo + * @return KeyInfo|null */ - function getCachedKeyInfo($key) { + public function getKeyInfo($key) { return $this->wrapProvider( $this->getHypixelPHP()->getProvider()->getKeyInfo(), - $this->getCache(CacheTypes::SESSIONS . DIRECTORY_SEPARATOR . CacheUtil::getCacheFileName($key)) + $this->_getCache(CacheTypes::SESSIONS . DIRECTORY_SEPARATOR . CacheUtil::getCacheFileName($key)) ); } /** - * @param Leaderboards $leaderboards + * @param KeyInfo $keyInfo * @throws InvalidArgumentException */ - function setCachedLeaderboards(Leaderboards $leaderboards) { - $this->setObjCache(CacheTypes::LEADERBOARDS, $leaderboards); + public function setKeyInfo(KeyInfo $keyInfo) { + $this->_setCache(CacheTypes::API_KEYS . DIRECTORY_SEPARATOR . CacheUtil::getCacheFileName($keyInfo->getKey()), $keyInfo); } /** - * @return null|Response|Leaderboards + * @return Leaderboards|null */ - function getCachedLeaderboards() { + public function getLeaderboards() { return $this->wrapProvider( $this->getHypixelPHP()->getProvider()->getLeaderboards(), - $this->getCache(CacheTypes::LEADERBOARDS) + $this->_getCache(CacheTypes::LEADERBOARDS) ); } /** - * @param Boosters $boosters + * @param Leaderboards $leaderboards * @throws InvalidArgumentException */ - function setCachedBoosters(Boosters $boosters) { - $this->setObjCache(CacheTypes::BOOSTERS, $boosters); + public function setLeaderboards(Leaderboards $leaderboards) { + $this->_setCache(CacheTypes::LEADERBOARDS, $leaderboards); } /** - * @return null|Response|Boosters + * @return Boosters|null */ - function getCachedBoosters() { + public function getBoosters() { return $this->wrapProvider( $this->getHypixelPHP()->getProvider()->getBoosters(), - $this->getCache(CacheTypes::BOOSTERS) + $this->_getCache(CacheTypes::BOOSTERS) ); } /** - * @param WatchdogStats $watchdogStats + * @param Boosters $boosters * @throws InvalidArgumentException */ - function setCachedWatchdogStats(WatchdogStats $watchdogStats) { - $this->setObjCache(CacheTypes::WATCHDOG_STATS, $watchdogStats); + public function setBoosters(Boosters $boosters) { + $this->_setCache(CacheTypes::BOOSTERS, $boosters); } /** - * @return null|Response|WatchdogStats + * @return WatchdogStats|null */ - function getCachedWatchdogStats() { + public function getWatchdogStats() { return $this->wrapProvider( $this->getHypixelPHP()->getProvider()->getWatchdogStats(), - $this->getCache(CacheTypes::WATCHDOG_STATS) + $this->_getCache(CacheTypes::WATCHDOG_STATS) ); } /** - * @param PlayerCount $playerCount + * @param WatchdogStats $watchdogStats * @throws InvalidArgumentException */ - function setCachedPlayerCount(PlayerCount $playerCount) { - $this->setObjCache(CacheTypes::PLAYER_COUNT, $playerCount); + public function setWatchdogStats(WatchdogStats $watchdogStats) { + $this->_setCache(CacheTypes::WATCHDOG_STATS, $watchdogStats); } /** - * @return null|Response|PlayerCount + * @return PlayerCount|null */ - function getCachedPlayerCount() { + public function getPlayerCount() { return $this->wrapProvider( $this->getHypixelPHP()->getProvider()->getPlayerCount(), - $this->getCache(CacheTypes::PLAYER_COUNT) + $this->_getCache(CacheTypes::PLAYER_COUNT) ); } /** - * @param GameCounts $gameCounts + * @param PlayerCount $playerCount * @throws InvalidArgumentException */ - function setCachedGameCounts(GameCounts $gameCounts) { - $this->setObjCache(CacheTypes::GAME_COUNTS, $gameCounts); + public function setPlayerCount(PlayerCount $playerCount) { + $this->_setCache(CacheTypes::PLAYER_COUNT, $playerCount); } /** - * @return null|Response|GameCounts + * @return GameCounts|null */ - function getCachedGameCounts() { + public function getGameCounts() { return $this->wrapProvider( $this->getHypixelPHP()->getProvider()->getGameCounts(), - $this->getCache(CacheTypes::GAME_COUNTS) + $this->_getCache(CacheTypes::GAME_COUNTS) ); } + + /** + * @param GameCounts $gameCounts + * @throws InvalidArgumentException + */ + public function setGameCounts(GameCounts $gameCounts) { + $this->_setCache(CacheTypes::GAME_COUNTS, $gameCounts); + } + } \ No newline at end of file diff --git a/src/cache/impl/MongoCacheHandler.php b/src/cache/impl/MongoCacheHandler.php index d206e67..488e44b 100644 --- a/src/cache/impl/MongoCacheHandler.php +++ b/src/cache/impl/MongoCacheHandler.php @@ -3,12 +3,12 @@ namespace Plancke\HypixelPHP\cache\impl; use MongoDB\Client; +use MongoDB\Database; use Plancke\HypixelPHP\cache\CacheHandler; use Plancke\HypixelPHP\cache\CacheTimes; use Plancke\HypixelPHP\cache\CacheTypes; use Plancke\HypixelPHP\classes\HypixelObject; use Plancke\HypixelPHP\exceptions\InvalidArgumentException; -use Plancke\HypixelPHP\fetch\Response; use Plancke\HypixelPHP\HypixelPHP; use Plancke\HypixelPHP\responses\booster\Boosters; use Plancke\HypixelPHP\responses\friend\Friends; @@ -20,6 +20,7 @@ use Plancke\HypixelPHP\responses\PlayerCount; use Plancke\HypixelPHP\responses\Session; use Plancke\HypixelPHP\responses\WatchdogStats; +use Plancke\HypixelPHP\util\CacheUtil; /** * Implementation for CacheHandler, stores data in MongoDB @@ -72,19 +73,26 @@ public function ensureIndexes() { * Select the mongo database to use * * @param string $db - * @return \MongoDB\Database + * @return Database */ public function selectDB($db = "HypixelPHP") { return $this->mongoClient->selectDatabase($db); } /** - * @param Player $player - * @throws InvalidArgumentException + * @param $collection + * @param $query + * @return array|null */ - public function setCachedPlayer(Player $player) { - $query = ['record.uuid' => (string)$player->getUUID()]; - $this->updateCollection(CacheTypes::PLAYERS, $query, $player); + public function queryCollection($collection, $query) { + return $this->selectDB()->selectCollection($collection)->findOne($query, [ + 'typeMap' => [ + 'root' => 'array', + 'document' => 'array', + 'array' => 'array' + ], + "maxTimeMS" => 1000 + ]); } /** @@ -100,11 +108,35 @@ public function updateCollection($collection, $query, $obj) { $this->selectDB()->selectCollection($collection)->replaceOne($query, $this->objToArray($obj), ['upsert' => true]); } + /** + * @param $key + * @param $constructor + * @return HypixelObject|null + */ + function getSingleSave($key, $constructor) { + $query = ['key' => $key]; + return $this->wrapProvider($constructor, $this->queryCollection(MongoCacheHandler::SINGLE_SAVE, $query)); + } + + /** + * @param $key + * @param HypixelObject $hypixelObject + * @throws InvalidArgumentException + */ + function setSingleSave($key, HypixelObject $hypixelObject) { + $query = ['key' => $key]; + + $raw = $hypixelObject->getRaw(); + $raw['key'] = $key; + + $this->updateCollection(MongoCacheHandler::SINGLE_SAVE, $query, $raw); + } + /** * @param $uuid - * @return null|Response|Player + * @return Player|null */ - function getCachedPlayer($uuid) { + public function getPlayer($uuid) { $query = ['record.uuid' => (string)$uuid]; return $this->wrapProvider( $this->getHypixelPHP()->getProvider()->getPlayer(), @@ -113,40 +145,17 @@ function getCachedPlayer($uuid) { } /** - * @param $collection - * @param $query - * @return array|null - */ - public function queryCollection($collection, $query) { - return $this->selectDB()->selectCollection($collection)->findOne($query, [ - 'typeMap' => [ - 'root' => 'array', - 'document' => 'array', - 'array' => 'array' - ], - "maxTimeMS" => 1000 - ]); - } - - /** - * @param $username - * @param $obj + * @param Player $player * @throws InvalidArgumentException */ - function setPlayerUUID($username, $obj) { - $query = ['name_lowercase' => strtolower($username)]; - if ($obj['uuid'] == '' || $obj['uuid'] == null) { - // still not found, just update time so we don't keep fetching - // $this->updateCollection(CollectionNames::PLAYER_UUID, $query, ['$set' => [['timestamp' => time()]]]); - $this->selectDB()->selectCollection(CacheTypes::PLAYER_UUID)->updateOne($query, ['$set' => ['timestamp' => time()]]); - } else { - $this->updateCollection(CacheTypes::PLAYER_UUID, $query, $obj); - } + public function setPlayer(Player $player) { + $query = ['record.uuid' => (string)$player->getUUID()]; + $this->updateCollection(CacheTypes::PLAYERS, $query, $player); } /** * @param $username - * @return mixed|null|string + * @return string|null */ function getUUID($username) { $username = strtolower($username); @@ -163,7 +172,7 @@ function getUUID($username) { $timestamp = array_key_exists('timestamp', $data) ? $data['timestamp'] : 0; $diff = time() - $cacheTime - $timestamp; - $this->getHypixelPHP()->getLogger()->log("Found name match in PLAYER_UUID! '$diff'"); + $this->getHypixelPHP()->getLogger()->log(LOG_DEBUG, "Found name match in PLAYER_UUID! '$diff'"); if ($diff < 0) { return $data['uuid']; @@ -177,7 +186,7 @@ function getUUID($username) { $timestamp = array_key_exists('timestamp', $data) ? $data['timestamp'] : 0; $diff = time() - $this->getCacheTime(CacheTimes::UUID) - $timestamp; - $this->getHypixelPHP()->getLogger()->log("Found name match in PLAYERS! '$diff'"); + $this->getHypixelPHP()->getLogger()->log(LOG_DEBUG, "Found name match in PLAYERS! '$diff'"); if ($diff < 0) { if (isset($data['record']['uuid']) && $data['record']['uuid'] != '') { @@ -193,7 +202,7 @@ function getUUID($username) { $timestamp = array_key_exists('timestamp', $data) ? $data['timestamp'] : 0; $diff = time() - $this->getCacheTime(CacheTimes::UUID) - $timestamp; - $this->getHypixelPHP()->getLogger()->log("Found name match in PLAYERS! '$diff'"); + $this->getHypixelPHP()->getLogger()->log(LOG_DEBUG, "Found name match in PLAYERS! '$diff'"); if ($diff < 0) { if (isset($data['record']['uuid']) && $data['record']['uuid'] != '') { @@ -207,19 +216,26 @@ function getUUID($username) { } /** - * @param Guild $guild + * @param $username + * @param $obj * @throws InvalidArgumentException */ - function setCachedGuild(Guild $guild) { - $query = ['record._id' => (string)$guild->getID()]; - $this->updateCollection(CacheTypes::GUILDS, $query, $guild); + public function setPlayerUUID($username, $obj) { + $query = ['name_lowercase' => strtolower($username)]; + if ($obj['uuid'] == '' || $obj['uuid'] == null) { + // still not found, just update time so we don't keep fetching + // $this->updateCollection(CollectionNames::PLAYER_UUID, $query, ['$set' => [['timestamp' => time()]]]); + $this->selectDB()->selectCollection(CacheTypes::PLAYER_UUID)->updateOne($query, ['$set' => ['timestamp' => time()]]); + } else { + $this->updateCollection(CacheTypes::PLAYER_UUID, $query, $obj); + } } /** * @param $id - * @return null|Response|Guild + * @return Guild|null */ - function getCachedGuild($id) { + public function getGuild($id) { $query = ['record._id' => (string)$id]; return $this->wrapProvider( $this->getHypixelPHP()->getProvider()->getGuild(), @@ -228,21 +244,22 @@ function getCachedGuild($id) { } /** - * @param $uuid - * @param $obj + * @param Guild $guild * @throws InvalidArgumentException */ - function setGuildIDForUUID($uuid, $obj) { - $query = ['uuid' => (string)$uuid]; - $this->updateCollection(CacheTypes::GUILDS_UUID, $query, $obj); + public function setGuild(Guild $guild) { + $query = ['record._id' => (string)$guild->getID()]; + $this->updateCollection(CacheTypes::GUILDS, $query, $guild); } /** * @param $uuid - * @return mixed|null + * @return string|null */ function getGuildIDForUUID($uuid) { $query = ['uuid' => (string)$uuid]; + // TODO Do we really need this collection? + // Could just check members object inside the documents? $data = $this->queryCollection(CacheTypes::GUILDS_UUID, $query); if ($data != null) { if (isset($data['uuid']) && $data['uuid'] != null && $data['uuid'] != '') { @@ -251,28 +268,25 @@ function getGuildIDForUUID($uuid) { $cacheTime = $this->getCacheTime(CacheTimes::GUILD_NOT_FOUND); } $timestamp = array_key_exists('timestamp', $data) ? $data['timestamp'] : 0; - $diff = time() - $cacheTime - $timestamp; - - if ($diff < 0) { - return $data['guild']; - } + if (CacheUtil::isExpired($timestamp, $cacheTime)) return null; + return $data['guild']; } return null; } /** - * @param $name + * @param $uuid * @param $obj * @throws InvalidArgumentException */ - function setGuildIDForName($name, $obj) { - $query = ['name_lower' => strtolower((string)$name)]; - $this->updateCollection(CacheTypes::GUILDS_NAME, $query, $obj); + function setGuildIDForUUID($uuid, $obj) { + $query = ['uuid' => (string)$uuid]; + $this->updateCollection(CacheTypes::GUILDS_UUID, $query, $obj); } /** * @param $name - * @return mixed|null + * @return string|null */ function getGuildIDForName($name) { $query = ['record.name_lower' => strtolower((string)$name)]; @@ -280,9 +294,9 @@ function getGuildIDForName($name) { if ($data != null) { $cacheTime = $this->getCacheTime(CacheTimes::GUILD); $timestamp = array_key_exists('timestamp', $data) ? $data['timestamp'] : 0; - $diff = time() - $cacheTime - $timestamp; - if ($diff < 0) { + if (!CacheUtil::isExpired($timestamp, $cacheTime)) { + // it's not expired, return guild directly return $this->wrapProvider($this->getHypixelPHP()->getProvider()->getGuild(), $data); } } @@ -296,29 +310,27 @@ function getGuildIDForName($name) { $cacheTime = $this->getCacheTime(CacheTimes::GUILD_NOT_FOUND); } $timestamp = array_key_exists('timestamp', $data) ? $data['timestamp'] : 0; - $diff = time() - $cacheTime - $timestamp; - - if ($diff < 0) { - return $data['guild']; - } + if (CacheUtil::isExpired($timestamp, $cacheTime)) return null; + return $data['guild']; } return null; } /** - * @param Friends $friends + * @param $name + * @param $obj * @throws InvalidArgumentException */ - function setCachedFriends(Friends $friends) { - $query = ['record.uuid' => (string)$friends->getUUID()]; - $this->updateCollection(CacheTypes::FRIENDS, $query, $friends); + function setGuildIDForName($name, $obj) { + $query = ['name_lower' => strtolower((string)$name)]; + $this->updateCollection(CacheTypes::GUILDS_NAME, $query, $obj); } /** * @param $uuid - * @return null|Response|Friends + * @return Friends|null */ - function getCachedFriends($uuid) { + public function getFriends($uuid) { $query = ['record.uuid' => (string)$uuid]; return $this->wrapProvider( $this->getHypixelPHP()->getProvider()->getFriends(), @@ -327,15 +339,19 @@ function getCachedFriends($uuid) { } /** - * @param Session $session + * @param Friends $friends * @throws InvalidArgumentException */ - function setCachedSession(Session $session) { - $query = ['record.uuid' => (string)$session->getUUID()]; - $this->updateCollection(CacheTypes::SESSIONS, $query, $session); + public function setFriends(Friends $friends) { + $query = ['record.uuid' => (string)$friends->getUUID()]; + $this->updateCollection(CacheTypes::FRIENDS, $query, $friends); } - function getCachedSession($uuid) { + /** + * @param $uuid + * @return Session|null + */ + public function getSession($uuid) { $query = ['record.uuid' => (string)$uuid]; return $this->wrapProvider( $this->getHypixelPHP()->getProvider()->getSession(), @@ -344,19 +360,19 @@ function getCachedSession($uuid) { } /** - * @param KeyInfo $keyInfo + * @param Session $session * @throws InvalidArgumentException */ - function setCachedKeyInfo(KeyInfo $keyInfo) { - $query = ['record.key' => (string)$keyInfo->getKey()]; - $this->updateCollection(CacheTypes::API_KEYS, $query, $keyInfo); + public function setSession(Session $session) { + $query = ['record.uuid' => (string)$session->getUUID()]; + $this->updateCollection(CacheTypes::SESSIONS, $query, $session); } /** * @param $key - * @return null|Response|KeyInfo + * @return KeyInfo|null */ - function getCachedKeyInfo($key) { + public function getKeyInfo($key) { $query = ['record.key' => (string)$key]; return $this->wrapProvider( $this->getHypixelPHP()->getProvider()->getKeyInfo(), @@ -365,101 +381,94 @@ function getCachedKeyInfo($key) { } /** - * @param Leaderboards $leaderboards + * @param KeyInfo $keyInfo * @throws InvalidArgumentException */ - function setCachedLeaderboards(Leaderboards $leaderboards) { - $this->setSingleSave(CacheTypes::LEADERBOARDS, $leaderboards); + public function setKeyInfo(KeyInfo $keyInfo) { + $query = ['record.key' => (string)$keyInfo->getKey()]; + $this->updateCollection(CacheTypes::API_KEYS, $query, $keyInfo); } + /** - * @param $key - * @param HypixelObject $hypixelObject - * @throws InvalidArgumentException + * @return Leaderboards|null */ - function setSingleSave($key, HypixelObject $hypixelObject) { - $query = ['key' => $key]; - - $raw = $hypixelObject->getRaw(); - $raw['key'] = $key; - - $this->updateCollection(MongoCacheHandler::SINGLE_SAVE, $query, $raw); + public function getLeaderboards() { + /** @noinspection PhpIncompatibleReturnTypeInspection */ + return $this->getSingleSave(CacheTypes::LEADERBOARDS, $this->getHypixelPHP()->getProvider()->getLeaderboards()); } /** - * @return null|HypixelObject|Response|Leaderboards + * @param Leaderboards $leaderboards + * @throws InvalidArgumentException */ - function getCachedLeaderboards() { - return $this->getSingleSave(CacheTypes::LEADERBOARDS, $this->getHypixelPHP()->getProvider()->getLeaderboards()); + public function setLeaderboards(Leaderboards $leaderboards) { + $this->setSingleSave(CacheTypes::LEADERBOARDS, $leaderboards); } + /** - * @param $key - * @param $constructor - * @return HypixelObject|null + * @return Boosters|null */ - function getSingleSave($key, $constructor) { - $query = ['key' => $key]; - return $this->wrapProvider($constructor, $this->queryCollection(MongoCacheHandler::SINGLE_SAVE, $query)); + public function getBoosters() { + /** @noinspection PhpIncompatibleReturnTypeInspection */ + return $this->getSingleSave(CacheTypes::BOOSTERS, $this->getHypixelPHP()->getProvider()->getBoosters()); } /** * @param Boosters $boosters * @throws InvalidArgumentException */ - function setCachedBoosters(Boosters $boosters) { + public function setBoosters(Boosters $boosters) { $this->setSingleSave(CacheTypes::BOOSTERS, $boosters); } + /** - * @return null|HypixelObject|Response|Boosters + * @return WatchdogStats|null */ - function getCachedBoosters() { - return $this->getSingleSave(CacheTypes::BOOSTERS, $this->getHypixelPHP()->getProvider()->getBoosters()); + public function getWatchdogStats() { + /** @noinspection PhpIncompatibleReturnTypeInspection */ + return $this->getSingleSave(CacheTypes::WATCHDOG_STATS, $this->getHypixelPHP()->getProvider()->getWatchdogStats()); } /** * @param WatchdogStats $watchdogStats * @throws InvalidArgumentException */ - function setCachedWatchdogStats(WatchdogStats $watchdogStats) { + public function setWatchdogStats(WatchdogStats $watchdogStats) { $this->setSingleSave(CacheTypes::WATCHDOG_STATS, $watchdogStats); } /** - * @return null|HypixelObject|Response|WatchdogStats + * @return PlayerCount|null */ - function getCachedWatchdogStats() { - return $this->getSingleSave(CacheTypes::WATCHDOG_STATS, $this->getHypixelPHP()->getProvider()->getWatchdogStats()); + public function getPlayerCount() { + /** @noinspection PhpIncompatibleReturnTypeInspection */ + return $this->getSingleSave(CacheTypes::PLAYER_COUNT, $this->getHypixelPHP()->getProvider()->getPlayerCount()); } /** * @param PlayerCount $playerCount * @throws InvalidArgumentException */ - function setCachedPlayerCount(PlayerCount $playerCount) { + public function setPlayerCount(PlayerCount $playerCount) { $this->setSingleSave(CacheTypes::PLAYER_COUNT, $playerCount); } /** - * @return null|HypixelObject|Response|PlayerCount + * @return GameCounts|null */ - function getCachedPlayerCount() { - return $this->getSingleSave(CacheTypes::PLAYER_COUNT, $this->getHypixelPHP()->getProvider()->getPlayerCount()); + public function getGameCounts() { + /** @noinspection PhpIncompatibleReturnTypeInspection */ + return $this->getSingleSave(CacheTypes::GAME_COUNTS, $this->getHypixelPHP()->getProvider()->getGameCounts()); } /** * @param GameCounts $gameCounts * @throws InvalidArgumentException */ - function setCachedGameCounts(GameCounts $gameCounts) { + public function setGameCounts(GameCounts $gameCounts) { $this->setSingleSave(CacheTypes::GAME_COUNTS, $gameCounts); } - - /** - * @return null|HypixelObject|Response|GameCounts - */ - function getCachedGameCounts() { - return $this->getSingleSave(CacheTypes::GAME_COUNTS, $this->getHypixelPHP()->getProvider()->getGameCounts()); - } } \ No newline at end of file diff --git a/tests/util/NoCacheHandler.php b/src/cache/impl/NoCacheHandler.php similarity index 76% rename from tests/util/NoCacheHandler.php rename to src/cache/impl/NoCacheHandler.php index ac20d60..2a00e2d 100644 --- a/tests/util/NoCacheHandler.php +++ b/src/cache/impl/NoCacheHandler.php @@ -1,6 +1,6 @@ getHypixelPHP()->getLogger()->log('Extra \'' . $key . '\' set to ' . json_encode($val)); + $this->getHypixelPHP()->getLogger()->log(LOG_DEBUG, 'Extra \'' . $key . '\' set to ' . var_export($val, true)); $this->data['extra'][$key] = $val; $anyChange = true; } if ($anyChange && $save) { - $this->getHypixelPHP()->getCacheHandler()->_setCache($this); + $this->getHypixelPHP()->getCacheHandler()->setCache($this); } } diff --git a/src/classes/gameType/GameTypes.php b/src/classes/gameType/GameTypes.php index 2d9af86..0014f38 100644 --- a/src/classes/gameType/GameTypes.php +++ b/src/classes/gameType/GameTypes.php @@ -12,8 +12,6 @@ class GameTypes { const QUAKE = 2; const WALLS = 3; const PAINTBALL = 4; - /** @deprecated */ - const HUNGERGAMES = 5; const SURVIVAL_GAMES = 5; const TNTGAMES = 6; const VAMPIREZ = 7; @@ -109,7 +107,6 @@ public static function fromID($id) { return new GameType('WALLS', 'Walls', 'Walls', 'Walls', GameTypes::WALLS, false); case GameTypes::PAINTBALL: return new GameType('PAINTBALL', 'Paintball', 'Paintball', 'Paintball', GameTypes::PAINTBALL, false); - case GameTypes::HUNGERGAMES: case GameTypes::SURVIVAL_GAMES: return new GameType('SURVIVAL_GAMES', 'HungerGames', 'Blitz Survival Games', 'BSG', GameTypes::SURVIVAL_GAMES); case GameTypes::TNTGAMES: diff --git a/src/color/ColorUtils.php b/src/color/ColorUtils.php index 8564560..3dd119d 100644 --- a/src/color/ColorUtils.php +++ b/src/color/ColorUtils.php @@ -108,7 +108,6 @@ public static function getAllFormattingCodes() { // - /** * Removes all MC encoded colors from a string * @param $string diff --git a/src/exceptions/HypixelPHPException.php b/src/exceptions/HypixelPHPException.php index e1fe707..a1d2ff1 100644 --- a/src/exceptions/HypixelPHPException.php +++ b/src/exceptions/HypixelPHPException.php @@ -2,10 +2,12 @@ namespace Plancke\HypixelPHP\exceptions; +use Exception; + /** * Class HypixelPHPException * @package Plancke\HypixelPHP\exceptions */ -class HypixelPHPException extends \Exception { +class HypixelPHPException extends Exception { } \ No newline at end of file diff --git a/src/fetch/Fetcher.php b/src/fetch/Fetcher.php index f98966d..3d9b1dc 100644 --- a/src/fetch/Fetcher.php +++ b/src/fetch/Fetcher.php @@ -30,6 +30,27 @@ public function __construct(HypixelPHP $HypixelPHP) { }); } + /** + * @return ResponseAdapter + */ + public function getResponseAdapter() { + if ($this->responseAdapter == null) { + $getter = $this->responseAdapterGetter; + $this->responseAdapter = $getter($this->getHypixelPHP()); + } + return $this->responseAdapter; + } + + /** + * @param ResponseAdapter $responseAdapter + * @return $this + */ + public function setResponseAdapter(ResponseAdapter $responseAdapter) { + $this->responseAdapter = $responseAdapter; + $this->responseAdapterGetter = null; + return $this; + } + /** * @param Closure $getter * @return $this @@ -56,29 +77,6 @@ public function setTimeOut($timeOut) { return $this; } - /** - * @return ResponseAdapter - */ - public function getResponseAdapter() { - if ($this->responseAdapter == null) { - $getter = $this->responseAdapterGetter; - $this->responseAdapter = $getter($this->getHypixelPHP()); - } - return $this->responseAdapter; - } - - /** - * @param ResponseAdapter $logger - * @return $this - */ - public function setResponseAdapter(ResponseAdapter $logger) { - $this->responseAdapter = $logger; - $this->responseAdapterGetter = function ($HypixelAPI) use ($logger) { - return $logger; - }; - return $this; - } - /** * @param string $fetch * @param array $keyValues diff --git a/src/fetch/impl/DefaultFetcher.php b/src/fetch/impl/DefaultFetcher.php index dcfdfca..1403143 100644 --- a/src/fetch/impl/DefaultFetcher.php +++ b/src/fetch/impl/DefaultFetcher.php @@ -49,17 +49,17 @@ public function fetch($fetch, $keyValues = []) { $requestURL .= '&' . $key . '=' . $value; $debug .= '?' . $key . '=' . $value; } - $this->getHypixelPHP()->getLogger()->log('Starting Fetch: ' . $debug); + $this->getHypixelPHP()->getLogger()->log(LOG_DEBUG, 'Starting Fetch: ' . $debug); $response = $this->getURLContents($requestURL); if (!$response->wasSuccessful()) { - $this->getHypixelPHP()->getLogger()->log('Fetch Failed! ' . var_export($response, true)); + $this->getHypixelPHP()->getLogger()->log(LOG_DEBUG, 'Fetch Failed! ' . var_export($response, true)); // If one fails, stop trying for that session // ideally also have a cached check before $this->getHypixelPHP()->getCacheHandler()->setGlobalTime(CacheHandler::MAX_CACHE_TIME); } else { - $this->getHypixelPHP()->getLogger()->log('Fetch successful!'); + $this->getHypixelPHP()->getLogger()->log(LOG_DEBUG, 'Fetch successful!'); } return $this->getResponseAdapter()->adaptResponse($fetch, $keyValues, $response); diff --git a/src/log/Formatter.php b/src/log/Formatter.php index 21bb8ab..091b115 100644 --- a/src/log/Formatter.php +++ b/src/log/Formatter.php @@ -9,9 +9,10 @@ abstract class Formatter { /** + * @param $level * @param string $line * @return string */ - public abstract function formatLine($line); + public abstract function formatLine($level, $line); } \ No newline at end of file diff --git a/src/log/Logger.php b/src/log/Logger.php index da77c27..fd196b9 100644 --- a/src/log/Logger.php +++ b/src/log/Logger.php @@ -3,7 +3,6 @@ namespace Plancke\HypixelPHP\log; use Plancke\HypixelPHP\classes\Module; -use Plancke\HypixelPHP\log\impl\DefaultFormatter; /** * Class Logger @@ -12,35 +11,27 @@ abstract class Logger extends Module { protected $enabled = true; - protected $log_folder; protected $formatter; /** - * @return string + * @param int $level + * @param string $line */ - public function getLogFolder() { - return $this->log_folder; - } + public function log($level, $line) { + if (!$this->isEnabled()) return; - /** - * @param string $log_folder - * @return $this - */ - public function setLogFolder($log_folder) { - $this->log_folder = $log_folder; - return $this; + if ($this->getFormatter() != null) { + $line = $this->getFormatter()->formatLine($level, $line); + } + + $this->actuallyLog($level, $line); } /** + * @param int $level * @param string $line */ - public function log($line) { - if (!$this->isEnabled()) { - return; - } - - $this->actuallyLog($this->getFormatter()->formatLine($line)); - } + protected abstract function actuallyLog($level, $line); /** * @return boolean @@ -59,17 +50,9 @@ public function setEnabled($enabled) { } /** - * @param string $line - */ - protected abstract function actuallyLog($line); - - /** - * @return Formatter + * @return Formatter|null */ public function getFormatter() { - if ($this->formatter == null) { - $this->setFormatter(new DefaultFormatter()); - } return $this->formatter; } diff --git a/src/log/impl/DefaultLogger.php b/src/log/impl/BasicLogger.php similarity index 70% rename from src/log/impl/DefaultLogger.php rename to src/log/impl/BasicLogger.php index 42ee633..6bb8897 100644 --- a/src/log/impl/DefaultLogger.php +++ b/src/log/impl/BasicLogger.php @@ -3,14 +3,16 @@ namespace Plancke\HypixelPHP\log\impl; use Plancke\HypixelPHP\HypixelPHP; +use Plancke\HypixelPHP\log\Formatter; use Plancke\HypixelPHP\log\Logger; /** - * Class DefaultLogger + * Class BasicLogger * @package Plancke\HypixelPHP\log\impl */ -class DefaultLogger extends Logger { +class BasicLogger extends Logger { + protected $log_folder; /** * Size of the individual files, in bytes (100MB by default) */ @@ -23,7 +25,27 @@ class DefaultLogger extends Logger { function __construct(HypixelPHP $HypixelPHP) { parent::__construct($HypixelPHP); - $this->setFormatter(new DefaultFormatter()); + $this->setFormatter(new class() extends Formatter { + public function formatLine($level, $line) { + return '[' . date("d-m-Y H:i:s") . '] [' . $level . '] ' . $line; + } + }); + } + + /** + * @return string + */ + public function getLogFolder() { + return $this->log_folder; + } + + /** + * @param string $log_folder + * @return $this + */ + public function setLogFolder($log_folder) { + $this->log_folder = $log_folder; + return $this; } /** @@ -48,9 +70,10 @@ public function setSize($size) { * - LOG_FOLDER/DATE/0.log * - LOG_FOLDER/DATE/1.log * separated every {@link $this->size} + * @param $level * @param string $line */ - public function actuallyLog($line) { + public function actuallyLog($level, $line) { $dirName = $this->log_folder . DIRECTORY_SEPARATOR . date("Y-m-d"); if (!file_exists($dirName)) { mkdir($dirName, 0777, true); diff --git a/src/log/impl/DefaultFormatter.php b/src/log/impl/DefaultFormatter.php deleted file mode 100644 index 60b8652..0000000 --- a/src/log/impl/DefaultFormatter.php +++ /dev/null @@ -1,21 +0,0 @@ -enabled = false; + } + + public function actuallyLog($level, $line) { + } + +} \ No newline at end of file diff --git a/src/log/impl/SysLogger.php b/src/log/impl/SysLogger.php new file mode 100644 index 0000000..095c191 --- /dev/null +++ b/src/log/impl/SysLogger.php @@ -0,0 +1,19 @@ +options = $options; - return $this; - } - - /** - * @param array $input - * @return $this - */ - public function setOptions($input) { - foreach ($input as $key => $val) { - if ($this->options[$key] != $val) { - if (is_array($val)) { - $this->getHypixelPHP()->getLogger()->log('Setting ' . $key . ' to ' . json_encode($val)); - } else { - $this->getHypixelPHP()->getLogger()->log('Setting ' . $key . ' to ' . $val); - } - } - $this->options[$key] = $val; - } - return $this; - } - -} \ No newline at end of file diff --git a/src/provider/Provider.php b/src/provider/Provider.php index bdae12d..59750a1 100644 --- a/src/provider/Provider.php +++ b/src/provider/Provider.php @@ -2,6 +2,7 @@ namespace Plancke\HypixelPHP\provider; +use Closure; use Plancke\HypixelPHP\classes\Module; use Plancke\HypixelPHP\responses\booster\Boosters; use Plancke\HypixelPHP\responses\friend\Friends; @@ -21,7 +22,7 @@ class Provider extends Module { /** - * @return \Closure + * @return Closure */ public function getPlayer() { return function ($HypixelPHP, $data) { @@ -30,7 +31,7 @@ public function getPlayer() { } /** - * @return \Closure + * @return Closure */ public function getGuild() { return function ($HypixelPHP, $data) { @@ -39,7 +40,7 @@ public function getGuild() { } /** - * @return \Closure + * @return Closure */ public function getSession() { return function ($HypixelPHP, $data) { @@ -48,7 +49,7 @@ public function getSession() { } /** - * @return \Closure + * @return Closure */ public function getFriends() { return function ($HypixelPHP, $data) { @@ -57,7 +58,7 @@ public function getFriends() { } /** - * @return \Closure + * @return Closure */ public function getBoosters() { return function ($HypixelPHP, $data) { @@ -66,7 +67,7 @@ public function getBoosters() { } /** - * @return \Closure + * @return Closure */ public function getLeaderboards() { return function ($HypixelPHP, $data) { @@ -75,7 +76,7 @@ public function getLeaderboards() { } /** - * @return \Closure + * @return Closure */ public function getKeyInfo() { return function ($HypixelPHP, $data) { @@ -84,7 +85,7 @@ public function getKeyInfo() { } /** - * @return \Closure + * @return Closure */ public function getWatchdogStats() { return function ($HypixelPHP, $data) { @@ -93,7 +94,7 @@ public function getWatchdogStats() { } /** - * @return \Closure + * @return Closure */ public function getPlayerCount() { return function ($HypixelPHP, $data) { @@ -102,7 +103,7 @@ public function getPlayerCount() { } /** - * @return \Closure + * @return Closure */ public function getGameCounts() { return function ($HypixelPHP, $data) { diff --git a/src/responses/player/GameStats.php b/src/responses/player/GameStats.php index a63a643..300341a 100644 --- a/src/responses/player/GameStats.php +++ b/src/responses/player/GameStats.php @@ -3,7 +3,6 @@ namespace Plancke\HypixelPHP\responses\player; use Plancke\HypixelPHP\classes\APIObject; -use Plancke\HypixelPHP\util\TimeUtils; /** * Class GameStats @@ -33,21 +32,4 @@ public function getCoins() { return $this->getInt('coins'); } - /** - * @param $stat - * @return mixed - * @deprecated These aren't used anymore - */ - public function getWeeklyStat($stat) { - return $this->get($stat . '_' . TimeUtils::getWeeklyOscillation()); - } - - /** - * @param $stat - * @return mixed - * @deprecated These aren't used anymore - */ - public function getMonthlyStat($stat) { - return $this->get($stat . '_' . TimeUtils::getMonthlyOscillation()); - } } \ No newline at end of file diff --git a/src/responses/player/Player.php b/src/responses/player/Player.php index 8208008..b8e77ec 100644 --- a/src/responses/player/Player.php +++ b/src/responses/player/Player.php @@ -47,32 +47,32 @@ public function getAchievementPoints($force_update = false) { $total = 0; $oneTime = $this->getArray('achievementsOneTime'); - $this->getHypixelPHP()->getLogger()->log('Starting OneTime Achievements'); + $this->getHypixelPHP()->getLogger()->log(LOG_DEBUG, 'Starting OneTime Achievements'); foreach ($oneTime as $dbName) { if (!is_string($dbName)) continue; $game = strtolower(substr($dbName, 0, strpos($dbName, "_"))); $dbName = strtoupper(substr($dbName, strpos($dbName, "_") + 1)); if (!in_array($game, $games)) continue; - $this->getHypixelPHP()->getLogger()->log('Achievement: ' . strtoupper(substr($dbName, strpos($dbName, "_")))); + $this->getHypixelPHP()->getLogger()->log(LOG_DEBUG, 'Achievement: ' . strtoupper(substr($dbName, strpos($dbName, "_")))); if (in_array($dbName, array_keys($achievements[$game]['one_time']))) { if (array_key_exists("legacy", $achievements[$game]['one_time'][$dbName]) && $achievements[$game]['one_time'][$dbName]["legacy"]) continue; - $this->getHypixelPHP()->getLogger()->log('Achievement: ' . $dbName . ' - ' . $achievements[$game]['one_time'][$dbName]['points']); + $this->getHypixelPHP()->getLogger()->log(LOG_DEBUG, 'Achievement: ' . $dbName . ' - ' . $achievements[$game]['one_time'][$dbName]['points']); $total += $achievements[$game]['one_time'][$dbName]['points']; } } $tiered = $this->getArray('achievements'); - $this->getHypixelPHP()->getLogger()->log('Starting Tiered Achievements'); + $this->getHypixelPHP()->getLogger()->log(LOG_DEBUG, 'Starting Tiered Achievements'); foreach ($tiered as $dbName => $value) { $game = strtolower(substr($dbName, 0, strpos($dbName, "_"))); $dbName = strtoupper(substr($dbName, strpos($dbName, "_") + 1)); if (!in_array($game, $games)) continue; - $this->getHypixelPHP()->getLogger()->log('Achievement: ' . $dbName); + $this->getHypixelPHP()->getLogger()->log(LOG_DEBUG, 'Achievement: ' . $dbName); if (in_array($dbName, array_keys($achievements[$game]['tiered']))) { if (array_key_exists("legacy", $achievements[$game]['tiered'][$dbName]) && $achievements[$game]['tiered'][$dbName]["legacy"]) continue; $tierTotal = 0; foreach ($achievements[$game]['tiered'][$dbName]['tiers'] as $tier) { if ($value >= $tier['amount']) { - $this->getHypixelPHP()->getLogger()->log('Tier: ' . $tier['amount'] . ' - ' . $tier['points']); + $this->getHypixelPHP()->getLogger()->log(LOG_DEBUG, 'Tier: ' . $tier['amount'] . ' - ' . $tier['points']); $tierTotal += $tier['points']; } } diff --git a/src/util/CacheUtil.php b/src/util/CacheUtil.php index 9f57694..3d1ab57 100644 --- a/src/util/CacheUtil.php +++ b/src/util/CacheUtil.php @@ -2,6 +2,8 @@ namespace Plancke\HypixelPHP\util; +use Exception; + /** * Class CacheUtil * @package Plancke\HypixelPHP\util @@ -40,7 +42,7 @@ public static function getRemainingTime($cachedTime, $duration, $offset = 0) { if (sizeof($offset) == 2) { try { $offsetValue = random_int($offset[0], $offset[1]); - } catch (\Exception $e) { + } catch (Exception $e) { $offsetValue = $offset[0]; // fallback } } diff --git a/src/util/InputType.php b/src/util/InputType.php index c47d456..1143293 100644 --- a/src/util/InputType.php +++ b/src/util/InputType.php @@ -21,17 +21,11 @@ abstract class InputType { * @return int|null */ public static function getType($input) { - if ($input instanceof Player) { - return InputType::PLAYER_OBJECT; - } + if ($input instanceof Player) return InputType::PLAYER_OBJECT; - if (Validator::isAnyUUID($input)) { - return InputType::UUID; - } + if (Validator::isAnyUUID($input)) return InputType::UUID; - if (Validator::isUsername($input)) { - return InputType::USERNAME; - } + if (Validator::isUsername($input)) return InputType::USERNAME; return null; } diff --git a/src/util/TimeUtils.php b/src/util/TimeUtils.php index 96d1280..c1ad945 100644 --- a/src/util/TimeUtils.php +++ b/src/util/TimeUtils.php @@ -3,6 +3,8 @@ namespace Plancke\HypixelPHP\util; use DateTime; +use DateTimeZone; +use Exception; /** * Class TimeUtils @@ -14,7 +16,6 @@ abstract class TimeUtils { * @return string */ public static function getWeeklyOscillation() { - date_default_timezone_set("America/New_York"); $epoch = 1417237200000; $milli = round(microtime(true) * 1000); @@ -27,13 +28,13 @@ public static function getWeeklyOscillation() { /** * Returns {@code a} or {@code b} depending on the current month * @return string + * @throws Exception */ public static function getMonthlyOscillation() { - date_default_timezone_set("America/New_York"); $epoch = 1417410000000; - $dateStart = new DateTime(date("Y-m-d")); - $dateEnd = new DateTime(date("Y-m-d", $epoch / 1000)); + $dateStart = new DateTime(date("Y-m-d"), self::getHypixelTimeZone()); + $dateEnd = new DateTime(date("Y-m-d", $epoch / 1000), self::getHypixelTimeZone()); $diffYear = $dateEnd->format("Y") - $dateStart->format("Y"); /* @var $diffYear int */ @@ -47,7 +48,10 @@ public static function getMonthlyOscillation() { * @return int */ public static function getJavaMonth(DateTime $date) { - date_default_timezone_set("America/New_York"); return $date->format("n") - 1; } + + public static function getHypixelTimeZone() { + return new DateTimeZone("America/New_York"); + } } \ No newline at end of file diff --git a/src/util/Utilities.php b/src/util/Utilities.php index 58c4ae6..0d23d70 100644 --- a/src/util/Utilities.php +++ b/src/util/Utilities.php @@ -12,6 +12,7 @@ abstract class Utilities { * Converts Hexadecimal color code into RGB * @param $hex * @return array + * @deprecated */ public static function hex2rgb($hex) { // replace the pound symbol just in case @@ -53,9 +54,7 @@ public static function getRecursiveValue($array, $key, $default = null, $delimit */ public static function ensureDashedUUID($uuid) { if (strpos($uuid, "-")) { - if (strlen($uuid) == 32) { - return $uuid; - } + if (strlen($uuid) == 32) return $uuid; $uuid = Utilities::ensureNoDashesUUID($uuid); } return substr($uuid, 0, 8) . "-" . substr($uuid, 8, 12) . substr($uuid, 12, 16) . "-" . substr($uuid, 16, 20) . "-" . substr($uuid, 20, 32); @@ -73,6 +72,7 @@ public static function ensureNoDashesUUID($uuid) { * @param $filename * * @return null|string + * @deprecated */ public static function getFileContent($filename) { $content = null; @@ -88,14 +88,14 @@ public static function getFileContent($filename) { /** * @param $filename - * @param $content + * @param $content * + * @deprecated */ public static function setFileContent($filename, $content) { if (!file_exists(dirname($filename))) { - @mkdir(dirname($filename), 0777, true); + @mkdir(dirname($filename), 0744, true); } - $file = fopen($filename, 'w+'); - fwrite($file, $content); - fclose($file); + + file_put_contents($filename, $content); } } \ No newline at end of file diff --git a/src/util/games/bedwars/BedWarsPrestige.php b/src/util/games/bedwars/BedWarsPrestige.php index 49ae65f..b70fa28 100644 --- a/src/util/games/bedwars/BedWarsPrestige.php +++ b/src/util/games/bedwars/BedWarsPrestige.php @@ -123,4 +123,11 @@ private static function fromID0($id) { return null; } } + + /** + * @return array + */ + public static function getRainbowColors(): array { + return self::$rainbowColors; + } } \ No newline at end of file diff --git a/src/wrappers/battlegrounds/weapon/Weapon.php b/src/wrappers/battlegrounds/weapon/Weapon.php index 0a8e651..7696dea 100644 --- a/src/wrappers/battlegrounds/weapon/Weapon.php +++ b/src/wrappers/battlegrounds/weapon/Weapon.php @@ -69,7 +69,8 @@ class Weapon { "Vanquisher's", "Champion's", "Warlord's" ] ]; - protected static $materialMap = [ + protected static /** @noinspection SpellCheckingInspection */ + $materialMap = [ 'WOOD_AXE' => 'Steel Sword', 'STONE_AXE' => 'Training Sword', 'IRON_AXE' => 'Demonblade', 'GOLD_AXE' => 'Venomstrike', 'DIAMOND_AXE' => 'Diamondspark', 'WOOD_HOE' => 'Zweireaper', 'STONE_HOE' => 'Runeblade', 'IRON_HOE' => 'Elven Greatsword', 'GOLD_HOE' => 'Hatchet', diff --git a/tests/APITest.php b/tests/APITest.php deleted file mode 100644 index dbfe4a1..0000000 --- a/tests/APITest.php +++ /dev/null @@ -1,38 +0,0 @@ -assertEquals(ExceptionCodes::NO_KEY, $e->getCode()); - } - } - - function testInvalidKey() { - try { - new HypixelPHP("INVALID"); - } catch (HypixelPHPException $e) { - $this->assertEquals(ExceptionCodes::INVALID_KEY, $e->getCode()); - } - } - - function testValidKey() { - try { - new HypixelPHP("b13e2f50-a16c-4aa5-92a6-75e9b699b9fc"); - } catch (HypixelPHPException $e) { - $this->fail(); - } - - $this->assertTrue(TRUE); - } - -} diff --git a/tests/ResponseTest.php b/tests/ResponseTest.php index fe3358a..5e4eeee 100644 --- a/tests/ResponseTest.php +++ b/tests/ResponseTest.php @@ -4,27 +4,17 @@ use PHPUnit\Framework\TestCase; use Plancke\HypixelPHP\exceptions\HypixelPHPException; -use Plancke\HypixelPHP\fetch\FetchParams; -use Plancke\HypixelPHP\responses\player\Player; -use Plancke\HypixelPHP\responses\player\Stats; use Plancke\HypixelPHP\responses\PlayerCount; use Plancke\Tests\util\TestUtil; class ResponseTest extends TestCase { - /** - * @throws HypixelPHPException - */ - function testPlayerResponse() { - $player = TestUtil::getHypixelPHP()->getPlayer([FetchParams::PLAYER_BY_UUID => TestUtil::PLANCKE]); - $this->assertTrue($player instanceof Player); - $this->assertTrue($player->getStats() instanceof Stats); - } - /** * @throws HypixelPHPException */ 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); } diff --git a/tests/ValidatorTest.php b/tests/ValidatorTest.php index cd1f3fc..cbf1079 100644 --- a/tests/ValidatorTest.php +++ b/tests/ValidatorTest.php @@ -7,31 +7,33 @@ class ValidatorTest extends TestCase { - function testUUIDMatcher() { - $UUID = 'f025c1c7-f55a-4ea0-b8d9-3f47d17dfe0f'; // dashes - $this->assertTrue(Validator::isAnyUUID($UUID)); - $UUID = 'f025c1c7f55a4ea0b8d93f47d17dfe0f'; // no dashes - $this->assertTrue(Validator::isAnyUUID($UUID)); - $UUID = 'f025c1c7f55a9ea0b8d93f47d17dfe0f'; // bad version - $this->assertFalse(Validator::isAnyUUID($UUID)); - $UUID = 'f025c1c7f55a4ea0b8d93f47d17dfe0g'; // bad last character - $this->assertFalse(Validator::isAnyUUID($UUID)); - $UUID = 'f025c1c7f55a4ea0b8d93f47d17dfe0'; // too short - $this->assertFalse(Validator::isAnyUUID($UUID)); - $UUID = 'f025c1c7-f55a-4ea0-b8d9-3f47d17dfe0ff'; // too long - $this->assertFalse(Validator::isAnyUUID($UUID)); + function testUUID() { + $this->assertTrue(Validator::isAnyUUID('f025c1c7-f55a-4ea0-b8d9-3f47d17dfe0f')); // dashes + $this->assertTrue(Validator::isAnyUUID('f025c1c7f55a4ea0b8d93f47d17dfe0f')); // no dashes + + $this->assertFalse(Validator::isAnyUUID('f025c1c7f55a9ea0b8d93f47d17dfe0f')); // bad version + $this->assertFalse(Validator::isAnyUUID('f025c1c7f55a4ea0b8d93f47d17dfe0g')); // bad last character + $this->assertFalse(Validator::isAnyUUID('f025c1c7f55a4ea0b8d93f47d17dfe0')); // too short + $this->assertFalse(Validator::isAnyUUID('f025c1c7-f55a-4ea0-b8d9-3f47d17dfe0ff')); // too long } - function testUsernameMatcher() { - $name = 'Plancke'; - $this->assertTrue(Validator::isUsername($name)); - $name = 'Plancke-R'; // dash - $this->assertFalse(Validator::isUsername($name)); - $name = 'Plancke_R'; // underscore - $this->assertTrue(Validator::isUsername($name)); - $name = 'G'; // 1 letter og - $this->assertTrue(Validator::isUsername($name)); - $name = 'hello world'; // spaces - $this->assertFalse(Validator::isUsername($name)); + function testUsername() { + $this->assertTrue(Validator::isUsername('Plancke')); + $this->assertTrue(Validator::isUsername('Plancke_R')); // underscore + $this->assertTrue(Validator::isUsername('G')); // 1 letter og + + $this->assertFalse(Validator::isUsername('Plancke-R'));// dash + $this->assertFalse(Validator::isUsername('hello world')); // spaces + } + + /** + * @depends testUUID + */ + function testAPIKey() { + // any uuid will do but just double checking separately in case anything changes down the line + $this->assertTrue(Validator::isValidAPIKey('f025c1c7-f55a-4ea0-b8d9-3f47d17dfe0f')); + $this->assertTrue(Validator::isValidAPIKey('f025c1c7f55a4ea0b8d93f47d17dfe0f')); + + $this->assertFalse(Validator::isValidAPIKey('Plancke')); } } \ No newline at end of file diff --git a/tests/util/CustomLogger.php b/tests/util/CustomLogger.php deleted file mode 100644 index f2a50f6..0000000 --- a/tests/util/CustomLogger.php +++ /dev/null @@ -1,18 +0,0 @@ -setLogger(new CustomLogger($HypixelPHP)); + $HypixelPHP->setLogger(new SysLogger($HypixelPHP)); $HypixelPHP->setCacheHandler(new NoCacheHandler($HypixelPHP)); $fetcher = new DefaultFetcher($HypixelPHP);