Passed
Push — master ( b97736...5ab0b6 )
by MusikAnimal
04:31
created

ArticleInfo::getEndDate()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * This file contains only the ArticleInfo class.
4
 */
5
6
namespace Xtools;
7
8
use Symfony\Component\DependencyInjection\Container;
9
use Symfony\Component\DomCrawler\Crawler;
10
use DateTime;
11
12
/**
13
 * An ArticleInfo provides statistics about a page on a project. This model does not
14
 * have a separate Repository because it needs to use individual SQL statements to
15
 * traverse the page's history, saving class instance variables along the way.
16
 */
17
class ArticleInfo extends Model
18
{
19
    /** @const string[] Domain names of wikis supported by WikiWho. */
20
    const TEXTSHARE_WIKIS = [
21
        'en.wikipedia.org',
22
        'de.wikipedia.org',
23
        'eu.wikipedia.org',
24
        'tr.wikipedia.org',
25
        'es.wikipedia.org',
26
    ];
27
28
    /** @var Container The application's DI container. */
29
    protected $container;
30
31
    /** @var Page The page. */
32
    protected $page;
33
34
    /** @var false|int From what date to obtain records. */
35
    protected $startDate;
36
37
    /** @var false|int To what date to obtain records. */
38
    protected $endDate;
39
40
    /** @var int Number of revisions that belong to the page. */
41
    protected $numRevisions;
42
43
    /** @var int Maximum number of revisions to process, as configured. */
44
    protected $maxRevisions;
45
46
    /** @var int Number of revisions that were actually processed. */
47
    protected $numRevisionsProcessed;
48
49
    /**
50
     * Various statistics about editors to the page. These are not User objects
51
     * so as to preserve memory.
52
     * @var mixed[]
53
     */
54
    protected $editors;
55
56
    /** @var mixed[] The top 10 editors to the page by number of edits. */
57
    protected $topTenEditorsByEdits;
58
59
    /** @var mixed[] The top 10 editors to the page by added text. */
60
    protected $topTenEditorsByAdded;
61
62
    /** @var int Number of edits made by the top 10 editors. */
63
    protected $topTenCount;
64
65
    /** @var mixed[] Various statistics about bots that edited the page. */
66
    protected $bots;
67
68
    /** @var int Number of edits made to the page by bots. */
69
    protected $botRevisionCount;
70
71
    /** @var mixed[] Various counts about each individual year and month of the page's history. */
72
    protected $yearMonthCounts;
73
74
    /** @var Edit The first edit to the page. */
75
    protected $firstEdit;
76
77
    /** @var Edit The last edit to the page. */
78
    protected $lastEdit;
79
80
    /** @var Edit Edit that made the largest addition by number of bytes. */
81
    protected $maxAddition;
82
83
    /** @var Edit Edit that made the largest deletion by number of bytes. */
84
    protected $maxDeletion;
85
86
    /** @var int[] Number of in and outgoing links and redirects to the page. */
87
    protected $linksAndRedirects;
88
89
    /** @var string[] Assessments of the page (see Page::getAssessments). */
90
    protected $assessments;
91
92
    /**
93
     * Maximum number of edits that were created across all months. This is used as a comparison
94
     * for the bar charts in the months section.
95
     * @var int
96
     */
97
    protected $maxEditsPerMonth;
98
99
    /** @var string[] List of (semi-)automated tools that were used to edit the page. */
100
    protected $tools;
101
102
    /**
103
     * Total number of bytes added throughout the page's history. This is used as a comparison
104
     * when computing the top 10 editors by added text.
105
     * @var int
106
     */
107
    protected $addedBytes = 0;
108
109
    /** @var int Number of days between first and last edit. */
110
    protected $totalDays;
111
112
    /** @var int Number of minor edits to the page. */
113
    protected $minorCount = 0;
114
115
    /** @var int Number of anonymous edits to the page. */
116
    protected $anonCount = 0;
117
118
    /** @var int Number of automated edits to the page. */
119
    protected $automatedCount = 0;
120
121
    /** @var int Number of edits to the page that were reverted with the subsequent edit. */
122
    protected $revertCount = 0;
123
124
    /** @var int[] The "edits per <time>" counts. */
125
    protected $countHistory = [
126
        'day' => 0,
127
        'week' => 0,
128
        'month' => 0,
129
        'year' => 0
130
    ];
131
132
    /** @var string[] List of wikidata and Checkwiki errors. */
133
    protected $bugs;
134
135
    /** @var array List of editors and the percentage of the current content that they authored. */
136
    protected $textshares;
137
138
    /** @var array Number of categories, templates and files on the page. */
139
    protected $transclusionData;
140
141
    /**
142
     * ArticleInfo constructor.
143
     * @param Page $page The page to process.
144
     * @param Container $container The DI container.
145
     * @param false|int $start From what date to obtain records.
146
     * @param false|int $end To what date to obtain records.
147
     */
148 13
    public function __construct(Page $page, Container $container, $start = false, $end = false)
149
    {
150 13
        $this->page = $page;
151 13
        $this->container = $container;
152 13
        $this->startDate = $start;
153 13
        $this->endDate = $end;
154 13
    }
155
156
    /**
157
     * Get date opening date range.
158
     * @return false|int
159
     */
160 1
    public function getStartDate()
161
    {
162 1
        return $this->startDate;
163
    }
164
165
    /**
166
     * Get date closing date range.
167
     * @return false|int
168
     */
169 1
    public function getEndDate()
170
    {
171 1
        return $this->endDate;
172
    }
173
174
    /**
175
     * Get the day of last date we should show in the month/year sections,
176
     * based on $this->endDate or the current date.
177
     * @return int As Unix timestamp.
178
     */
179 4
    private function getLastDay()
180
    {
181 4
        if ($this->endDate !== false) {
182
            return (new DateTime('@'.$this->endDate))
183
                ->modify('last day of this month')
184
                ->getTimestamp();
185
        } else {
186 4
            return strtotime('last day of this month');
187
        }
188
    }
189
190
    /**
191
     * Has date range?
192
     * @return bool
193
     */
194 1
    public function hasDateRange()
195
    {
196 1
        return $this->startDate !== false || $this->endDate !== false;
197
    }
198
199
    /**
200
     * Return the start/end date values as associative array,
201
     * with YYYY-MM-DD as the date format. This is used mainly as
202
     * a helper to pass to the pageviews Twig macros.
203
     * @return array
204
     */
205 1
    public function getDateParams()
206
    {
207 1
        if (!$this->hasDateRange()) {
208
            return [];
209
        }
210
211
        $ret = [
212 1
            'start' => $this->firstEdit->getTimestamp()->format('Y-m-d'),
213 1
            'end' => $this->lastEdit->getTimestamp()->format('Y-m-d'),
214
        ];
215
216 1
        if ($this->startDate !== false) {
217 1
            $ret['start'] = date('Y-m-d', $this->startDate);
218
        }
219 1
        if ($this->endDate !== false) {
220 1
            $ret['end'] = date('Y-m-d', $this->endDate);
221
        }
222
223 1
        return $ret;
224
    }
225
226
    /**
227
     * Shorthand to get the page's project.
228
     * @return Project
229
     * @codeCoverageIgnore
230
     */
231
    public function getProject()
232
    {
233
        return $this->page->getProject();
234
    }
235
236
    /**
237
     * Get the number of revisions belonging to the page.
238
     * @return int
239
     */
240 4
    public function getNumRevisions()
241
    {
242 4
        if (!isset($this->numRevisions)) {
243 4
            $this->numRevisions = $this->page->getNumRevisions(null, $this->startDate, $this->endDate);
244
        }
245 4
        return $this->numRevisions;
246
    }
247
248
    /**
249
     * Get the maximum number of revisions that we should process.
250
     * @return int
251
     */
252 3
    public function getMaxRevisions()
253
    {
254 3
        if (!isset($this->maxRevisions)) {
255 3
            $this->maxRevisions = (int) $this->container->getParameter('app.max_page_revisions');
256
        }
257 3
        return $this->maxRevisions;
258
    }
259
260
    /**
261
     * Get the number of revisions that are actually getting processed.
262
     * This goes by the app.max_page_revisions parameter, or the actual
263
     * number of revisions, whichever is smaller.
264
     * @return int
265
     */
266 6
    public function getNumRevisionsProcessed()
267
    {
268 6
        if (isset($this->numRevisionsProcessed)) {
269 4
            return $this->numRevisionsProcessed;
270
        }
271
272 2
        if ($this->tooManyRevisions()) {
273 1
            $this->numRevisionsProcessed = $this->getMaxRevisions();
274
        } else {
275 1
            $this->numRevisionsProcessed = $this->getNumRevisions();
276
        }
277
278 2
        return $this->numRevisionsProcessed;
279
    }
280
281
    /**
282
     * Are there more revisions than we should process, based on the config?
283
     * @return bool
284
     */
285 3
    public function tooManyRevisions()
286
    {
287 3
        return $this->getMaxRevisions() > 0 && $this->getNumRevisions() > $this->getMaxRevisions();
288
    }
289
290
    /**
291
     * Fetch and store all the data we need to show the ArticleInfo view.
292
     * @codeCoverageIgnore
293
     */
294
    public function prepareData()
295
    {
296
        $this->parseHistory();
297
        $this->setLogsEvents();
298
299
        // Bots need to be set before setting top 10 counts.
300
        $this->setBots();
301
302
        $this->setTopTenCounts();
303
    }
304
305
    /**
306
     * Get the number of editors that edited the page.
307
     * @return int
308
     */
309 1
    public function getNumEditors()
310
    {
311 1
        return count($this->editors);
312
    }
313
314
    /**
315
     * Get the number of bots that edited the page.
316
     * @return int
317
     */
318
    public function getNumBots()
319
    {
320
        return count($this->getBots());
321
    }
322
323
    /**
324
     * Get the number of days between the first and last edit.
325
     * @return int
326
     */
327 1
    public function getTotalDays()
328
    {
329 1
        if (isset($this->totalDays)) {
330 1
            return $this->totalDays;
331
        }
332 1
        $dateFirst = $this->firstEdit->getTimestamp();
333 1
        $dateLast = $this->lastEdit->getTimestamp();
334 1
        $interval = date_diff($dateLast, $dateFirst, true);
335 1
        $this->totalDays = $interval->format('%a');
0 ignored issues
show
Documentation Bug introduced by
The property $totalDays was declared of type integer, but $interval->format('%a') is of type string. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
336 1
        return $this->totalDays;
337
    }
338
339
    /**
340
     * Returns length of the page.
341
     * @return int
342
     */
343 1
    public function getLength()
344
    {
345 1
        if ($this->hasDateRange()) {
346 1
            return $this->lastEdit->getLength();
347
        }
348
349
        return $this->page->getLength();
350
    }
351
352
    /**
353
     * Get the average number of days between edits to the page.
354
     * @return double
355
     */
356 1
    public function averageDaysPerEdit()
357
    {
358 1
        return round($this->getTotalDays() / $this->getNumRevisionsProcessed(), 1);
359
    }
360
361
    /**
362
     * Get the average number of edits per day to the page.
363
     * @return double
364
     */
365 1
    public function editsPerDay()
366
    {
367 1
        $editsPerDay = $this->getTotalDays()
368 1
            ? $this->getNumRevisionsProcessed() / ($this->getTotalDays() / (365 / 12 / 24))
369 1
            : 0;
370 1
        return round($editsPerDay, 1);
371
    }
372
373
    /**
374
     * Get the average number of edits per month to the page.
375
     * @return double
376
     */
377 1
    public function editsPerMonth()
378
    {
379 1
        $editsPerMonth = $this->getTotalDays()
380 1
            ? $this->getNumRevisionsProcessed() / ($this->getTotalDays() / (365 / 12))
381 1
            : 0;
382 1
        return min($this->getNumRevisionsProcessed(), round($editsPerMonth, 1));
383
    }
384
385
    /**
386
     * Get the average number of edits per year to the page.
387
     * @return double
388
     */
389 1
    public function editsPerYear()
390
    {
391 1
        $editsPerYear = $this->getTotalDays()
392 1
            ? $this->getNumRevisionsProcessed() / ($this->getTotalDays() / 365)
393 1
            : 0;
394 1
        return min($this->getNumRevisionsProcessed(), round($editsPerYear, 1));
395
    }
396
397
    /**
398
     * Get the average number of edits per editor.
399
     * @return double
400
     */
401 1
    public function editsPerEditor()
402
    {
403 1
        return round($this->getNumRevisionsProcessed() / count($this->editors), 1);
404
    }
405
406
    /**
407
     * Get the percentage of minor edits to the page.
408
     * @return double
409
     */
410 1
    public function minorPercentage()
411
    {
412 1
        return round(
413 1
            ($this->minorCount / $this->getNumRevisionsProcessed()) * 100,
414 1
            1
415
        );
416
    }
417
418
    /**
419
     * Get the percentage of anonymous edits to the page.
420
     * @return double
421
     */
422 1
    public function anonPercentage()
423
    {
424 1
        return round(
425 1
            ($this->anonCount / $this->getNumRevisionsProcessed()) * 100,
426 1
            1
427
        );
428
    }
429
430
    /**
431
     * Get the percentage of edits made by the top 10 editors.
432
     * @return double
433
     */
434 1
    public function topTenPercentage()
435
    {
436 1
        return round(($this->topTenCount / $this->getNumRevisionsProcessed()) * 100, 1);
437
    }
438
439
    /**
440
     * Get the number of times the page has been viewed in the given timeframe.
441
     * If the ArticleInfo instance has a date range, it is used instead of the
442
     * value of the $latest parameter.
443
     * @param  int $latest Last N days.
444
     * @return int
445
     */
446
    public function getPageviews($latest)
447
    {
448
        if (!$this->hasDateRange()) {
449
            return $this->page->getLastPageviews($latest);
450
        }
451
452
        $daterange = $this->getDateParams();
453
        return $this->page->getPageviews($daterange['start'], $daterange['end']);
454
    }
455
456
    /**
457
     * Get the page assessments of the page.
458
     * @see https://www.mediawiki.org/wiki/Extension:PageAssessments
459
     * @return string[]|false False if unsupported.
460
     * @codeCoverageIgnore
461
     */
462
    public function getAssessments()
463
    {
464
        if (!is_array($this->assessments)) {
0 ignored issues
show
introduced by
The condition ! is_array($this->assessments) can never be true.
Loading history...
465
            $this->assessments = $this->page->getAssessments();
466
        }
467
        return $this->assessments;
468
    }
469
470
    /**
471
     * Get the number of automated edits made to the page.
472
     * @return int
473
     */
474 1
    public function getAutomatedCount()
475
    {
476 1
        return $this->automatedCount;
477
    }
478
479
    /**
480
     * Get the number of edits to the page that were reverted with the subsequent edit.
481
     * @return int
482
     */
483 1
    public function getRevertCount()
484
    {
485 1
        return $this->revertCount;
486
    }
487
488
    /**
489
     * Get the number of edits to the page made by logged out users.
490
     * @return int
491
     */
492 1
    public function getAnonCount()
493
    {
494 1
        return $this->anonCount;
495
    }
496
497
    /**
498
     * Get the number of minor edits to the page.
499
     * @return int
500
     */
501 1
    public function getMinorCount()
502
    {
503 1
        return $this->minorCount;
504
    }
505
506
    /**
507
     * Get the number of edits to the page made in the past day, week, month and year.
508
     * @return int[] With keys 'day', 'week', 'month' and 'year'.
509
     */
510
    public function getCountHistory()
511
    {
512
        return $this->countHistory;
513
    }
514
515
    /**
516
     * Get the number of edits to the page made by the top 10 editors.
517
     * @return int
518
     */
519 1
    public function getTopTenCount()
520
    {
521 1
        return $this->topTenCount;
522
    }
523
524
    /**
525
     * Get the first edit to the page.
526
     * @return Edit
527
     */
528 1
    public function getFirstEdit()
529
    {
530 1
        return $this->firstEdit;
531
    }
532
533
    /**
534
     * Get the last edit to the page.
535
     * @return Edit
536
     */
537 1
    public function getLastEdit()
538
    {
539 1
        return $this->lastEdit;
540
    }
541
542
    /**
543
     * Get the edit that made the largest addition to the page (by number of bytes).
544
     * @return Edit
545
     */
546 1
    public function getMaxAddition()
547
    {
548 1
        return $this->maxAddition;
549
    }
550
551
    /**
552
     * Get the edit that made the largest removal to the page (by number of bytes).
553
     * @return Edit
554
     */
555 1
    public function getMaxDeletion()
556
    {
557 1
        return $this->maxDeletion;
558
    }
559
560
    /**
561
     * Get the list of editors to the page, including various statistics.
562
     * @return mixed[]
563
     */
564 1
    public function getEditors()
565
    {
566 1
        return $this->editors;
567
    }
568
569
    /**
570
     * Get the list of the top editors to the page (by edits), including various statistics.
571
     * @return mixed[]
572
     */
573 1
    public function topTenEditorsByEdits()
574
    {
575 1
        return $this->topTenEditorsByEdits;
576
    }
577
578
    /**
579
     * Get the list of the top editors to the page (by added text), including various statistics.
580
     * @return mixed[]
581
     */
582 1
    public function topTenEditorsByAdded()
583
    {
584 1
        return $this->topTenEditorsByAdded;
585
    }
586
587
    /**
588
     * Get various counts about each individual year and month of the page's history.
589
     * @return mixed[]
590
     */
591 2
    public function getYearMonthCounts()
592
    {
593 2
        return $this->yearMonthCounts;
594
    }
595
596
    /**
597
     * Get the maximum number of edits that were created across all months. This is used as a
598
     * comparison for the bar charts in the months section.
599
     * @return int
600
     */
601 1
    public function getMaxEditsPerMonth()
602
    {
603 1
        return $this->maxEditsPerMonth;
604
    }
605
606
    /**
607
     * Get a list of (semi-)automated tools that were used to edit the page, including
608
     * the number of times they were used, and a link to the tool's homepage.
609
     * @return mixed[]
610
     */
611 1
    public function getTools()
612
    {
613 1
        return $this->tools;
614
    }
615
616
    /**
617
     * Get the list of page's wikidata and Checkwiki errors.
618
     * @see Page::getErrors()
619
     * @return string[]
620
     */
621
    public function getBugs()
622
    {
623
        if (!is_array($this->bugs)) {
0 ignored issues
show
introduced by
The condition ! is_array($this->bugs) can never be true.
Loading history...
624
            $this->bugs = $this->page->getErrors();
625
        }
626
        return $this->bugs;
627
    }
628
629
    /**
630
     * Get the number of wikidata nad CheckWiki errors.
631
     * @return int
632
     */
633
    public function numBugs()
634
    {
635
        return count($this->getBugs());
636
    }
637
638
    /**
639
     * Get the number of external links on the page.
640
     * @return int
641
     */
642 1
    public function linksExtCount()
643
    {
644 1
        return $this->getLinksAndRedirects()['links_ext_count'];
645
    }
646
647
    /**
648
     * Get the number of incoming links to the page.
649
     * @return int
650
     */
651 1
    public function linksInCount()
652
    {
653 1
        return $this->getLinksAndRedirects()['links_in_count'];
654
    }
655
656
    /**
657
     * Get the number of outgoing links from the page.
658
     * @return int
659
     */
660 1
    public function linksOutCount()
661
    {
662 1
        return $this->getLinksAndRedirects()['links_out_count'];
663
    }
664
665
    /**
666
     * Get the number of redirects to the page.
667
     * @return int
668
     */
669 1
    public function redirectsCount()
670
    {
671 1
        return $this->getLinksAndRedirects()['redirects_count'];
672
    }
673
674
    /**
675
     * Get the number of external, incoming and outgoing links, along with
676
     * the number of redirects to the page.
677
     * @return int
678
     * @codeCoverageIgnore
679
     */
680
    private function getLinksAndRedirects()
681
    {
682
        if (!is_array($this->linksAndRedirects)) {
0 ignored issues
show
introduced by
The condition ! is_array($this->linksAndRedirects) can never be true.
Loading history...
683
            $this->linksAndRedirects = $this->page->countLinksAndRedirects();
684
        }
685
        return $this->linksAndRedirects;
686
    }
687
688
    /**
689
     * Parse the revision history, collecting our core statistics.
690
     * @return mixed[] Associative "master" array of metadata about the page.
691
     *
692
     * Untestable because it relies on getting a PDO statement. All the important
693
     * logic lives in other methods which are tested.
694
     * @codeCoverageIgnore
695
     */
696
    private function parseHistory()
697
    {
698
        if ($this->tooManyRevisions()) {
699
            $limit = $this->getMaxRevisions();
700
        } else {
701
            $limit = null;
702
        }
703
704
        // Third parameter is ignored if $limit is null.
705
        $revStmt = $this->page->getRevisionsStmt(
706
            null,
707
            $limit,
708
            $this->getNumRevisions(),
709
            $this->startDate,
710
            $this->endDate
711
        );
712
        $revCount = 0;
713
714
        /**
715
         * Data about previous edits so that we can use them as a basis for comparison.
716
         * @var Edit[]
717
         */
718
        $prevEdits = [
719
            // The previous Edit, used to discount content that was reverted.
720
            'prev' => null,
721
722
            // The last edit deemed to be the max addition of content. This is kept track of
723
            // in case we find out the next edit was reverted (and was also a max edit),
724
            // in which case we'll want to discount it and use this one instead.
725
            'maxAddition' => null,
726
727
            // Same as with maxAddition, except the maximum amount of content deleted.
728
            // This is used to discount content that was reverted.
729
            'maxDeletion' => null,
730
        ];
731
732
        while ($rev = $revStmt->fetch()) {
733
            $edit = new Edit($this->page, $rev);
734
735
            if ($revCount === 0) {
0 ignored issues
show
introduced by
The condition $revCount === 0 can never be false.
Loading history...
736
                $this->firstEdit = $edit;
737
            }
738
739
            // Sometimes, with old revisions (2001 era), the revisions from 2002 come before 2001
740
            if ($edit->getTimestamp() < $this->firstEdit->getTimestamp()) {
741
                $this->firstEdit = $edit;
742
            }
743
744
            $prevEdits = $this->updateCounts($edit, $prevEdits);
745
746
            $revCount++;
747
        }
748
749
        $this->numRevisionsProcessed = $revCount;
750
751
        // Various sorts
752
        arsort($this->editors);
753
        ksort($this->yearMonthCounts);
754
        if ($this->tools) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->tools 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...
755
            arsort($this->tools);
756
        }
757
    }
