2018-07-08 20:50:19 +05:30
|
|
|
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
|
|
|
|
namespace common\tasks;
|
|
|
|
|
|
|
|
use api\exceptions\ThisShouldNotHappenException;
|
|
|
|
use common\models\Account;
|
|
|
|
use common\models\MojangUsername;
|
2019-05-09 06:53:49 +05:30
|
|
|
use Ely\Mojang\Api as MojangApi;
|
|
|
|
use Ely\Mojang\Exception\MojangApiException;
|
|
|
|
use Ely\Mojang\Exception\NoContentException;
|
|
|
|
use GuzzleHttp\Exception\GuzzleException;
|
2018-07-08 20:50:19 +05:30
|
|
|
use Yii;
|
|
|
|
use yii\queue\JobInterface;
|
|
|
|
|
|
|
|
class PullMojangUsername implements JobInterface {
|
|
|
|
|
|
|
|
public $username;
|
|
|
|
|
|
|
|
public static function createFromAccount(Account $account): self {
|
|
|
|
$result = new static();
|
|
|
|
$result->username = $account->username;
|
|
|
|
|
|
|
|
return $result;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param \yii\queue\Queue $queue which pushed and is handling the job
|
|
|
|
*
|
|
|
|
* @throws \Exception
|
|
|
|
*/
|
|
|
|
public function execute($queue) {
|
|
|
|
Yii::$app->statsd->inc('queue.pullMojangUsername.attempt');
|
2019-05-09 06:53:49 +05:30
|
|
|
/** @var MojangApi $mojangApi */
|
|
|
|
$mojangApi = Yii::$app->get(MojangApi::class);
|
2018-07-08 20:50:19 +05:30
|
|
|
try {
|
|
|
|
$response = $mojangApi->usernameToUUID($this->username);
|
|
|
|
Yii::$app->statsd->inc('queue.pullMojangUsername.found');
|
|
|
|
} catch (NoContentException $e) {
|
|
|
|
$response = false;
|
|
|
|
Yii::$app->statsd->inc('queue.pullMojangUsername.not_found');
|
2019-05-09 06:53:49 +05:30
|
|
|
} catch (GuzzleException | MojangApiException $e) {
|
2018-07-08 20:50:19 +05:30
|
|
|
Yii::$app->statsd->inc('queue.pullMojangUsername.error');
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
/** @var MojangUsername|null $mojangUsername */
|
|
|
|
$mojangUsername = MojangUsername::findOne($this->username);
|
|
|
|
if ($response === false) {
|
|
|
|
if ($mojangUsername !== null) {
|
|
|
|
$mojangUsername->delete();
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
if ($mojangUsername === null) {
|
|
|
|
$mojangUsername = new MojangUsername();
|
2019-05-09 06:53:49 +05:30
|
|
|
$mojangUsername->username = $response->getName();
|
|
|
|
$mojangUsername->uuid = $response->getId();
|
2018-07-08 20:50:19 +05:30
|
|
|
} else {
|
2019-05-09 06:53:49 +05:30
|
|
|
$mojangUsername->uuid = $response->getId();
|
2018-07-08 20:50:19 +05:30
|
|
|
$mojangUsername->touch('last_pulled_at');
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!$mojangUsername->save()) {
|
|
|
|
throw new ThisShouldNotHappenException('Cannot save mojang username');
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|