0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【PHP】GitHubのスターカウンターを作ってみた

Posted at

GitHub Star Counter

image.png

使い方

https://github-pitan76-star-counter.glitch.me/?user=(ユーザー名or組織名)&w=(横幅)

使用例

https://github-pitan76-star-counter.glitch.me/?user=PTOM76&w=320
PTOM76 Stars

ソースコード

GitHub API

GitHubから提供されているREST APIを用いてリポジトリの一覧のjsonを取得できる。
リポジトリの一覧にあるリポジトリにはstargazers_countというデータが含まれており、それを用いることでスター数を取得できる。

  • パラメータ
    • page - ページ番号
    • per_page - ページあたりの結果数
    • sort - 順番
https://api.github.com/users/(ユーザー名or組織名)/repos?page=1&per_page=100&sort=updated

スターカウント用の関数

つくったコードから抜粋してきました。
GitHub APIを用いてユーザー/組織のスター数の合計を取得します。(ただし、更新された順に100リポジトリまで)

function getTotalStars($username) {
    $url = "https://api.github.com/users/$username/repos?page=1&per_page=100&sort=updated";

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['User-Agent: PHP']);
    $res = curl_exec($ch);
    curl_close($ch);

    $repos = json_decode($res, true);

    if (isset($repos['status']) && $repos['status'] == "404")
        return 404;
  
    $stars = 0;
    foreach ($repos as $repo) {
        $stars += $repo['stargazers_count'];
    }

    return $stars;
}

GdImageからBase64形式への関数

GdImageをbase64に変換する関数です
ob_start、ob_get_contents、ob_end_cleanを使えばそのまま出力せずにバッファとして変数に保存できます。

function base64_image($image) {
    ob_start(); // 出力のバッファリング開始
    imagepng($image); // 画像を出力
    $raw = ob_get_contents(); // 出力されたバッファを変数に代入
    ob_end_clean(); // 出力のバッファリングを終了
    
    return 'data:image/png;base64,' . base64_encode($raw);
}

最後に

つくったスターカウンターは100リポジトリまでしか処理しないので、完全なものを作りたい場合はpageを使う必要がありそう。(個人用につくったものなのでそこらへんは考慮してませんでしたが)

glitch.comで動かしているのですが、いつかGitHub Actionsだけでカウンターを動かしている人も見かけたことがあるのでやってみたいですね

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?