|
- <?php
-
- namespace App\Knockout;
-
- use App\Helper\BBCode;
- use Carbon\Carbon;
- use Illuminate\Support\Facades\Cache;
-
- class Post {
-
- // meta
- public $id;
- public $date;
- public $content;
-
- // related
- public User $user;
- public $ratings = [];
-
- public static function unwrap($post)
- {
- $s = new self();
-
- $s->id = $post->id;
- $s->date = Carbon::parse($post->createdAt)->format('d/m/Y H:i');
- $s->content = $post->content;
-
- // grab user if available
- if (isset($post->user) && isset($post->user->id)) {
- $s->user = User::unwrap($post->user);
- }
-
- // grab ratings if available
- $s->ratings = array_map(function($rating) {
- return Rating::unwrap($rating);
- }, $post->ratings ?? []);
-
- return $s;
- }
-
- private static function requestAll(int $userId, int $page = 1): Dataset
- {
- $data = (new AbstractData)->httpGet(sprintf('/user/%u/posts/%u', $userId, $page));
- $json = json_decode($data);
- $records = array_map(function($user) {
- return self::unwrap($user);
- }, $json->posts);
- return (new Dataset($records))
- ->setTotalRecords($json->totalPosts)
- ->setCurrentPage($page)
- ->setRecordsPerPage(40);
- }
-
- public static function updateAll(int $userId, int $page = 0): Dataset
- {
- $key = sprintf('user-posts-%u-%u', $userId, $page);
- $data = self::requestAll($userId, $page);
- Cache::put($key, $data, 300);
- return $data;
- }
-
- public static function all(int $userId, int $page = 0): Dataset
- {
- $key = sprintf('user-posts-%u-%u', $userId, $page);
- return Cache::get($key, function() use($userId, $page) {
- return self::updateAll($userId, $page);
- });
- }
-
- public function dateDiff()
- {
- return Carbon::createFromFormat('d/m/Y H:i', $this->date)->diffForHumans();
- }
-
- public function render()
- {
- return (new BBCode($this->content))->render();
- }
-
- }
|