accounts/common/components/Mojang/Api.php

55 lines
1.6 KiB
PHP
Raw Normal View History

<?php
namespace common\components\Mojang;
use common\components\Mojang\exceptions\MojangApiException;
use common\components\Mojang\exceptions\NoContentException;
use common\components\Mojang\response\UsernameToUUIDResponse;
use Yii;
class Api {
/**
* @param string $username
* @param int $atTime
*
* @return UsernameToUUIDResponse
* @throws MojangApiException
* @throws NoContentException|\GuzzleHttp\Exception\RequestException
* @url http://wiki.vg/Mojang_API#Username_-.3E_UUID_at_time
*/
public function usernameToUUID($username, $atTime = null) {
2016-07-21 21:42:55 +05:30
$query = [];
if ($atTime !== null) {
2016-07-21 21:42:55 +05:30
$query['atTime'] = $atTime;
}
$response = $this->getClient()->get($this->buildUsernameToUUIDRoute($username), $query);
if ($response->getStatusCode() === 204) {
throw new NoContentException('Username not found');
} elseif ($response->getStatusCode() !== 200) {
throw new MojangApiException('Unexpected request result');
}
2016-07-21 21:42:55 +05:30
$data = json_decode($response->getBody(), true);
$responseObj = new UsernameToUUIDResponse();
$responseObj->id = $data['id'];
$responseObj->name = $data['name'];
$responseObj->legacy = isset($data['legacy']);
$responseObj->demo = isset($data['demo']);
return $responseObj;
}
/**
* @return \GuzzleHttp\Client
*/
protected function getClient() {
return Yii::$app->guzzle;
}
2016-07-21 21:42:55 +05:30
protected function buildUsernameToUUIDRoute($username) {
return 'https://api.mojang.com/users/profiles/minecraft/' . $username;
}
}