758
759
    /**
760
     * Update various counts based on the current edit.
761
     * @param  Edit   $edit
762
     * @param  Edit[] $prevEdits With 'prev', 'maxAddition' and 'maxDeletion'
763
     * @return Edit[] Updated version of $prevEdits.
764
     */
765 4
    private function updateCounts(Edit $edit, $prevEdits)
766
    {
767
        // Update the counts for the year and month of the current edit.
768 4
        $this->updateYearMonthCounts($edit);
769
770
        // Update counts for the user who made the edit.
771 4
        $this->updateUserCounts($edit);
772
773
        // Update the year/month/user counts of anon and minor edits.
774 4
        $this->updateAnonMinorCounts($edit);
775
776
        // Update counts for automated tool usage, if applicable.
777 4
        $this->updateToolCounts($edit);
778
779
        // Increment "edits per <time>" counts
780 4
        $this->updateCountHistory($edit);
781
782
        // Update figures regarding content addition/removal, and the revert count.
783 4
        $prevEdits = $this->updateContentSizes($edit, $prevEdits);
784
785
        // Now that we've updated all the counts, we can reset
786
        // the prev and last edits, which are used for tracking.
787 4
        $prevEdits['prev'] = $edit;
788 4
        $this->lastEdit = $edit;
789
790 4
        return $prevEdits;
791
    }
