|
- <?php
-
- namespace App\Knockout;
-
- use Illuminate\Support\Facades\Cache;
-
- class User {
-
- public $id;
- public $username;
- public $avatar;
- public $background;
- public $banned = false;
-
- public static function unwrap($user)
- {
- $s = new self();
-
- $s->id = $user->id;
- $s->username = $user->username;
- $s->avatar = sprintf("https://cdn.knockout.chat/image/%u.webp", $user->id);
- $s->background = sprintf("https://cdn.knockout.chat/image/%u-bg.webp", $user->id);
- $s->banned = $user->banned;
-
- return $s;
- }
-
- private static function requestAll(int $page = 0, string $query = ''): Dataset
- {
- $path = ['/users/'];
- if ($page > 0) $path[] = $page;
- $data = (new AbstractData)->httpGet(implode('', $path), ['filter' => $query]);
- $json = json_decode($data);
- $records = array_map(function($user) {
- return self::unwrap($user);
- }, $json->users);
- return (new Dataset($records))
- ->setTotalRecords($json->totalUsers)
- ->setCurrentPage($page)
- ->setRecordsPerPage(40);
- }
-
- public static function updateAll(int $page = 0, string $query = ''): Dataset
- {
- $key = sprintf('users-%u-%s', $page, $query);
- $data = self::requestAll($page, $query);
- Cache::put($key, $data, 3600);
- return $data;
- }
-
- public static function all(int $page = 0, string $query = ''): Dataset
- {
- $key = sprintf('users-%u-%s', $page, $query);
- return Cache::get($key, function() use($page, $query) {
- return self::updateAll($page, $query);
- });
- }
-
- private static function requestOne(int $userId): Dataset
- {
- $data = (new AbstractData)->httpGet(sprintf('/user/%s', $userId));
- $json = json_decode($data);
- $record = self::unwrap($json);
- return (new Dataset($record));
- }
-
- public static function updateOne(int $userId): Dataset
- {
- $key = sprintf('user-%u', $userId);
- $data = self::requestOne($userId);
- Cache::put($key, $data, 3600);
- return $data;
- }
-
- public static function one(int $userId): Dataset
- {
- $key = sprintf('user-%u', $userId);
- return Cache::get($key, function() use($userId) {
- return self::updateOne($userId);
- });
- }
-
- public function postInfoClasses() {
- $classes = [];
- $showAvatar = true;
- $showBackground = true;
-
- if ($this->banned) $classes[] = 'banned';
- $classes[] = $showAvatar ? 'show-avatar' : 'hide-avatar';
- $classes[] = $showBackground ? 'show-backgrounds' : 'hide-backgrounds';
-
- return implode(' ', $classes);
- }
-
- }
|