Passed
Push — master ( 16bc58...e2c4be )
by MusikAnimal
05:53
created

AuthorshipRepository::getData()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 30
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 16
nc 5
nop 2
dl 0
loc 30
rs 9.7333
c 0
b 0
f 0
1
<?php
2
declare(strict_types = 1);
3
4
namespace AppBundle\Repository;
5
6
use AppBundle\Model\Page;
7
use AppBundle\Model\Project;
8
use GuzzleHttp;
9
10
/**
11
 * AuthorshipRepository is responsible for retrieving authorship data about a single page.
12
 * @codeCoverageIgnore
13
 */
14
class AuthorshipRepository extends Repository
15
{
16
    /**
17
     * Query the WikiWho service to get authorship percentages.
18
     * @see https://api.wikiwho.net/
19
     * @param Page $page
20
     * @param int|null $revId ID of revision to target, or null for latest revision.
21
     * @return array[]|null Response from WikiWho. null if something went wrong.
22
     */
23
    public function getData(Page $page, ?int $revId): ?array
24
    {
25
        $cacheKey = $this->getCacheKey(func_get_args(), 'page_authorship');
26
        if ($this->cache->hasItem($cacheKey)) {
27
            return $this->cache->getItem($cacheKey)->get();
28
        }
29
30
        $title = rawurlencode(str_replace(' ', '_', $page->getTitle()));
31
        $projectLang = $page->getProject()->getLang();
32
33
        $url = "https://api.wikiwho.net/$projectLang/api/v1.0.0-beta/rev_content/$title"
34
            .($revId ? "/$revId" : '')
35
            ."/?o_rev_id=false&editor=true&token_id=false&out=false&in=false";
36
37
        // Ignore HTTP errors to fail gracefully.
38
        $opts = ['http_errors' => false];
39
40
        // Use WikiWho API credentials, if present. They are not required.
41
        if ($this->container->hasParameter('app.wikiwho.username')) {
42
            $opts['auth'] = [
43
                $this->container->getParameter('app.wikiwho.username'),
44
                $this->container->getParameter('app.wikiwho.password'),
45
            ];
46
        }
47
48
        $client = new GuzzleHttp\Client();
49
        $res = $client->request('GET', $url, $opts);
50
51
        // Cache and return.
52
        return $this->setCache($cacheKey, json_decode($res->getBody()->getContents(), true));
53
    }
54
55
    /**
56
     * Get a map of user IDs/usernames given the user IDs.
57
     * @param Project $project
58
     * @param int[] $userIds
59
     * @return array
60
     */
61
    public function getUsernamesFromIds(Project $project, array $userIds): array
62
    {
63
        $userTable = $project->getTableName('user');
64
        $userIds = implode(',', array_unique(array_filter($userIds)));
65
        $sql = "SELECT user_id, user_name
66
                FROM $userTable
67
                WHERE user_id IN ($userIds)";
68
        return $this->executeProjectsQuery($sql)->fetchAll();
69
    }
70
}
71