792
793
    /**
794
     * Update various figures about content sizes based on the given edit.
795
     * @param  Edit   $edit
796
     * @param  Edit[] $prevEdits With 'prev', 'maxAddition' and 'maxDeletion'
797
     * @return Edit[] Updated version of $prevEdits.
798
     */
799 4
    private function updateContentSizes(Edit $edit, $prevEdits)
800
    {
801
        // Check if it was a revert
802 4
        if ($edit->isRevert($this->container)) {
803 4
            return $this->updateContentSizesRevert($prevEdits);
804
        } else {
805 4
            return $this->updateContentSizesNonRevert($edit, $prevEdits);
806
        }
807
    }
808
809
    /**
810
     * Updates the figures on content sizes assuming the given edit was a revert of the previous one.
811
     * In such a case, we don't want to treat the previous edit as legit content addition or removal.
812
     * @param  Edit[] $prevEdits With 'prev', 'maxAddition' and 'maxDeletion'.
813
     * @return Edit[] Updated version of $prevEdits, for tracking.
814
     */
815 4
    private function updateContentSizesRevert($prevEdits)
816
    {
817 4
        $this->revertCount++;
818
819
        // Adjust addedBytes given this edit was a revert of the previous one.
820 4
        if ($prevEdits['prev'] && $prevEdits['prev']->getSize() > 0) {
821
            $this->addedBytes -= $prevEdits['prev']->getSize();
822
823
            // Also deduct from the user's individual added byte count.
824
            $username = $prevEdits['prev']->getUser()->getUsername();
825
            $this->editors[$username]['added'] -= $prevEdits['prev']->getSize();
826
        }
827
828
        // @TODO: Test this against an edit war (use your sandbox).
829
        // Also remove as max added or deleted, if applicable.
830 4
        if ($this->maxAddition && $prevEdits['prev']->getId() === $this->maxAddition->getId()) {
831
            // $this->editors[$prevEdits->getUser()->getUsername()]['sizes'] = $edit->getLength() / 1024;
832
            $this->maxAddition = $prevEdits['maxAddition'];
833
            $prevEdits['maxAddition'] = $prevEdits['prev']; // In the event of edit wars.
834 4
        } elseif ($this->maxDeletion && $prevEdits['prev']->getId() === $this->maxDeletion->getId()) {
835 4
            $this->maxDeletion = $prevEdits['maxDeletion'];
836 4
            $prevEdits['maxDeletion'] = $prevEdits['prev']; // In the event of edit wars.
837
        }
838
839 4
        return $prevEdits;
840
    }
