Passed
Push — master ( a61c57...8dbe0a )
by MusikAnimal
10:33
created

Page::getLang()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2.032

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 0
dl 0
loc 7
ccs 4
cts 5
cp 0.8
crap 2.032
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * This file contains only the Page class.
4
 */
5
6
declare(strict_types = 1);
7
8
namespace AppBundle\Model;
9
10
use DateTime;
11
12
/**
13
 * A Page is a single wiki page in one project.
14
 */
15
class Page extends Model
16
{
17
    /** @var string The page name as provided at instantiation. */
18
    protected $unnormalizedPageName;
19
20
    /** @var string[] Metadata about this page. */
21
    protected $pageInfo;
22
23
    /** @var string[] Revision history of this page. */
24
    protected $revisions;
25
26
    /** @var int Number of revisions for this page. */
27
    protected $numRevisions;
28
29
    /** @var string[] List of Wikidata sitelinks for this page. */
30
    protected $wikidataItems;
31
32
    /** @var int Number of Wikidata sitelinks for this page. */
33
    protected $numWikidataItems;
34
35
    /**
36
     * Page constructor.
37
     * @param Project $project
38
     * @param string $pageName
39
     */
40 42
    public function __construct(Project $project, string $pageName)
41
    {
42 42
        $this->project = $project;
43 42
        $this->unnormalizedPageName = $pageName;
44 42
    }
45
46
    /**
47
     * Get a Page instance given a revision row (JOINed on the page table).
48
     * @param Project $project
49
     * @param array $rev Must contain 'page_title' and 'page_namespace'.
50
     * @return static
51
     */
52 3
    public static function newFromRev(Project $project, array $rev): self
53
    {
54 3
        $namespaces = $project->getNamespaces();
55 3
        $pageTitle = $rev['page_title'];
56
57 3
        if (0 === (int)$rev['page_namespace']) {
58 2
            $fullPageTitle = $pageTitle;
59
        } else {
60 2
            $fullPageTitle = $namespaces[$rev['page_namespace']].":$pageTitle";
61
        }
62
63 3
        return new self($project, $fullPageTitle);
64
    }
65
66
    /**
67
     * Unique identifier for this Page, to be used in cache keys.
68
     * Use of md5 ensures the cache key does not contain reserved characters.
69
     * @see Repository::getCacheKey()
70
     * @return string
71
     * @codeCoverageIgnore
72
     */
73
    public function getCacheKey(): string
74
    {
75
        return md5((string)$this->getId());
76
    }
77
78
    /**
79
     * Get basic information about this page from the repository.
80
     * @return array|null
81
     */
82 9
    protected function getPageInfo(): ?array
83
    {
84 9
        if (empty($this->pageInfo)) {
85 9
            $this->pageInfo = $this->getRepository()
86 9
                ->getPageInfo($this->project, $this->unnormalizedPageName);
0 ignored issues
show
Bug introduced by
The method getPageInfo() does not exist on AppBundle\Repository\Repository. It seems like you code against a sub-type of AppBundle\Repository\Repository such as AppBundle\Repository\PageRepository. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

86
                ->/** @scrutinizer ignore-call */ getPageInfo($this->project, $this->unnormalizedPageName);
Loading history...
87
        }
88 9
        return $this->pageInfo;
89
    }
90
91
    /**
92
     * Get the page's title.
93
     * @param bool $useUnnormalized Use the unnormalized page title to avoid an API call. This should be used only if
94
     *   you fetched the page title via other means (SQL query), and is not from user input alone.
95
     * @return string
96
     */
97 3
    public function getTitle(bool $useUnnormalized = false): string
98
    {
99 3
        if ($useUnnormalized) {
100 1
            return $this->unnormalizedPageName;
101
        }
102 3
        $info = $this->getPageInfo();
103 3
        return $info['title'] ?? $this->unnormalizedPageName;
104
    }
105
106
    /**
107
     * Get the page's title without the namespace.
108
     * @return string
109
     */
110 1
    public function getTitleWithoutNamespace(): string
111
    {
112 1
        $info = $this->getPageInfo();
113 1
        $title = $info['title'] ?? $this->unnormalizedPageName;
114 1
        $nsName = $this->getNamespaceName();
115 1
        return str_replace($nsName . ':', '', $title);
116
    }
117
118
    /**
119
     * Get this page's database ID.
120
     * @return int|null Null if nonexistent.
121
     */
122 1
    public function getId(): ?int
123
    {
124 1
        $info = $this->getPageInfo();
125 1
        return isset($info['pageid']) ? (int)$info['pageid'] : null;
126
    }
127
128
    /**
129
     * Get this page's length in bytes.
130
     * @return int|null Null if nonexistent.
131
     */
132 1
    public function getLength(): ?int
133
    {
134 1
        $info = $this->getPageInfo();
135 1
        return isset($info['length']) ? (int)$info['length'] : null;
136
    }
137
138
    /**
139
     * Get HTML for the stylized display of the title.
140
     * The text will be the same as Page::getTitle().
141
     * @return string
142
     */
143 1
    public function getDisplayTitle(): string
144
    {
145 1
        $info = $this->getPageInfo();
146 1
        if (isset($info['displaytitle'])) {
147 1
            return $info['displaytitle'];
148
        }
149 1
        return $this->getTitle();
150
    }
151
152
    /**
153
     * Get the full URL of this page.
154
     * @return string|null Null if nonexistent.
155
     */
156 1
    public function getUrl(): ?string
157
    {
158 1
        $info = $this->getPageInfo();
159 1
        return $info['fullurl'] ?? null;
160
    }
161
162
    /**
163
     * Get the numerical ID of the namespace of this page.
164
     * @return int|null Null if page doesn't exist.
165
     */
166 2
    public function getNamespace(): ?int
167
    {
168 2
        $info = $this->getPageInfo();
169 2
        return isset($info['ns']) ? (int)$info['ns'] : null;
170
    }
171
172
    /**
173
     * Get the name of the namespace of this page.
174
     * @return string|null Null if could not be determined.
175
     */
176 1
    public function getNamespaceName(): ?string
177
    {
178 1
        $info = $this->getPageInfo();
179 1
        return isset($info['ns'])
180 1
            ? ($this->getProject()->getNamespaces()[$info['ns']] ?? null)
181 1
            : null;
182
    }
183
184
    /**
185
     * Get the number of page watchers.
186
     * @return int|null Null if unknown.
187
     */
188 1
    public function getWatchers(): ?int
189
    {
190 1
        $info = $this->getPageInfo();
191 1
        return isset($info['watchers']) ? (int)$info['watchers'] : null;
192
    }
193
194
    /**
195
     * Get the HTML content of the body of the page.
196
     * @param DateTime|int $target If a DateTime object, the
197
     *   revision at that time will be returned. If an integer, it is
198
     *   assumed to be the actual revision ID.
199
     * @return string
200
     */
201 1
    public function getHTMLContent($target = null): string
202
    {
203 1
        if (is_a($target, 'DateTime')) {
204
            $target = $this->getRepository()->getRevisionIdAtDate($this, $target);
0 ignored issues
show
Bug introduced by
The method getRevisionIdAtDate() does not exist on AppBundle\Repository\Repository. It seems like you code against a sub-type of AppBundle\Repository\Repository such as AppBundle\Repository\PageRepository. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

204
            $target = $this->getRepository()->/** @scrutinizer ignore-call */ getRevisionIdAtDate($this, $target);
Loading history...
205
        }
206 1
        return $this->getRepository()->getHTMLContent($this, $target);
0 ignored issues
show
Bug introduced by
The method getHTMLContent() does not exist on AppBundle\Repository\Repository. It seems like you code against a sub-type of AppBundle\Repository\Repository such as AppBundle\Repository\PageRepository. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

206
        return $this->getRepository()->/** @scrutinizer ignore-call */ getHTMLContent($this, $target);
Loading history...
207
    }
208
209
    /**
210
     * Whether or not this page exists.
211
     * @return bool
212
     */
213 1
    public function exists(): bool
214
    {
215 1
        $info = $this->getPageInfo();
216 1
        return null !== $info && !isset($info['missing']) && !isset($info['invalid']) && !isset($info['interwiki']);
217
    }
218
219
    /**
220
     * Get the Project to which this page belongs.
221
     * @return Project
222
     */
223 16
    public function getProject(): Project
224
    {
225 16
        return $this->project;
226
    }
227
228
    /**
229
     * Get the language code for this page.
230
     * If not set, the language code for the project is returned.
231
     * @return string
232
     */
233 2
    public function getLang(): string
234
    {
235 2
        $info = $this->getPageInfo();
236 2
        if (isset($info['pagelanguage'])) {
237 2
            return $info['pagelanguage'];
238
        } else {
239
            return $this->getProject()->getLang();
240
        }
241
    }
242
243
    /**
244
     * Get the Wikidata ID of this page.
245
     * @return string|null Null if none exists.
246
     */
247 4
    public function getWikidataId(): ?string
248
    {
249 4
        $info = $this->getPageInfo();
250 4
        if (isset($info['pageprops']['wikibase_item'])) {
251 3
            return $info['pageprops']['wikibase_item'];
252
        } else {
253 1
            return null;
254
        }
255
    }
256
257
    /**
258
     * Get the number of revisions the page has.
259
     * @param User $user Optionally limit to those of this user.
260
     * @param false|int $start
261
     * @param false|int $end
262
     * @return int
263
     */
264 4
    public function getNumRevisions(?User $user = null, $start = false, $end = false): int
265
    {
266
        // If a user is given, we will not cache the result via instance variable.
267 4
        if (null !== $user) {
268
            return (int)$this->getRepository()->getNumRevisions($this, $user, $start, $end);
0 ignored issues
show
Bug introduced by
The method getNumRevisions() does not exist on AppBundle\Repository\Repository. It seems like you code against a sub-type of AppBundle\Repository\Repository such as AppBundle\Repository\PageRepository. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

268
            return (int)$this->getRepository()->/** @scrutinizer ignore-call */ getNumRevisions($this, $user, $start, $end);
Loading history...
269
        }
270
271
        // Return cached value, if present.
272 4
        if (null !== $this->numRevisions) {
273
            return $this->numRevisions;
274
        }
275
276
        // Otherwise, return the count of all revisions if already present.
277 4
        if (null !== $this->revisions) {
278
            $this->numRevisions = count($this->revisions);
279
        } else {
280
            // Otherwise do a COUNT in the event fetching all revisions is not desired.
281 4
            $this->numRevisions = (int)$this->getRepository()->getNumRevisions($this, null, $start, $end);
282
        }
283
284 4
        return $this->numRevisions;
285
    }
286
287
    /**
288
     * Get all edits made to this page.
289
     * @param User|null $user Specify to get only revisions by the given user.
290
     * @param false|int $start
291
     * @param false|int $end
292
     * @return array
293
     */
294
    public function getRevisions(?User $user = null, $start = false, $end = false): array
295
    {
296
        if ($this->revisions) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->revisions 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...
297
            return $this->revisions;
298
        }
299
300
        $this->revisions = $this->getRepository()->getRevisions($this, $user, $start, $end);
0 ignored issues
show
Bug introduced by
The method getRevisions() does not exist on AppBundle\Repository\Repository. It seems like you code against a sub-type of AppBundle\Repository\Repository such as AppBundle\Repository\GlobalContribsRepository or AppBundle\Repository\PageRepository or AppBundle\Repository\EditSummaryRepository. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

300
        $this->revisions = $this->getRepository()->/** @scrutinizer ignore-call */ getRevisions($this, $user, $start, $end);
Loading history...
301
302
        return $this->revisions;
303
    }
