Completed
Push — master ( 80bd76...26106c )
by Sam
03:54
created

ProjectRepository::getProject()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 10
nc 2
nop 2
1
<?php
2
/**
3
 * This file contains only the ProjectRepository class.
4
 */
5
6
namespace Xtools;
7
8
use Mediawiki\Api\MediawikiApi;
9
use Mediawiki\Api\SimpleRequest;
10
use Psr\Container\ContainerInterface;
11
12
/**
13
 * This class provides data to the Project class.
14
 */
15
class ProjectRepository extends Repository
16
{
17
18
    /** @var array Project metadata. */
19
    protected $metadata;
20
21
    /** @var string[] Metadata if XTools is in single-wiki mode. */
22
    protected $singleMetadata;
23
24
    /** @var string The cache key for the 'all project' metadata.
25
     */
26
    protected $cacheKeyAllProjects = 'allprojects';
27
28
    /**
29
     * Convenience method to get a new Project object based on a given identification string.
30
     * @param string $projectIdent The domain name, database name, or URL of a project.
31
     * @param ContainerInterface $container Symfony's container.
32
     * @return Project
33
     */
34
    public static function getProject($projectIdent, ContainerInterface $container)
35
    {
36
        $project = new Project($projectIdent);
37
        $projectRepo = new ProjectRepository();
38
        $projectRepo->setContainer($container);
0 ignored issues
show
Compatibility introduced by
$container of type object<Psr\Container\ContainerInterface> is not a sub-type of object<Symfony\Component...ncyInjection\Container>. It seems like you assume a concrete implementation of the interface Psr\Container\ContainerInterface to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
39
        if ($container->getParameter('app.single_wiki')) {
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Psr\Container\ContainerInterface as the method getParameter() does only exist in the following implementations of said interface: Container14\ProjectServiceContainer, LazyServiceProjectServiceContainer, ProjectServiceContainer, Symfony\Component\DependencyInjection\Container, Symfony\Component\Depend...ection\ContainerBuilder, Symfony\Component\Depend...tainers\CustomContainer, Symfony\Component\Depend...ProjectServiceContainer, Symfony\Component\Depend...ProjectServiceContainer.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
40
            $projectRepo->setSingleMetadata([
41
                'url' => $container->getParameter('wiki_url'),
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Psr\Container\ContainerInterface as the method getParameter() does only exist in the following implementations of said interface: Container14\ProjectServiceContainer, LazyServiceProjectServiceContainer, ProjectServiceContainer, Symfony\Component\DependencyInjection\Container, Symfony\Component\Depend...ection\ContainerBuilder, Symfony\Component\Depend...tainers\CustomContainer, Symfony\Component\Depend...ProjectServiceContainer, Symfony\Component\Depend...ProjectServiceContainer.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
42
                'dbname' => $container->getParameter('database_replica_name'),
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Psr\Container\ContainerInterface as the method getParameter() does only exist in the following implementations of said interface: Container14\ProjectServiceContainer, LazyServiceProjectServiceContainer, ProjectServiceContainer, Symfony\Component\DependencyInjection\Container, Symfony\Component\Depend...ection\ContainerBuilder, Symfony\Component\Depend...tainers\CustomContainer, Symfony\Component\Depend...ProjectServiceContainer, Symfony\Component\Depend...ProjectServiceContainer.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
43
            ]);
44
        }
45
        $project->setRepository($projectRepo);
46
        return $project;
47
    }
48
49
    /**
50
     * Get the XTools default project.
51
     * @param ContainerInterface $container
52
     * @return Project
53
     */
54
    public static function getDefaultProject(ContainerInterface $container)
55
    {
56
        $defaultProjectName = $container->getParameter('default_project');
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Psr\Container\ContainerInterface as the method getParameter() does only exist in the following implementations of said interface: Container14\ProjectServiceContainer, LazyServiceProjectServiceContainer, ProjectServiceContainer, Symfony\Component\DependencyInjection\Container, Symfony\Component\Depend...ection\ContainerBuilder, Symfony\Component\Depend...tainers\CustomContainer, Symfony\Component\Depend...ProjectServiceContainer, Symfony\Component\Depend...ProjectServiceContainer.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
57
        return self::getProject($defaultProjectName, $container);
58
    }
59
60
    /**
61
     * Get the global 'meta' project, which is either Meta (if this is Labs) or the default project.
62
     * @return Project
63
     */
64
    public function getGlobalProject()
65
    {
66
        if ($this->isLabs()) {
67
            return self::getProject('metawiki', $this->container);
68
        } else {
69
            return self::getDefaultProject($this->container);
70
        }
71
    }
72
73
    /**
74
     * For single-wiki installations, you must manually set the wiki URL and database name
75
     * (because there's no meta.wiki database to query).
76
     * @param $metadata
77
     * @throws \Exception
78
     */
79
    public function setSingleMetadata($metadata)
80
    {
81
        if (!array_key_exists('url', $metadata) || !array_key_exists('dbname', $metadata)) {
82
            $error = "Single-wiki metadata should contain 'url' and 'dbname' keys.";
83
            throw new \Exception($error);
84
        }
85
        $this->singleMetadata = array_intersect_key($metadata, ['url' => '', 'dbname' => '']);
86
    }
87
88
    /**
89
     * Get metadata about all projects.
90
     * @return string[] Each item has 'dbname' and 'url' keys.
91
     */
92
    public function getAll()
93
    {
94
        $this->log->debug(__METHOD__." Getting all projects' metadata");
95
        // Single wiki mode?
96
        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...
97
            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...
98
        }
99
100
        // Maybe we've already fetched it.
101
        if ($this->cache->hasItem($this->cacheKeyAllProjects)) {
102
            return $this->cache->getItem($this->cacheKeyAllProjects)->get();
103
        }
104
105
        // Otherwise, fetch all from the database.
106
        $wikiQuery = $this->getMetaConnection()->createQueryBuilder();
107
        $wikiQuery->select(['dbname', 'url'])->from('wiki');
108
        $projects = $wikiQuery->execute()->fetchAll();
109
        $projectsMetadata = [];
110
        foreach ($projects as $project) {
111
            $projectsMetadata[$project['dbname']] = $project;
112
        }
113
114
        // Cache and return.
115
        $cacheItem = $this->cache->getItem($this->cacheKeyAllProjects);
116
        $cacheItem->set($projectsMetadata);
117
        $cacheItem->expiresAfter(new \DateInterval('P1D'));
118
        $this->cache->save($cacheItem);
119
        return $projectsMetadata;
120
    }