841
842
    /**
843
     * Updates the figures on content sizes assuming the given edit
844
     * was NOT a revert of the previous edit.
845
     * @param  Edit   $edit
846
     * @param  Edit[] $prevEdits With 'prev', 'maxAddition' and 'maxDeletion'.
847
     * @return Edit[] Updated version of $prevEdits, for tracking.
848
     */
849 4
    private function updateContentSizesNonRevert(Edit $edit, $prevEdits)
850
    {
851 4
        $editSize = $this->getEditSize($edit, $prevEdits);
852
853
        // Edit was not a revert, so treat size > 0 as content added.
854 4
        if ($editSize > 0) {
855 4
            $this->addedBytes += $editSize;
856 4
            $this->editors[$edit->getUser()->getUsername()]['added'] += $editSize;
857
858
            // Keep track of edit with max addition.
859 4
            if (!$this->maxAddition || $editSize > $this->maxAddition->getSize()) {
860
                // Keep track of old maxAddition in case we find out the next $edit was reverted
861
                // (and was also a max edit), in which case we'll want to use this one ($edit).
862 4
                $prevEdits['maxAddition'] = $this->maxAddition;
863
864 4
                $this->maxAddition = $edit;
865
            }
866 4
        } elseif ($editSize < 0 && (!$this->maxDeletion || $editSize < $this->maxDeletion->getSize())) {
867
            // Keep track of old maxDeletion in case we find out the next edit was reverted
868
            // (and was also a max deletion), in which case we'll want to use this one.
869 4
            $prevEdits['maxDeletion'] = $this->maxDeletion;
870
871 4
            $this->maxDeletion = $edit;
872
        }
873
874 4
        return $prevEdits;
875
    }
