Completed
Push — master ( fcf66f...4020b1 )
by Sam
02:59
created

ProjectRepository::getOne()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 26
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 26
rs 8.8571
cc 2
eloc 15
nc 2
nop 1
1
<?php
2
3
namespace Xtools;
4
5
use Mediawiki\Api\MediawikiApi;
6
use Mediawiki\Api\SimpleRequest;
7
8
class ProjectRepository extends Repository
9
{
10
11
    /** @var array Project metadata. */
12
    protected $metadata;
13
14
    /** @var string[] */
15
    protected $singleMetadata;
16
17
    /**
18
     * For single-wiki installations, you must manually set the wiki URL and database name
19
     * (because there's no meta.wiki database to query).
20
     * @param $metadata
21
     * @throws \Exception
22
     */
23
    public function setSingleMetadata($metadata)
24
    {
25
        if (!array_key_exists('url', $metadata) || !array_key_exists('dbname', $metadata)) {
26
            $error = "Single-wiki metadata should contain 'url' and 'dbname' keys.";
27
            throw new \Exception($error);
28
        }
29
        $this->singleMetadata = array_intersect_key($metadata, ['url' => '', 'dbname' => '']);
30
    }
31
32
    /**
33
     * Get metadata about all projects.
34
     * @return string[] Each item has 'dbname' and 'url' keys.
35
     */
36
    public function getAll()
37
    {
38
        if ($this->singleMetadata) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->singleMetadata of type string[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
39
            return [$this->getOne('')];
0 ignored issues
show
Bug Best Practice introduced by
The return type of return array($this->getOne('')); (string[][]) is incompatible with the return type documented by Xtools\ProjectRepository::getAll of type string[].

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
40
        }
41
        $wikiQuery = $this->metaConnection->createQueryBuilder();
42
        $wikiQuery->select(['dbname', 'url'])->from('wiki');
43
        return $wikiQuery->execute()->fetchAll();
44
    }
45
46
    /**
47
     * Get metadata about one project.
48
     * @param string $project A project URL, domain name, or database name.
49
     * @return string[] With 'dbname' and 'url' keys.
50
     */
51
    public function getOne($project)
52
    {
53
        // For single-wiki setups, every project is the same.
54
        if ($this->singleMetadata) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->singleMetadata of type string[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
55
            return $this->singleMetadata;
56
        }
57
58
        // Otherwise, fetch the project's metadata from the meta.wiki table.
59
        $wikiQuery = $this->metaConnection->createQueryBuilder();
60
        $wikiQuery->select(['dbname', 'url'])
61
            ->from('wiki')
62
            ->where($wikiQuery->expr()->eq('dbname', ':project'))
63
            // The meta database will have the project's URL stored as https://en.wikipedia.org
64
            // so we need to query for it accordingly, trying different variations the user
65
            // might have inputted.
66
            ->orwhere($wikiQuery->expr()->like('url', ':projectUrl'))
67
            ->orwhere($wikiQuery->expr()
68
                ->like('url', ':projectUrl2'))
69
            ->setParameter('project', $project)
70
            ->setParameter('projectUrl', "https://$project")
71
            ->setParameter('projectUrl2', "https://$project.org");
72
        $wikiStatement = $wikiQuery->execute();
73
74
        // Fetch the wiki data.
75
        return $wikiStatement->fetch();
76
    }
77
78
    /**
79
     * Get metadata about a project.
80
     *
81
     * @param string $projectUrl The project's URL.
82
     * @return array With 'general' and 'namespaces' keys: the former contains 'wikiName',
83
     * 'wikiId', 'url', 'lang', 'articlePath', 'scriptPath', 'script', 'timezone', and
84
     * 'timezoneOffset'; the latter contains all namespace names, keyed by their IDs.
85
     */
86
    public function getMetadata($projectUrl)
87
    {
88
        if ($this->metadata) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->metadata of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
89
            return $this->metadata;
90
        }
91
        
92
        $api = MediawikiApi::newFromPage($projectUrl);
93
94
        $params = ['meta' => 'siteinfo', 'siprop' => 'general|namespaces'];
95
        $query = new SimpleRequest('query', $params);
96
97
        $this->metadata = [
98
            'general' => [],
99
            'namespaces' => [],
100
        ];
101
102
        $res = $api->getRequest($query);
103
104
        if (isset($res['query']['general'])) {
105
            $info = $res['query']['general'];
106
            $this->metadata['general'] = [
107
                'wikiName' => $info['sitename'],
108
                'wikiId' => $info['wikiid'],
109
                'url' => $info['server'],
110
                'lang' => $info['lang'],
111
                'articlePath' => $info['articlepath'],
112
                'scriptPath' => $info['scriptpath'],
113
                'script' => $info['script'],
114
                'timezone' => $info['timezone'],
115
                'timeOffset' => $info['timeoffset'],
116
            ];
117
118
//            if ($this->container->getParameter('app.is_labs') &&
1 ignored issue
show
Unused Code Comprehensibility introduced by
59% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
119
//                substr($result['general']['dbName'], -2) != '_p'
120
//            ) {
121
//                $result['general']['dbName'] .= '_p';
122
//            }
123
        }
124
125 View Code Duplication
        if (isset($res['query']['namespaces'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
126
            foreach ($res['query']['namespaces'] as $namespace) {
127
                if ($namespace['id'] < 0) {
128
                    continue;
129
                }
130
131
                if (isset($namespace['name'])) {
132
                    $name = $namespace['name'];
133
                } elseif (isset($namespace['*'])) {
134
                    $name = $namespace['*'];
135
                } else {
136
                    continue;
137
                }
138
139
                // FIXME: Figure out a way to i18n-ize this
140
                if ($name === '') {
141
                    $name = 'Article';
142
                }
143
144
                $this->metadata['namespaces'][$namespace['id']] = $name;
145
            }
146
        }
147
148
        return $this->metadata;
149
    }
150
}
151