121
122
    /**
123
     * Get metadata about one project.
124
     * @param string $project A project URL, domain name, or database name.
125
     * @return string[] With 'dbname' and 'url' keys.
126
     */
127
    public function getOne($project)
128
    {
129
        $this->log->debug(__METHOD__." Getting metadata about $project");
130
        // For single-wiki setups, every project is the same.
131
        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...
132
            return $this->singleMetadata;
133
        }
134
135
        // For muli-wiki setups, first check the cache.
136
        // First the all-projects cache, then the individual one.
137
        if ($this->cache->hasItem($this->cacheKeyAllProjects)) {
138
            foreach ($this->cache->getItem($this->cacheKeyAllProjects)->get() as $projMetadata) {
139
                if ($projMetadata['dbname'] == "$project"
140
                    || $projMetadata['url'] == "$project"
141
                    || $projMetadata['url'] == "https://$project") {
142
                    $this->log->debug(__METHOD__ . " Using cached data for $project");
143
                    return $projMetadata;
144
                }
145
            }
146
        }
147
        $cacheKey = "project.$project";
148
        if ($this->cache->hasItem($cacheKey)) {
149
            return $this->cache->getItem($cacheKey)->get();
150
        }
151
152
        // Otherwise, fetch the project's metadata from the meta.wiki table.
153
        $wikiQuery = $this->getMetaConnection()->createQueryBuilder();
154
        $wikiQuery->select(['dbname', 'url'])
155
            ->from('wiki')
156
            ->where($wikiQuery->expr()->eq('dbname', ':project'))
157
            // The meta database will have the project's URL stored as https://en.wikipedia.org
158
            // so we need to query for it accordingly, trying different variations the user
159
            // might have inputted.
160
            ->orwhere($wikiQuery->expr()->like('url', ':projectUrl'))
161
            ->orwhere($wikiQuery->expr()
162
                ->like('url', ':projectUrl2'))
163
            ->setParameter('project', $project)
164
            ->setParameter('projectUrl', "https://$project")
165
            ->setParameter('projectUrl2', "https://$project.org");
166
        $wikiStatement = $wikiQuery->execute();
167
168
        // Fetch and cache the wiki data.
169
        $projectMetadata = $wikiStatement->fetch();
170
        $cacheItem = $this->cache->getItem($cacheKey);
171
        $cacheItem->set($projectMetadata)