876
877
    /**
878
     * Get the size of the given edit, based on the previous edit (if present).
879
     * We also don't return the actual edit size if last revision had a length of null.
880
     * This happens when the edit follows other edits that were revision-deleted.
881
     * @see T148857 for more information.
882
     * @todo Remove once T101631 is resolved.
883
     * @param  Edit   $edit
884
     * @param  Edit[] $prevEdits With 'prev', 'maxAddition' and 'maxDeletion'.
885
     * @return Edit[] Updated version of $prevEdits, for tracking.
886
     */
887 4
    private function getEditSize(Edit $edit, $prevEdits)
888
    {
889 4
        if ($prevEdits['prev'] && $prevEdits['prev']->getLength() === null) {
0 ignored issues
show
introduced by
The condition $prevEdits['prev'] && $p...]->getLength() === null can never be true.
Loading history...
890
            return 0;
891
        } else {
892 4
            return $edit->getSize();
893
        }
894
    }
895
896
    /**
897
     * Update counts of automated tool usage for the given edit.
898
     * @param Edit $edit
899
     */
900 4
    private function updateToolCounts(Edit $edit)
901
    {
902 4
        $automatedTool = $edit->getTool($this->container);
903
904 4
        if ($automatedTool === false) {
905
            // Nothing to do.
906 4
            return;
907
        }
908
909 4
        $editYear = $edit->getYear();
910 4
        $editMonth = $edit->getMonth();
911
912 4
        $this->automatedCount++;
913 4
        $this->yearMonthCounts[$editYear]['automated']++;
914 4
        $this->yearMonthCounts[$editYear]['months'][$editMonth]['automated']++;
915
916 4
        if (!isset($this->tools[$automatedTool['name']])) {
917 4
            $this->tools[$automatedTool['name']] = [
918 4
                'count' => 1,
919 4
                'link' => $automatedTool['link'],
920
            ];
921
        } else {
922
            $this->tools[$automatedTool['name']]['count']++;
923
        }
924 4
    }
925
926
    /**
927
     * Update various counts for the year and month of the given edit.
928
     * @param Edit $edit
929
     */
930 4
    private function updateYearMonthCounts(Edit $edit)
931
    {
932 4
        $editYear = $edit->getYear();
933 4
        $editMonth = $edit->getMonth();
934
935
        // Fill in the blank arrays for the year and 12 months if needed.
936 4
        if (!isset($this->yearMonthCounts[$editYear])) {
937 4
            $this->addYearMonthCountEntry($edit);
938
        }
939
940
        // Increment year and month counts for all edits
941 4
        $this->yearMonthCounts[$editYear]['all']++;
942 4
        $this->yearMonthCounts[$editYear]['months'][$editMonth]['all']++;
943
        // This will ultimately be the size of the page by the end of the year
944 4
        $this->yearMonthCounts[$editYear]['size'] = (int) $edit->getLength();
945
946
        // Keep track of which month had the most edits
947 4
        $editsThisMonth = $this->yearMonthCounts[$editYear]['months'][$editMonth]['all'];
948 4
        if ($editsThisMonth > $this->maxEditsPerMonth) {
949 4
            $this->maxEditsPerMonth = $editsThisMonth;
950
        }
951 4
    }
952
953
    /**
954
     * Add a new entry to $this->yearMonthCounts for the given year,
955
     * with blank values for each month. This called during self::parseHistory().
956
     * @param Edit $edit
957
     */
958 4
    private function addYearMonthCountEntry(Edit $edit)
