Completed
Push — master ( e15cd8...6a18e3 )
by Sam
03:48
created

ProjectRepository::optedIn()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 0
1
<?php
2
3
namespace Xtools;
4
5
use Mediawiki\Api\MediawikiApi;
6
use Mediawiki\Api\SimpleRequest;
7
use Symfony\Component\DependencyInjection\Container;
8
9
class ProjectRepository extends Repository
10
{
11
12
    /** @var array Project metadata. */
13
    protected $metadata;
14
15
    /** @var string[] Metadata if XTools is in single-wiki mode. */
16
    protected $singleMetadata;
17
18
    /** @var string[][] Metadata of all projects, populated by self::getAll(). */
19
    protected $projectsMetadata;
20
21
    /**
22
     * Convenience method to get a new Project object based on a given identification string.
23
     * @param string $projectIdent The domain name, database name, or URL of a project.
24
     * @param Container $container Symfony's container.
25
     * @return Project
26
     */
27
    public static function getProject($projectIdent, Container $container)
28
    {
29
        $project = new Project($projectIdent);
30
        $projectRepo = new ProjectRepository();
31
        $projectRepo->setContainer($container);
32
        if ($container->getParameter('app.single_wiki')) {
33
            $projectRepo->setSingleMetadata([
34
                'url' => $container->getParameter('wiki_url'),
35
                'dbname' => $container->getParameter('database_replica_name'),
36
            ]);
37
        }
38
        $project->setRepository($projectRepo);
39
        return $project;
40
    }
41
42
    /**
43
     * Get the XTools default project.
44
     * @param Container $container
45
     * @return Project
46
     */
47
    public static function getDefaultProject(Container $container)
48
    {
49
        $defaultProjectName = $container->getParameter('default_project');
50
        return self::getProject($defaultProjectName, $container);
51
    }
52
53
    /**
54
     * For single-wiki installations, you must manually set the wiki URL and database name
55
     * (because there's no meta.wiki database to query).
56
     * @param $metadata
57
     * @throws \Exception
58
     */
59
    public function setSingleMetadata($metadata)
60
    {
61
        if (!array_key_exists('url', $metadata) || !array_key_exists('dbname', $metadata)) {
62
            $error = "Single-wiki metadata should contain 'url' and 'dbname' keys.";
63
            throw new \Exception($error);
64
        }
65
        $this->singleMetadata = array_intersect_key($metadata, ['url' => '', 'dbname' => '']);
66
    }
67
68
    /**
69
     * Get metadata about all projects.
70
     * @return string[] Each item has 'dbname' and 'url' keys.
71
     */
72
    public function getAll()
73
    {
74
        // Single wiki mode?
75
        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...
76
            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...
77
        }
78
        // Maybe we've already fetched it.
79
        if (is_array($this->projectsMetadata)) {
80
            return $this->projectsMetadata;
81
        }
82
        $wikiQuery = $this->getMetaConnection()->createQueryBuilder();
83
        $wikiQuery->select(['dbname', 'url'])->from('wiki');
84
        $projects = $wikiQuery->execute()->fetchAll();
85
        $this->projectsMetadata = [];
86
        foreach ($projects as $project) {
87
            $this->projectsMetadata[$project['url']] = $project;
88
            $this->projectsMetadata[$project['dbname']] = $project;
89
        }
90
        return $this->projectsMetadata;
91
    }
92
93
    /**
94
     * Get metadata about one project.
95
     * @param string $project A project URL, domain name, or database name.
96
     * @return string[] With 'dbname' and 'url' keys.
97
     */
98
    public function getOne($project)
99
    {
100
        // For single-wiki setups, every project is the same.
101
        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...
102
            return $this->singleMetadata;
103
        }
104
105
        // Maybe we've already fetched it (if we're requesting via a domain).
106
        if (isset($this->projectsMetadata[$project])) {
107
            return $this->projectsMetadata[$project];
108
        }
109
        if (isset($this->projectsMetadata['https://'.$project])) {
110
            return $this->projectsMetadata['https://'.$project];
111
        }
112
113
        // For muli-wiki setups, first check the cache.
114
        $cacheKey = "project.$project";
115
        if ($this->cache->hasItem($cacheKey)) {
116
            return $this->cache->getItem($cacheKey)->get();
117
        }
118
119
        // Otherwise, fetch the project's metadata from the meta.wiki table.
120
        $wikiQuery = $this->getMetaConnection()->createQueryBuilder();
