Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update OsuAPI.php #2

Merged
merged 1 commit into from
Oct 9, 2015
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 54 additions & 28 deletions class/OsuAPI.php
Original file line number Diff line number Diff line change
@@ -1,49 +1,75 @@
<?php
// Thanks to Cygnix
// Created by Lemmmy

/**
* @author Lemmy
*/
class OsuAPI
{
const API_URL = "https://osu.ppy.sh/api/";

private $modes = ["osu", "taiko", "ctb", "mania"];
/**
* Each mode of osu! that we want to use
*
* @var array
*/
protected static $modes = ["osu", "taiko", "ctb", "mania"];

/**
* Your private osu!API key
*
* @var string
*/
private $apiKey;

/**
* Creates a new instance of OsuAPI
*
* @param string $apiKey [Your private osu!API key]
* @param string $apiKey Your private osu!API key
*/
public function __construct($apiKey) {
$this->apiKey = $apiKey;
}

/**
* Gets user information for a specific game mode
*
* @param string $username [The player's username]
* @param [string] $mode [The game mode]
* $return array | false
* @param string $username The player's username
* @param string $mode The game mode
* @return array|bool
*/
public function getUserForMode($username, $mode = "osu") {
if (in_array($mode, $this->modes)) {
$query = [
"k" => $this->apiKey,
"u" => $username,
"m" => $mode,
];

$request = file_get_contents(self::API_URL . "get_user?" . http_build_query($query));

if ($request) {
$apiResult = json_decode($request);

if (isset($apiResult[0])) {
return $apiResult[0];
}
if (in_array($mode, static::$modes)) {
$request = $this->request('get_user', ['u' => $username, 'm' => $mode]);
if ($request && isset($result[0])) {
return $result[0];
}

return false;
}
}
}

/**
* Request from the osu!API
*
* @param string $url The resource to fetch
* @param array $params A list of arguments to give for the resource
*/
public function request($url, $params = [])
{
$params = array_merge(["k" => $this->apiKey], $params);
$url = static::API_URL . $url . '?' . http_build_query($params);

return $this->decode(file_get_contents($url));
}

/**
* Decode a response from the API
*
* @param string $content The response from the API
* @return array|null The decoded JSON object, or null.
*/
protected function decode($content)
{
// todo: error handling here
if (strlen($content) > 0 && $content) {
return json_decode($content, true);
}

return null;
}
}