959
    {
960 4
        $editYear = $edit->getYear();
961
962
        // Beginning of the month at 00:00:00.
963 4
        $firstEditTime = mktime(0, 0, 0, (int) $this->firstEdit->getMonth(), 1, $this->firstEdit->getYear());
0 ignored issues
show
Bug introduced by
$this->firstEdit->getYear() of type string is incompatible with the type integer expected by parameter $year of mktime(). ( Ignorable by Annotation )

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

963
        $firstEditTime = mktime(0, 0, 0, (int) $this->firstEdit->getMonth(), 1, /** @scrutinizer ignore-type */ $this->firstEdit->getYear());
Loading history...
964
965 4
        $this->yearMonthCounts[$editYear] = [
966
            'all' => 0,
967
            'minor' => 0,
968
            'anon' => 0,
969
            'automated' => 0,
970
            'size' => 0, // Keep track of the size by the end of the year.
971
            'events' => [],
972
            'months' => [],
973
        ];
974
975 4
        for ($i = 1; $i <= 12; $i++) {
976 4
            $timeObj = mktime(0, 0, 0, $i, 1, $editYear);
977
978
            // Don't show zeros for months before the first edit or after the current month.
979 4
            if ($timeObj < $firstEditTime || $timeObj > $this->getLastDay()) {
980 4
                continue;
981
            }
982
983 4
            $this->yearMonthCounts[$editYear]['months'][sprintf('%02d', $i)] = [
984
                'all' => 0,
985
                'minor' => 0,
986
                'anon' => 0,
987
                'automated' => 0,
988
            ];
989
        }
990 4
    }
991
992
    /**
993
     * Update the counts of anon and minor edits for year, month,
994
     * and user of the given edit.
995
     * @param Edit $edit
996
     */
997 4
    private function updateAnonMinorCounts(Edit $edit)
998
    {
999 4
        $editYear = $edit->getYear();
1000 4
        $editMonth = $edit->getMonth();
1001
1002
        // If anonymous, increase counts
1003 4
        if ($edit->isAnon()) {
1004 4
            $this->anonCount++;
1005 4
            $this->yearMonthCounts[$editYear]['anon']++;
1006 4
            $this->yearMonthCounts[$editYear]['months'][$editMonth]['anon']++;
1007
        }
1008
1009
        // If minor edit, increase counts
1010 4
        if ($edit->isMinor()) {
1011 4
            $this->minorCount++;
1012 4
            $this->yearMonthCounts[$editYear]['minor']++;
1013 4
            $this->yearMonthCounts[$editYear]['months'][$editMonth]['minor']++;
1014
        }
1015 4
    }
1016
1017
    /**
1018
     * Update various counts for the user of the given edit.
1019
     * @param Edit $edit
1020
     */
1021 4
    private function updateUserCounts(Edit $edit)
1022
    {
1023 4
        $username = $edit->getUser()->getUsername();
1024
1025
        // Initialize various user stats if needed.
1026 4
        if (!isset($this->editors[$username])) {
1027 4
            $this->editors[$username] = [
1028 4
                'all' => 0,
1029 4
                'minor' => 0,
1030 4
                'minorPercentage' => 0,
1031 4
                'first' => $edit->getTimestamp(),
1032 4
                'firstId' => $edit->getId(),
1033
                'last' => null,
1034
                'atbe' => null,
1035 4
                'added' => 0,
1036
                'sizes' => [],
1037
            ];
1038
        }
1039
1040
        // Increment user counts
1041 4
        $this->editors[$username]['all']++;
1042 4
        $this->editors[$username]['last'] = $edit->getTimestamp();
1043 4
        $this->editors[$username]['lastId'] = $edit->getId();
1044
1045
        // Store number of KB added with this edit
1046 4
        $this->editors[$username]['sizes'][] = $edit->getLength() / 1024;
1047
1048
        // Increment minor counts for this user
1049 4
        if ($edit->isMinor()) {
1050 4
            $this->editors[$username]['minor']++;
1051
        }
1052 4
    }
1053
1054
    /**
1055
     * Increment "edits per <time>" counts based on the given edit.
1056
     * @param Edit $edit
1057
     */
1058 4
    private function updateCountHistory(Edit $edit)
1059
    {
1060 4
        $editTimestamp = $edit->getTimestamp();
1061
1062 4
        if ($editTimestamp > new DateTime('-1 day')) {
1063
            $this->countHistory['day']++;
1064
        }
1065 4
        if ($editTimestamp > new DateTime('-1 week')) {
1066
            $this->countHistory['week']++;
1067
        }
1068 4
        if ($editTimestamp > new DateTime('-1 month')) {
1069
            $this->countHistory['month']++;
1070
        }
1071 4
        if ($editTimestamp > new DateTime('-1 year')) {
1072
            $this->countHistory['year']++;
1073
        }
1074 4
    }
1075
1076
    /**
1077
     * Get info about bots that edited the page.
1078
     * @return mixed[] Contains the bot's username, edit count to the page,
1079
     *   and whether or not they are currently a bot.
1080
     */
1081 1
    public function getBots()
1082
    {
1083 1
        return $this->bots;
1084
    }
1085
1086
    /**
1087
     * Set info about bots that edited the page. This is done as a private setter
1088
     * because we need this information when computing the top 10 editors,
1089
     * where we don't want to include bots.
1090
     */
1091
    private function setBots()
1092
    {
1093
        // Parse the botedits
1094
        $bots = [];
1095
        $botData = $this->getRepository()->getBotData($this->page, $this->startDate, $this->endDate);
1096
        while ($bot = $botData->fetch()) {
1097
            $bots[$bot['username']] = [
1098
                'count' => (int) $bot['count'],
1099
                'current' => $bot['current'] === 'bot',
1100
            ];
1101
        }
1102
1103
        // Sort by edit count.
1104
        uasort($bots, function ($a, $b) {
1105
            return $b['count'] - $a['count'];
1106
        });
1107
1108
        $this->bots = $bots;
1109
    }
1110
1111
    /**
1112
     * Number of edits made to the page by current or former bots.
1113
     * @param string[] $bots Used only in unit tests, where we
1114
     *   supply mock data for the bots that will get processed.
1115
     * @return int
1116
     */
1117 2
    public function getBotRevisionCount($bots = null)
1118
    {
1119 2
        if (isset($this->botRevisionCount)) {
1120
            return $this->botRevisionCount;
1121
        }
1122
1123 2
        if ($bots === null) {
1124 1
            $bots = $this->getBots();
1125
        }
1126
1127 2
        $count = 0;
1128
1129 2
        foreach ($bots as $username => $data) {
1130 2
            $count += $data['count'];
1131
        }
1132
1133 2
        $this->botRevisionCount = $count;
1134 2
        return $count;
1135
    }
1136
1137
    /**
1138
     * Query for log events during each year of the article's history,
1139
     *   and set the results in $this->yearMonthCounts.
1140
     */