121
        $wikiQuery->select(['dbname', 'url'])
122
            ->from('wiki')
123
            ->where($wikiQuery->expr()->eq('dbname', ':project'))
124
            // The meta database will have the project's URL stored as https://en.wikipedia.org
125
            // so we need to query for it accordingly, trying different variations the user
126
            // might have inputted.
127
            ->orwhere($wikiQuery->expr()->like('url', ':projectUrl'))
128
            ->orwhere($wikiQuery->expr()
129
                ->like('url', ':projectUrl2'))
130
            ->setParameter('project', $project)
131
            ->setParameter('projectUrl', "https://$project")
132
            ->setParameter('projectUrl2', "https://$project.org");
133
        $wikiStatement = $wikiQuery->execute();
134
135
        // Fetch and cache the wiki data.
136
        $projectMetadata = $wikiStatement->fetch();
137
        $cacheItem = $this->cache->getItem($cacheKey);
138
        $cacheItem->set($projectMetadata)
139
            ->expiresAfter(new \DateInterval('PT1H'));
140
        $this->cache->save($cacheItem);
141
142
        return $projectMetadata;
143
    }
144
145
    /**
146
     * Get metadata about a project.
147
     *
148
     * @param string $projectUrl The project's URL.
149
     * @return array With 'general' and 'namespaces' keys: the former contains 'wikiName',
150
     * 'wikiId', 'url', 'lang', 'articlePath', 'scriptPath', 'script', 'timezone', and
151
     * 'timezoneOffset'; the latter contains all namespace names, keyed by their IDs.
152
     */
153
    public function getMetadata($projectUrl)
154
    {
155
        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...
156
            return $this->metadata;
157
        }
158
        
159
        $api = MediawikiApi::newFromPage($projectUrl);
160
161
        $params = ['meta' => 'siteinfo', 'siprop' => 'general|namespaces'];
162
        $query = new SimpleRequest('query', $params);
163
164
        $this->metadata = [
165
            'general' => [],
166
            'namespaces' => [],
167
        ];
168
169
        $res = $api->getRequest($query);
170
171
        if (isset($res['query']['general'])) {
172
            $info = $res['query']['general'];
173
            $this->metadata['general'] = [
174
                'wikiName' => $info['sitename'],
175
                'wikiId' => $info['wikiid'],
176
                'url' => $info['server'],
177
                'lang' => $info['lang'],
178
                'articlePath' => $info['articlepath'],
179
                'scriptPath' => $info['scriptpath'],
180
                'script' => $info['script'],
181
                'timezone' => $info['timezone'],
182
                'timeOffset' => $info['timeoffset'],
183
            ];
184
185
//            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...
186
//                substr($result['general']['dbName'], -2) != '_p'
187
//            ) {
188
//                $result['general']['dbName'] .= '_p';
189
//            }
190
        }
191
192 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...
193
            foreach ($res['query']['namespaces'] as $namespace) {
194
                if ($namespace['id'] < 0) {
195
                    continue;
196
                }
197
198
                if (isset($namespace['name'])) {
199
                    $name = $namespace['name'];
200
                } elseif (isset($namespace['*'])) {
201
                    $name = $namespace['*'];
202
                } else {
203
                    continue;
204
                }
205
206
                // FIXME: Figure out a way to i18n-ize this
207
                if ($name === '') {
208
                    $name = 'Article';
209
                }
210
211
                $this->metadata['namespaces'][$namespace['id']] = $name;
212
            }
213
        }
214
215
        return $this->metadata;
216
    }
217
218
    /**
219
     * Get a list of projects that have opted in to having all their users' restricted statistics
220
     * available to anyone.
221
     *
222
     * @return string[]
223
     */
224
    public function optedIn()
225
    {
226
        $optedIn = $this->container->getParameter('opted_in');
227
        return $optedIn;
228
    }
229
230
    /**
231
     * Check to see if a page exists on this project.
232
     * @param $pageTitle
233
     * @return bool
234
     */
235
    public function pageExists(Project $project, $pageTitle)
236
    {
237
        $conn = $this->getProjectsConnection();
238
        $pageTable = $this->getTableName($project->getDatabaseName(), 'page');
239
        $query = "SELECT page_id FROM $pageTable WHERE page_title = :title LIMIT 1";
240
        $pages = $conn->executeQuery($query, ['title'=>$pageTitle])->fetchAll();
241
        return count($pages) > 0;
242
    }
243
}
244