172
            ->expiresAfter(new \DateInterval('PT1H'));
173
        $this->cache->save($cacheItem);
174
175
        return $projectMetadata;
176
    }
177
178
    /**
179
     * Get metadata about a project.
180
     *
181
     * @param string $projectUrl The project's URL.
182
     * @return array With 'general' and 'namespaces' keys: the former contains 'wikiName',
183
     * 'wikiId', 'url', 'lang', 'articlePath', 'scriptPath', 'script', 'timezone', and
184
     * 'timezoneOffset'; the latter contains all namespace names, keyed by their IDs.
185
     */
186
    public function getMetadata($projectUrl)
187
    {
188
        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...
189
            return $this->metadata;
190
        }
191
192
        $api = MediawikiApi::newFromPage($projectUrl);
193
194
        $params = ['meta' => 'siteinfo', 'siprop' => 'general|namespaces'];
195
        $query = new SimpleRequest('query', $params);
196
197
        $this->metadata = [
198
            'general' => [],
199
            'namespaces' => [],
200
        ];
201
202
        $res = $api->getRequest($query);
203
204
        if (isset($res['query']['general'])) {
205
            $info = $res['query']['general'];
206
            $this->metadata['general'] = [
207
                'wikiName' => $info['sitename'],
208
                'wikiId' => $info['wikiid'],
209
                'url' => $info['server'],
210
                'lang' => $info['lang'],
211
                'articlePath' => $info['articlepath'],
212
                'scriptPath' => $info['scriptpath'],
213
                'script' => $info['script'],
214
                'timezone' => $info['timezone'],
215
                'timeOffset' => $info['timeoffset'],
216
            ];
217
218
//            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...
219
//                substr($result['general']['dbName'], -2) != '_p'
220
//            ) {
221
//                $result['general']['dbName'] .= '_p';
222
//            }
223
        }
224
225 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...
226
            foreach ($res['query']['namespaces'] as $namespace) {
227
                if ($namespace['id'] < 0) {
228
                    continue;
229
                }
230
231
                if (isset($namespace['name'])) {
232
                    $name = $namespace['name'];
233
                } elseif (isset($namespace['*'])) {
234
                    $name = $namespace['*'];
235
                } else {
236
                    continue;
237
                }
238
239
                // FIXME: Figure out a way to i18n-ize this
240
                if ($name === '') {
241
                    $name = 'Article';
242
                }
243
244
                $this->metadata['namespaces'][$namespace['id']] = $name;
245
            }
246
        }
247
248
        return $this->metadata;
249
    }
250
251
    /**
252
     * Get a list of projects that have opted in to having all their users' restricted statistics
253
     * available to anyone.
254
     *
255
     * @return string[]
256
     */
257
    public function optedIn()
258
    {
259
        $optedIn = $this->container->getParameter('opted_in');
260
        return $optedIn;
261
    }
262
263
    /**
264
     * The path to api.php
265
     *
266
     * @return string
267
     */
268
    public function getApiPath()
269
    {
270
        return $this->container->getParameter('api_path');
271
    }
272
273
    /**
274
     * Get a page from the given Project.
275
     * @param Project $project The project.
276
     * @param string $pageName The name of the page.
277
     * @return Page
278
     */
279
    public function getPage(Project $project, $pageName)
280
    {
281
        $pageRepo = new PagesRepository();
282
        $pageRepo->setContainer($this->container);
283
        $page = new Page($project, $pageName);
284
        $page->setRepository($pageRepo);
285
        return $page;
286
    }
287
288
    /**
289
     * Check to see if a page exists on this project and has some content.
290
     * @param Project $project The project.
291
     * @param int $namespaceId The page namespace ID.
292
     * @param string $pageTitle The page title, without namespace.
293
     * @return bool
294
     */
295
    public function pageHasContent(Project $project, $namespaceId, $pageTitle)
296
    {
297
        $conn = $this->getProjectsConnection();
298
        $pageTable = $this->getTableName($project->getDatabaseName(), 'page');
299
        $query = "SELECT page_id "
300
             . " FROM $pageTable "
301
             . " WHERE page_namespace = :ns AND page_title = :title AND page_len > 0 "
302
             . " LIMIT 1";
303
        $params = [
304
            'ns' => $namespaceId,
305
            'title' => $pageTitle,
306
        ];
307
        $pages = $conn->executeQuery($query, $params)->fetchAll();
308
        return count($pages) > 0;
309
    }
310
}
311