1141 1
    private function setLogsEvents()
1142
    {
1143 1
        $logData = $this->getRepository()->getLogEvents(
0 ignored issues
show
Bug introduced by
The method getLogEvents() does not exist on Xtools\Repository. Did you maybe mean getLog()? ( Ignorable by Annotation )

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

1143
        $logData = $this->getRepository()->/** @scrutinizer ignore-call */ getLogEvents(

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
1144 1
            $this->page,
1145 1
            $this->startDate,
1146 1
            $this->endDate
1147
        );
1148
1149 1
        foreach ($logData as $event) {
1150 1
            $time = strtotime($event['timestamp']);
1151 1
            $year = date('Y', $time);
1152
1153 1
            if (!isset($this->yearMonthCounts[$year])) {
1154
                break;
1155
            }
1156
1157 1
            $yearEvents = $this->yearMonthCounts[$year]['events'];
1158
1159
            // Convert log type value to i18n key.
1160 1
            switch ($event['log_type']) {
1161 1
                case 'protect':
1162 1
                    $action = 'protections';
1163 1
                    break;
1164 1
                case 'delete':
1165 1
                    $action = 'deletions';
1166 1
                    break;
1167
                case 'move':
1168
                    $action = 'moves';
1169
                    break;
1170
                // count pending-changes protections along with normal protections.
1171
                case 'stable':
1172
                    $action = 'protections';
1173
                    break;
1174
            }
1175
1176 1
            if (empty($yearEvents[$action])) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $action does not seem to be defined for all execution paths leading up to this point.
Loading history...
1177 1
                $yearEvents[$action] = 1;
1178
            } else {
1179
                $yearEvents[$action]++;
1180
            }
1181
1182 1
            $this->yearMonthCounts[$year]['events'] = $yearEvents;
1183
        }
1184 1
    }
1185
1186
    /**
1187
     * Set statistics about the top 10 editors by added text and number of edits.
1188
     * This is ran *after* parseHistory() since we need the grand totals first.
1189
     * Various stats are also set for each editor in $this->editors to be used in the charts.
1190
     * @return integer Number of edits
1191
     */
1192 4
    private function setTopTenCounts()
1193
    {
1194 4
        $topTenCount = $counter = 0;
1195 4
        $topTenEditors = [];
1196
1197 4
        foreach ($this->editors as $editor => $info) {
1198
            // Count how many users are in the top 10% by number of edits, excluding bots.
1199 4
            if ($counter < 10 && !in_array($editor, array_keys($this->bots))) {
1200 4
                $topTenCount += $info['all'];
1201 4
                $counter++;
1202
1203
                // To be used in the Top Ten charts.
1204 4
                $topTenEditors[] = [
1205 4
                    'label' => $editor,
1206 4
                    'value' => $info['all'],
1207
                    'percentage' => (
1208 4
                        100 * ($info['all'] / $this->getNumRevisionsProcessed())
1209
                    )
1210
                ];
1211
            }
1212
1213
            // Compute the percentage of minor edits the user made.
1214 4
            $this->editors[$editor]['minorPercentage'] = $info['all']
1215 4
                ? ($info['minor'] / $info['all']) * 100
1216
                : 0;
1217
1218 4
            if ($info['all'] > 1) {
1219
                // Number of seconds/days between first and last edit.
1220 4
                $secs = $info['last']->getTimestamp() - $info['first']->getTimestamp();
1221 4
                $days = $secs / (60 * 60 * 24);
1222
1223
                // Average time between edits (in days).
1224 4
                $this->editors[$editor]['atbe'] = $days / $info['all'];
1225
            }
1226
1227 4
            if (count($info['sizes'])) {
1228
                // Average Total KB divided by number of stored sizes (usually the user's edit count to this page).
1229 4
                $this->editors[$editor]['size'] = array_sum($info['sizes']) / count($info['sizes']);
1230
            } else {
1231 4
                $this->editors[$editor]['size'] = 0;
1232
            }
1233
        }
1234
1235 4
        $this->topTenEditorsByEdits = $topTenEditors;
1236
1237
        // First sort editors array by the amount of text they added.
1238 4
        $topTenEditorsByAdded = $this->editors;
1239
        uasort($topTenEditorsByAdded, function ($a, $b) {
1240 4
            if ($a['added'] === $b['added']) {
1241 4
                return 0;
1242
            }
1243 4
            return $a['added'] > $b['added'] ? -1 : 1;
1244 4
        });
1245
1246
        // Then build a new array of top 10 editors by added text,
1247
        // in the data structure needed for the chart.
1248
        $this->topTenEditorsByAdded = array_map(function ($editor) {
1249 4
            $added = $this->editors[$editor]['added'];
1250
            return [
1251 4
                'label' => $editor,
1252 4
                'value' => $added,
1253
                'percentage' => (
1254 4
                    100 * ($added / $this->addedBytes)
1255
                )
1256
            ];
1257 4
        }, array_keys(array_slice($topTenEditorsByAdded, 0, 10)));
1258
1259 4
        $this->topTenCount = $topTenCount;
1260 4
    }
1261
1262
    /**
1263
     * Get authorship attribution from the WikiWho API.
1264
     * @see https://f-squared.org/wikiwho/
1265
     * @param  int $limit Max number of results.
1266
     * @return array
1267
     */
1268 1
    public function getTextshares($limit = null)
1269
    {
1270 1
        if (isset($this->textshares)) {
1271
            return $this->textshares;
1272
        }
1273
1274
        // TODO: check for failures. Should have a success:true
1275 1
        $ret = $this->getRepository()->getTextshares($this->page);
1276
1277
        // If revision can't be found, return error message.
1278 1
        if (!isset($ret['revisions'][0])) {
1279
            return [
1280
                'error' => isset($ret['Error']) ? $ret['Error'] : 'Unknown'
1281
            ];
1282
        }
1283
1284 1
        $revId = array_keys($ret['revisions'][0])[0];
1285 1
        $tokens = $ret['revisions'][0][$revId]['tokens'];
1286
1287 1
        list($counts, $totalCount, $userIds) = $this->countTokens($tokens);
1288 1
        $usernameMap = $this->getUsernameMap($userIds);
1289
1290 1
        if ($limit !== null) {
1291 1
            $countsToProcess = array_slice($counts, 0, $limit, true);
1292
        } else {
1293
            $countsToProcess = $counts;
1294
        }
1295
1296 1
        $textshares = [];
1297
1298
        // Loop through once more, creating an array with the user names (or IP address)
1299
        // as the key, and the count and percentage as the value.
1300 1
        foreach ($countsToProcess as $editor => $count) {
1301 1
            if (isset($usernameMap[$editor])) {
1302 1
                $index = $usernameMap[$editor];
1303
            } else {
1304 1
                $index = $editor;
1305
            }
1306 1
            $textshares[$index] = [
1307 1
                'count' => $count,
1308 1
                'percentage' => round(100 * ($count / $totalCount), 1)
1309
            ];
1310
        }
1311
1312 1
        $this->textshares = [
1313 1
            'list' => $textshares,
1314 1
            'totalAuthors' => count($counts),
1315 1
            'totalCount' => $totalCount,
1316
        ];
1317
1318 1
        return $this->textshares;
1319
    }