304
305
    /**
306
     * Get the full page wikitext.
307
     * @return string|null Null if nothing was found.
308
     */
309 1
    public function getWikitext(): ?string
310
    {
311 1
        $content = $this->getRepository()->getPagesWikitext(
0 ignored issues
show
Bug introduced by
The method getPagesWikitext() does not exist on AppBundle\Repository\Repository. It seems like you code against a sub-type of AppBundle\Repository\Repository such as AppBundle\Repository\PageRepository. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

311
        $content = $this->getRepository()->/** @scrutinizer ignore-call */ getPagesWikitext(
Loading history...
312 1
            $this->getProject(),
313 1
            [ $this->getTitle() ]
314
        );
315
316 1
        return $content[$this->getTitle()] ?? null;
317
    }
318
319
    /**
320
     * Get the statement for a single revision, so that you can iterate row by row.
321
     * @see PageRepository::getRevisionsStmt()
322
     * @param User|null $user Specify to get only revisions by the given user.
323
     * @param int $limit Max number of revisions to process.
324
     * @param int $numRevisions Number of revisions, if known. This is used solely to determine the
325
     *   OFFSET if we are given a $limit. If $limit is set and $numRevisions is not set, a
326
     *   separate query is ran to get the nuber of revisions.
327
     * @param false|int $start
328
     * @param false|int $end
329
     * @return \Doctrine\DBAL\Driver\PDOStatement
330
     */
331
    public function getRevisionsStmt(
332
        ?User $user = null,
333
        ?int $limit = null,
334
        ?int $numRevisions = null,
335
        $start = false,
336
        $end = false
337
    ): \Doctrine\DBAL\Driver\PDOStatement {
338
        // If we have a limit, we need to know the total number of revisions so that PageRepo
339
        // will properly set the OFFSET. See PageRepository::getRevisionsStmt() for more info.
340
        if (isset($limit) && null === $numRevisions) {
341
            $numRevisions = $this->getNumRevisions($user, $start, $end);
342
        }
343
        return $this->getRepository()->getRevisionsStmt($this, $user, $limit, $numRevisions, $start, $end);
0 ignored issues
show
Bug introduced by
The method getRevisionsStmt() does not exist on AppBundle\Repository\Repository. It seems like you code against a sub-type of AppBundle\Repository\Repository such as AppBundle\Repository\PageRepository. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

343
        return $this->getRepository()->/** @scrutinizer ignore-call */ getRevisionsStmt($this, $user, $limit, $numRevisions, $start, $end);
Loading history...
344
    }
345
346
    /**
347
     * Get the revision ID that immediately precedes the given date.
348
     * @param DateTime $date
349
     * @return int|null Null if none found.
350
     */
351
    public function getRevisionIdAtDate(DateTime $date): ?int
352
    {
353
        return $this->getRepository()->getRevisionIdAtDate($this, $date);
354
    }
355
356
    /**
357
     * Get CheckWiki errors for this page
358
     * @return string[] See getErrors() for format
359
     */
360 1
    public function getCheckWikiErrors(): array
361
    {
362 1
        return $this->getRepository()->getCheckWikiErrors($this);
0 ignored issues
show
Bug introduced by
The method getCheckWikiErrors() does not exist on AppBundle\Repository\Repository. It seems like you code against a sub-type of AppBundle\Repository\Repository such as AppBundle\Repository\PageRepository. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

362
        return $this->getRepository()->/** @scrutinizer ignore-call */ getCheckWikiErrors($this);
Loading history...
363
    }
364
365
    /**
366
     * Get Wikidata errors for this page
367
     * @return string[] See getErrors() for format
368
     */
369 2
    public function getWikidataErrors(): array
370
    {
371 2
        $errors = [];
372
373 2
        if (empty($this->getWikidataId())) {
374
            return [];
375
        }
376
377 2
        $wikidataInfo = $this->getRepository()->getWikidataInfo($this);
0 ignored issues
show
Bug introduced by
The method getWikidataInfo() does not exist on AppBundle\Repository\Repository. It seems like you code against a sub-type of AppBundle\Repository\Repository such as AppBundle\Repository\PageRepository. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

377
        $wikidataInfo = $this->getRepository()->/** @scrutinizer ignore-call */ getWikidataInfo($this);
Loading history...
378
379 2
        $terms = array_map(function ($entry) {
380 2
            return $entry['term'];
381 2
        }, $wikidataInfo);
382
383 2
        $lang = $this->getLang();
384
385 2
        if (!in_array('label', $terms)) {
386
            $errors[] = [
387
                'prio' => 2,
388
                'name' => 'Wikidata',
389
                'notice' => "Label for language <em>$lang</em> is missing", // FIXME: i18n
390
                'explanation' => "See: <a target='_blank' " .
391
                    "href='//www.wikidata.org/wiki/Help:Label'>Help:Label</a>",
392
            ];
393
        }
394
395 2
        if (!in_array('description', $terms)) {
396 2
            $errors[] = [
397 2
                'prio' => 3,
398 2
                'name' => 'Wikidata',
399 2
                'notice' => "Description for language <em>$lang</em> is missing", // FIXME: i18n
400
                'explanation' => "See: <a target='_blank' " .
401
                    "href='//www.wikidata.org/wiki/Help:Description'>Help:Description</a>",
402
            ];
403
        }
404
405 2
        return $errors;
406
    }
407
408
    /**
409
     * Get Wikidata and CheckWiki errors, if present
410
     * @return string[] List of errors in the format:
411
     *    [[
412
     *         'prio' => int,
413
     *         'name' => string,
414
     *         'notice' => string (HTML),
415
     *         'explanation' => string (HTML)
416
     *     ], ... ]
417
     */
418 1
    public function getErrors(): array
419
    {
420
        // Includes label and description
421 1
        $wikidataErrors = $this->getWikidataErrors();
422
423 1
        $checkWikiErrors = $this->getCheckWikiErrors();
424
425 1
        return array_merge($wikidataErrors, $checkWikiErrors);
426
    }
427
428
    /**
429
     * Get all wikidata items for the page, not just languages of sister projects
430
     * @return string[]
431
     */
432 1
    public function getWikidataItems(): array
433
    {
434 1
        if (!is_array($this->wikidataItems)) {
0 ignored issues
show
introduced by
The condition is_array($this->wikidataItems) is always true.
Loading history...
435 1
            $this->wikidataItems = $this->getRepository()->getWikidataItems($this);
436
        }
437 1
        return $this->wikidataItems;
438
    }
439
440
    /**
441
     * Count wikidata items for the page, not just languages of sister projects
442
     * @return int Number of records.
443
     */
444 2
    public function countWikidataItems(): int
445
    {
446 2
        if (is_array($this->wikidataItems)) {
0 ignored issues
show
introduced by
The condition is_array($this->wikidataItems) is always true.
Loading history...
447
            $this->numWikidataItems = count($this->wikidataItems);
448 2
        } elseif (null === $this->numWikidataItems) {
449 2
            $this->numWikidataItems = (int)$this->getRepository()->countWikidataItems($this);
450
        }
451 2
        return $this->numWikidataItems;
452
    }
453
454
    /**
455
     * Get number of in and outgoing links and redirects to this page.
456
     * @return string[] Counts with keys 'links_ext_count', 'links_out_count', 'links_in_count' and 'redirects_count'.
457
     */
458 2
    public function countLinksAndRedirects(): array
459
    {
460 2
        return $this->getRepository()->countLinksAndRedirects($this);
0 ignored issues
show
Bug introduced by
The method countLinksAndRedirects() does not exist on AppBundle\Repository\Repository. It seems like you code against a sub-type of AppBundle\Repository\Repository such as AppBundle\Repository\PageRepository. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

460
        return $this->getRepository()->/** @scrutinizer ignore-call */ countLinksAndRedirects($this);
Loading history...
461
    }
462
463
    /**
464
     * Get the sum of pageviews for the given page and timeframe.
465
     * @param string|DateTime $start In the format YYYYMMDD
466
     * @param string|DateTime $end In the format YYYYMMDD
467
     * @return int
468
     */
469 1
    public function getPageviews($start, $end): int
470
    {
471
        try {
472 1
            $pageviews = $this->getRepository()->getPageviews($this, $start, $end);
0 ignored issues
show
Bug introduced by
The method getPageviews() does not exist on AppBundle\Repository\Repository. It seems like you code against a sub-type of AppBundle\Repository\Repository such as AppBundle\Repository\PageRepository. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

472
            $pageviews = $this->getRepository()->/** @scrutinizer ignore-call */ getPageviews($this, $start, $end);
Loading history...
473
        } catch (\GuzzleHttp\Exception\ClientException $e) {
474
            // 404 means zero pageviews
475
            return 0;
476
        }
477
478 1
        return array_sum(array_map(function ($item) {
479 1
            return (int)$item['views'];
480 1
        }, $pageviews['items']));
481
    }
482
483
    /**
484
     * Get the sum of pageviews over the last N days
485
     * @param int $days Default 30
486
     * @return int Number of pageviews
487
     */
488 1
    public function getLastPageviews(int $days = 30): int
489
    {
490 1
        $start = date('Ymd', strtotime("-$days days"));
491 1
        $end = date('Ymd');
492 1
        return $this->getPageviews($start, $end);
493
    }
494
495
    /**
496
     * Is the page the project's Main Page?
497
     * @return bool
498
     */
499 1
    public function isMainPage(): bool
500
    {
501 1
        return $this->getProject()->getMainPage() === $this->getTitle();
502
    }
503
}
504