GetLastWikiUserComments   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 23
c 1
b 0
f 0
dl 0
loc 39
rs 10
wmc 5

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A get() 0 28 4
1
<?php
2
3
4
namespace App\Src\UseCases\Domain\Context\Queries;
5
6
7
use App\Src\UseCases\Domain\Ports\UserRepository;
8
use App\Src\UseCases\Infra\Sql\Model\PageModel;
9
use GuzzleHttp\Client;
10
use Illuminate\Support\Facades\Cache;
11
use Illuminate\Support\Carbon;
12
13
class GetLastWikiUserComments
14
{
15
    private $httpClient;
16
    private $commentsEndPoint = '?action=query&list=usercomments&format=json&ucuserguids=';
17
18
    public function __construct(UserRepository $userRepository)
19
    {
20
        $this->httpClient = new Client();
21
        $this->userRepository = $userRepository;
0 ignored issues
show
Bug Best Practice introduced by
The property userRepository does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
22
    }
23
24
    public function get(string $userId)
25
    {
26
        $comments = Cache::get("comments_".$userId);
27
        if(isset($comments)){
28
            return json_decode($comments, true);
29
        }
30
31
        $response = $this->httpClient->get(config('wiki.api_uri').$this->commentsEndPoint.$userId);
32
        $content = json_decode($response->getBody()->getContents(), true);
33
        $comments = $content['query']['usercomments'];
34
35
        $commentsToRetrieved = [];
36
        foreach($comments as $comment){
37
            if(!isset($commentsToRetrieved[$comment['pageid']])) {
38
                $commentsToRetrieved[$comment['pageid']] = $comment;
39
40
                $realPageId = $comment['associatedid'];
41
                $page = PageModel::where('page_id', $realPageId)->first();
42
                $commentsToRetrieved[$comment['pageid']]['picture'] = $page['picture'];
43
                $commentsToRetrieved[$comment['pageid']]['real_page_id'] = $realPageId;
44
45
                $commentsToRetrieved[$comment['pageid']]['title'] = $comment['associated_page_title'];
46
                $commentsToRetrieved[$comment['pageid']]['date'] = (new Carbon($comment['timestamp']))->translatedFormat('l j F Y - h:i');
47
            }
48
        }
49
50
        Cache::put("comments_".$userId, json_encode($commentsToRetrieved), 86400);
51
        return $commentsToRetrieved;
52
    }
53
}
54