1320
1321
    /**
1322
     * Get a map of user IDs to usernames, given the IDs.
1323
     * @param  int[] $userIds
1324
     * @return array IDs as keys, usernames as values.
1325
     */
1326 1
    private function getUsernameMap($userIds)
1327
    {
1328 1
        $userIdsNames = $this->getRepository()->getUsernamesFromIds(
1329 1
            $this->page->getProject(),
1330 1
            $userIds
1331
        );
1332
1333 1
        $usernameMap = [];
1334 1
        foreach ($userIdsNames as $userIdName) {
1335 1
            $usernameMap[$userIdName['user_id']] = $userIdName['user_name'];
1336
        }
1337
1338 1
        return $usernameMap;
1339
    }
1340
1341
    /**
1342
     * Get counts of token lengths for each author. Used in self::getTextshares()
1343
     * @param  array $tokens
1344
     * @return array [counts by user, total count, IDs of accounts]
1345
     */
1346 1
    private function countTokens($tokens)
1347
    {
1348 1
        $counts = [];
1349 1
        $userIds = [];
1350 1
        $totalCount = 0;
1351
1352
        // Loop through the tokens, keeping totals (token length) for each author.
1353 1
        foreach ($tokens as $token) {
1354 1
            $editor = $token['editor'];
1355
1356
            // IPs are prefixed with '0|', otherwise it's the user ID.
1357 1
            if (substr($editor, 0, 2) === '0|') {
1358 1
                $editor = substr($editor, 2);
1359
            } else {
1360 1
                $userIds[] = $editor;
1361
            }
1362
1363 1
            if (!isset($counts[$editor])) {
1364 1
                $counts[$editor] = 0;
1365
            }
1366
1367 1
            $counts[$editor] += strlen($token['str']);
1368 1
            $totalCount += strlen($token['str']);
1369
        }
1370
1371
        // Sort authors by count.
1372 1
        arsort($counts);
1373
1374 1
        return [$counts, $totalCount, $userIds];
1375
    }
1376
1377
    /**
1378
     * Get a list of wikis supported by WikiWho.
1379
     * @return string[]
1380
     * @codeCoverageIgnore
1381
     */
1382
    public function getTextshareWikis()
1383
    {
1384
        return self::TEXTSHARE_WIKIS;
1385
    }
1386
1387
    /**
1388
     * Get prose and reference information.
1389
     * @return array With keys 'characters', 'words', 'references', 'unique_references'
1390
     */
1391 1
    public function getProseStats()
1392
    {
1393 1
        $datetime = $this->endDate !== false ? new DateTime('@'.$this->endDate) : null;
1394 1
        $html = $this->page->getHTMLContent($datetime);
1395
1396 1
        $crawler = new Crawler($html);
1397
1398 1
        list($chars, $words) = $this->countCharsAndWords($crawler, '#mw-content-text p');
1399
1400 1
        $refs = $crawler->filter('#mw-content-text .reference');
1401 1
        $refContent = [];
1402
        $refs->each(function ($ref) use (&$refContent) {
1403 1
            $refContent[] = $ref->text();
1404 1
        });
1405 1
        $uniqueRefs = count(array_unique($refContent));
1406
1407 1
        $sections = count($crawler->filter('#mw-content-text .mw-headline'));
1408
1409
        return [
1410 1
            'characters' => $chars,
1411 1
            'words' => $words,
1412 1
            'references' => $refs->count(),
1413 1
            'unique_references' => $uniqueRefs,
1414 1
            'sections' => $sections,
1415
        ];
1416
    }
1417
1418
    /**
1419
     * Count the number of characters and words of the plain text
1420
     * within the DOM element matched by the given selector.
1421
     * @param  Crawler $crawler
1422
     * @param  string $selector HTML selector.
1423
     * @return array [num chars, num words]
1424
     */
1425 1
    private function countCharsAndWords($crawler, $selector)
1426
    {
1427 1
        $totalChars = 0;
1428 1
        $totalWords = 0;
1429 1
        $paragraphs = $crawler->filter($selector);
1430 1
        $paragraphs->each(function ($node) use (&$totalChars, &$totalWords) {
1431 1
            $text = preg_replace('/\[\d+\]/', '', trim($node->text()));
1432 1
            $totalChars += strlen($text);
1433 1
            $totalWords += count(explode(' ', $text));
1434 1
        });
1435
1436 1
        return [$totalChars, $totalWords];
1437
    }
1438
1439
    /**
1440
     * Fetch transclusion data (categories, templates and files)
1441
     * that are on the page.
1442
     * @return array With keys 'categories', 'templates' and 'files'.
1443
     */
1444 1
    private function getTransclusionData()
1445
    {
1446 1
        if (!is_array($this->transclusionData)) {
0 ignored issues
show
introduced by
The condition ! is_array($this->transclusionData) can never be true.
Loading history...
1447 1
            $this->transclusionData = $this->getRepository()
1448 1
                ->getTransclusionData($this->page);
1449
        }
1450 1
        return $this->transclusionData;
1451
    }
1452
1453
    /**
1454
     * Get the number of categories that are on the page.
1455
     * @return int
1456
     */
1457 1
    public function getNumCategories()
1458
    {
1459 1
        return $this->getTransclusionData()['categories'];
1460
    }
1461
1462
    /**
1463
     * Get the number of templates that are on the page.
1464
     * @return int
1465
     */
1466 1
    public function getNumTemplates()
1467
    {
1468 1
        return $this->getTransclusionData()['templates'];
1469
    }
1470
1471
    /**
1472
     * Get the number of files that are on the page.
1473
     * @return int
1474
     */
1475 1
    public function getNumFiles()
1476
    {
1477 1
        return $this->getTransclusionData()['files'];
1478
    }
1479
}
1480