Test Failed
Pull Request — master (#378)
by MusikAnimal
08:25
created

ArticleInfo::updateContentSizesRevert()   B

Complexity

Conditions 9
Paths 9

Size

Total Lines 27
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 16.1088

Importance

Changes 0
Metric Value
cc 9
eloc 13
nc 9
nop 1
dl 0
loc 27
rs 8.0555
c 0
b 0
f 0
ccs 5
cts 9
cp 0.5556
crap 16.1088
1
<?php
2
/**
3
 * This file contains only the ArticleInfo class.
4
 */
5
6
declare(strict_types = 1);
7
8
namespace AppBundle\Model;
9
10
use AppBundle\Helper\I18nHelper;
11
use DateTime;
12
use Symfony\Component\DependencyInjection\ContainerInterface;
13
14
/**
15
 * An ArticleInfo provides statistics about a page on a project.
16
 */
17
class ArticleInfo extends ArticleInfoApi
18
{
19
    /** @var I18nHelper For i18n and l10n. */
20
    protected $i18n;
21
22
    /** @var int Maximum number of revisions to process, as configured. */
23
    protected $maxRevisions;
24
25
    /** @var int Number of revisions that were actually processed. */
26
    protected $numRevisionsProcessed;
27
28
    /**
29
     * Various statistics about editors to the page. These are not User objects
30
     * so as to preserve memory.
31
     * @var mixed[]
32
     */
33
    protected $editors = [];
34
35
    /** @var mixed[] The top 10 editors to the page by number of edits. */
36
    protected $topTenEditorsByEdits;
37
38
    /** @var mixed[] The top 10 editors to the page by added text. */
39
    protected $topTenEditorsByAdded;
40
41
    /** @var int Number of edits made by the top 10 editors. */
42
    protected $topTenCount;
43
44
    /** @var mixed[] Various counts about each individual year and month of the page's history. */
45
    protected $yearMonthCounts;
46
47
    /** @var string[] Localized labels for the years, to be used in the 'Year counts' chart. */
48
    protected $yearLabels = [];
49
50
    /** @var string[] Localized labels for the months, to be used in the 'Month counts' chart. */
51
    protected $monthLabels = [];
52
53
    /** @var Edit The first edit to the page. */
54
    protected $firstEdit;
55
56
    /** @var Edit The last edit to the page. */
57
    protected $lastEdit;
58
59
    /** @var Edit Edit that made the largest addition by number of bytes. */
60
    protected $maxAddition;
61
62
    /** @var Edit Edit that made the largest deletion by number of bytes. */
63
    protected $maxDeletion;
64
65
    /**
66
     * Maximum number of edits that were created across all months. This is used as a comparison
67
     * for the bar charts in the months section.
68
     * @var int
69
     */
70
    protected $maxEditsPerMonth;
71
72
    /** @var string[][] List of (semi-)automated tools that were used to edit the page. */
73
    protected $tools;
74
75
    /**
76
     * Total number of bytes added throughout the page's history. This is used as a comparison
77
     * when computing the top 10 editors by added text.
78
     * @var int
79
     */
80
    protected $addedBytes = 0;
81
82
    /** @var int Number of days between first and last edit. */
83
    protected $totalDays;
84
85
    /** @var int Number of minor edits to the page. */
86
    protected $minorCount = 0;
87
88
    /** @var int Number of anonymous edits to the page. */
89
    protected $anonCount = 0;
90
91
    /** @var int Number of automated edits to the page. */
92
    protected $automatedCount = 0;
93
94
    /** @var int Number of edits to the page that were reverted with the subsequent edit. */
95
    protected $revertCount = 0;
96
97
    /** @var int[] The "edits per <time>" counts. */
98
    protected $countHistory = [
99
        'day' => 0,
100
        'week' => 0,
101
        'month' => 0,
102
        'year' => 0,
103
    ];
104
105
    /**
106
     * Make the I18nHelper accessible to ArticleInfo.
107
     * @param I18nHelper $i18n
108
     * @codeCoverageIgnore
109
     */
110
    public function setI18nHelper(I18nHelper $i18n): void
111
    {
112 12
        $this->i18n = $i18n;
113
    }
114 12
115 12
    /**
116
     * Get the day of last date we should show in the month/year sections,
117
     * based on $this->end or the current date.
118
     * @return int As Unix timestamp.
119
     */
120
    private function getLastDay(): int
121
    {
122
        if (false !== $this->end) {
123
            return (new DateTime('@'.$this->end))
0 ignored issues
show
Bug introduced by
Are you sure $this->end of type integer|true can be used in concatenation? ( Ignorable by Annotation )

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

123
            return (new DateTime('@'./** @scrutinizer ignore-type */ $this->end))
Loading history...
124
                ->modify('last day of this month')
125
                ->getTimestamp();
126
        } else {
127
            return strtotime('last day of this month');
128
        }
129
    }
130
131
    /**
132 4
     * Return the start/end date values as associative array, with YYYY-MM-DD as the date format.
133
     * This is used mainly as a helper to pass to the pageviews Twig macros.
134 4
     * @return array
135
     */
136
    public function getDateParams(): array
137
    {
138
        if (!$this->hasDateRange()) {
139 4
            return [];
140
        }
141
142
        $ret = [
143
            'start' => $this->firstEdit->getTimestamp()->format('Y-m-d'),
144
            'end' => $this->lastEdit->getTimestamp()->format('Y-m-d'),
145
        ];
146
147
        if (false !== $this->start) {
148 1
            $ret['start'] = date('Y-m-d', $this->start);
0 ignored issues
show
Bug introduced by
It seems like $this->start can also be of type true; however, parameter $timestamp of date() does only seem to accept integer|null, maybe add an additional type check? ( Ignorable by Annotation )

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

148
            $ret['start'] = date('Y-m-d', /** @scrutinizer ignore-type */ $this->start);
Loading history...
149
        }
150 1
        if (false !== $this->end) {
151
            $ret['end'] = date('Y-m-d', $this->end);
152
        }
153
154
        return $ret;
155 1
    }
156 1
157
    /**
158
     * Get the maximum number of revisions that we should process.
159 1
     * @return int
160 1
     */
161
    public function getMaxRevisions(): int
162 1
    {
163 1
        if (!isset($this->maxRevisions)) {
164
            $this->maxRevisions = (int) $this->container->getParameter('app.max_page_revisions');
165
        }
166 1
        return $this->maxRevisions;
167
    }
168
169
    /**
170
     * Get the number of revisions that are actually getting processed. This goes by the app.max_page_revisions
171
     * parameter, or the actual number of revisions, whichever is smaller.
172
     * @return int
173 3
     */
174
    public function getNumRevisionsProcessed(): int
175 3
    {
176 3
        if (isset($this->numRevisionsProcessed)) {
177
            return $this->numRevisionsProcessed;
178 3
        }
179
180
        if ($this->tooManyRevisions()) {
181
            $this->numRevisionsProcessed = $this->getMaxRevisions();
182
        } else {
183
            $this->numRevisionsProcessed = $this->getNumRevisions();
184
        }
185
186 3
        return $this->numRevisionsProcessed;
187
    }
188 3
189 1
    /**
190
     * Are there more revisions than we should process, based on the config?
191
     * @return bool
192 2
     */
193 1
    public function tooManyRevisions(): bool
194
    {
195 1
        return $this->getMaxRevisions() > 0 && $this->getNumRevisions() > $this->getMaxRevisions();
196
    }
197
198 2
    /**
199
     * Fetch and store all the data we need to show the ArticleInfo view.
200
     * @codeCoverageIgnore
201
     */
202
    public function prepareData(): void
203
    {
204
        $this->parseHistory();
205 3
        $this->setLogsEvents();
206
207 3
        // Bots need to be set before setting top 10 counts.
208
        $this->bots = $this->getBots();
209
210
        $this->doPostPrecessing();
211
    }
212
213
    /**
214
     * Get the number of editors that edited the page.
215
     * @return int
216
     */
217
    public function getNumEditors(): int
218
    {
219
        return count($this->editors);
220
    }
221
222
    /**
223
     * Get the number of days between the first and last edit.
224
     * @return int
225
     */
226
    public function getTotalDays(): int
227
    {
228
        if (isset($this->totalDays)) {
229 1
            return $this->totalDays;
230
        }
231 1
        $dateFirst = $this->firstEdit->getTimestamp();
232
        $dateLast = $this->lastEdit->getTimestamp();
233
        $interval = date_diff($dateLast, $dateFirst, true);
234
        $this->totalDays = (int)$interval->format('%a');
235
        return $this->totalDays;
236
    }
237
238 1
    /**
239
     * Returns length of the page.
240 1
     * @return int
241 1
     */
242
    public function getLength(): int
243 1
    {
244 1
        if ($this->hasDateRange()) {
245 1
            return $this->lastEdit->getLength();
246 1
        }
247 1
248
        return $this->page->getLength();
249
    }
250
251
    /**
252
     * Get the average number of days between edits to the page.
253
     * @return float
254 1
     */
255
    public function averageDaysPerEdit(): float
256 1
    {
257 1
        return round($this->getTotalDays() / $this->getNumRevisionsProcessed(), 1);
258
    }
259
260
    /**
261
     * Get the average number of edits per day to the page.
262
     * @return float
263
     */
264
    public function editsPerDay(): float
265
    {
266
        $editsPerDay = $this->getTotalDays()
267 1
            ? $this->getNumRevisionsProcessed() / ($this->getTotalDays() / (365 / 12 / 24))
268
            : 0;
269 1
        return round($editsPerDay, 1);
270
    }
271
272
    /**
273
     * Get the average number of edits per month to the page.
274
     * @return float
275
     */
276 1
    public function editsPerMonth(): float
277
    {
278 1
        $editsPerMonth = $this->getTotalDays()
279 1
            ? $this->getNumRevisionsProcessed() / ($this->getTotalDays() / (365 / 12))
280 1
            : 0;
281 1
        return min($this->getNumRevisionsProcessed(), round($editsPerMonth, 1));
282
    }
283
284
    /**
285
     * Get the average number of edits per year to the page.
286
     * @return float
287
     */
288 1
    public function editsPerYear(): float
289
    {
290 1
        $editsPerYear = $this->getTotalDays()
291 1
            ? $this->getNumRevisionsProcessed() / ($this->getTotalDays() / 365)
292 1
            : 0;
293 1
        return min($this->getNumRevisionsProcessed(), round($editsPerYear, 1));
294
    }
295
296
    /**
297
     * Get the average number of edits per editor.
298
     * @return float
299
     */
300 1
    public function editsPerEditor(): float
301
    {
302 1
        return round($this->getNumRevisionsProcessed() / count($this->editors), 1);
303 1
    }
304 1
305 1
    /**
306
     * Get the percentage of minor edits to the page.
307
     * @return float
308
     */
309
    public function minorPercentage(): float
310
    {
311
        return round(
312 1
            ($this->minorCount / $this->getNumRevisionsProcessed()) * 100,
313
            1
314 1
        );
315
    }
316
317
    /**
318
     * Get the percentage of anonymous edits to the page.
319
     * @return float
320
     */
321 1
    public function anonPercentage(): float
322
    {
323 1
        return round(
324 1
            ($this->anonCount / $this->getNumRevisionsProcessed()) * 100,
325 1
            1
326
        );
327
    }
328
329
    /**
330
     * Get the percentage of edits made by the top 10 editors.
331
     * @return float
332
     */
333 1
    public function topTenPercentage(): float
334
    {
335 1
        return round(($this->topTenCount / $this->getNumRevisionsProcessed()) * 100, 1);
336 1
    }
337 1
338
    /**
339
     * Get the number of automated edits made to the page.
340
     * @return int
341
     */
342
    public function getAutomatedCount(): int
343
    {
344
        return $this->automatedCount;
345 1
    }
346
347 1
    /**
348
     * Get the number of edits to the page that were reverted with the subsequent edit.
349
     * @return int
350
     */
351
    public function getRevertCount(): int
352
    {
353
        return $this->revertCount;
354 1
    }
355
356 1
    /**
357
     * Get the number of edits to the page made by logged out users.
358
     * @return int
359
     */
360
    public function getAnonCount(): int
361
    {
362
        return $this->anonCount;
363 1
    }
364
365 1
    /**
366
     * Get the number of minor edits to the page.
367
     * @return int
368
     */
369
    public function getMinorCount(): int
370
    {
371
        return $this->minorCount;
372 1
    }
373
374 1
    /**
375
     * Get the number of edits to the page made in the past day, week, month and year.
376
     * @return int[] With keys 'day', 'week', 'month' and 'year'.
377
     */
378
    public function getCountHistory(): array
379
    {
380
        return $this->countHistory;
381 1
    }
382
383 1
    /**
384
     * Get the number of edits to the page made by the top 10 editors.
385
     * @return int
386
     */
387
    public function getTopTenCount(): int
388
    {
389
        return $this->topTenCount;
390
    }
391
392
    /**
393
     * Get the first edit to the page.
394
     * @return Edit
395
     */
396
    public function getFirstEdit(): Edit
397
    {
398
        return $this->firstEdit;
399 1
    }
400
401 1
    /**
402
     * Get the last edit to the page.
403
     * @return Edit
404
     */
405
    public function getLastEdit(): Edit
406
    {
407
        return $this->lastEdit;
408 1
    }
409
410 1
    /**
411
     * Get the edit that made the largest addition to the page (by number of bytes).
412
     * @return Edit|null
413
     */
414
    public function getMaxAddition(): ?Edit
415
    {
416
        return $this->maxAddition;
417 1
    }
418
419 1
    /**
420
     * Get the edit that made the largest removal to the page (by number of bytes).
421
     * @return Edit|null
422
     */
423
    public function getMaxDeletion(): ?Edit
424
    {
425
        return $this->maxDeletion;
426 1
    }
427
428 1
    /**
429
     * Get the list of editors to the page, including various statistics.
430
     * @return mixed[]
431
     */
432
    public function getEditors(): array
433
    {
434
        return $this->editors;
435 1
    }
436
437 1
    /**
438
     * Get usernames of human editors (not bots).
439
     * @param int|null $limit
440
     * @return string[]
441
     */
442
    public function getHumans(?int $limit = null): array
443
    {
444 1
        return array_slice(array_diff(array_keys($this->getEditors()), array_keys($this->getBots())), 0, $limit);
445
    }
446 1
447
    /**
448
     * Get the list of the top editors to the page (by edits), including various statistics.
449
     * @return mixed[]
450
     */
451
    public function topTenEditorsByEdits(): array
452
    {
453
        return $this->topTenEditorsByEdits;
454
    }
455
456
    /**
457
     * Get the list of the top editors to the page (by added text), including various statistics.
458
     * @return mixed[]
459
     */
460
    public function topTenEditorsByAdded(): array
461
    {
462
        return $this->topTenEditorsByAdded;
463 1
    }
464
465 1
    /**
466
     * Get various counts about each individual year and month of the page's history.
467
     * @return mixed[]
468
     */
469
    public function getYearMonthCounts(): array
470
    {
471
        return $this->yearMonthCounts;
472 1
    }
473
474 1
    /**
475
     * Get the localized labels for the 'Year counts' chart.
476
     * @return string[]
477
     */
478
    public function getYearLabels(): array
479
    {
480
        return $this->yearLabels;
481 2
    }
482
483 2
    /**
484
     * Get the localized labels for the 'Month counts' chart.
485
     * @return string[]
486
     */
487
    public function getMonthLabels(): array
488
    {
489
        return $this->monthLabels;
490
    }
491
492
    /**
493
     * Get the maximum number of edits that were created across all months. This is used as a
494
     * comparison for the bar charts in the months section.
495
     * @return int
496
     */
497
    public function getMaxEditsPerMonth(): int
498
    {
499
        return $this->maxEditsPerMonth;
500
    }
501
502
    /**
503
     * Get a list of (semi-)automated tools that were used to edit the page, including
504
     * the number of times they were used, and a link to the tool's homepage.
505
     * @return string[]
506
     */
507
    public function getTools(): array
508
    {
509 1
        return $this->tools;
510
    }
511 1
512
    /**
513
     * Parse the revision history, collecting our core statistics.
514
     *
515
     * Untestable because it relies on getting a PDO statement. All the important
516
     * logic lives in other methods which are tested.
517
     * @codeCoverageIgnore
518
     */
519 1
    private function parseHistory(): void
520
    {
521 1
        if ($this->tooManyRevisions()) {
522
            $limit = $this->getMaxRevisions();
523
        } else {
524
            $limit = null;
525
        }
526
527
        // Third parameter is ignored if $limit is null.
528
        $revStmt = $this->page->getRevisionsStmt(
529
            null,
530
            $limit,
531
            $this->getNumRevisions(),
532
            $this->start,
533
            $this->end
534
        );
535
        $revCount = 0;
536
537
        /**
538
         * Data about previous edits so that we can use them as a basis for comparison.
539
         * @var Edit[]
540
         */
541
        $prevEdits = [
542
            // The previous Edit, used to discount content that was reverted.
543
            'prev' => null,
544
545
            // The SHA-1 of the edit *before* the previous edit. Used for more
546
            // accurate revert detection.
547
            'prevSha' => null,
548
549
            // The last edit deemed to be the max addition of content. This is kept track of
550
            // in case we find out the next edit was reverted (and was also a max edit),
551
            // in which case we'll want to discount it and use this one instead.
552
            'maxAddition' => null,
553
554
            // Same as with maxAddition, except the maximum amount of content deleted.
555
            // This is used to discount content that was reverted.
556
            'maxDeletion' => null,
557
        ];
558
559
        while ($rev = $revStmt->fetch()) {
560
            $edit = new Edit($this->page, $rev);
561
562
            if (0 === $revCount) {
563
                $this->firstEdit = $edit;
564
            }
565
566
            // Sometimes, with old revisions (2001 era), the revisions from 2002 come before 2001
567
            if ($edit->getTimestamp() < $this->firstEdit->getTimestamp()) {
568
                $this->firstEdit = $edit;
569
            }
570
571
            $prevEdits = $this->updateCounts($edit, $prevEdits);
572
573
            $revCount++;
574
        }
575
576
        $this->numRevisionsProcessed = $revCount;
577
578
        // Various sorts
579
        arsort($this->editors);
580
        ksort($this->yearMonthCounts);
581
        if ($this->tools) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->tools of type array<mixed,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...
582
            arsort($this->tools);
583
        }
584
    }
585
586
    /**
587
     * Update various counts based on the current edit.
588
     * @param Edit $edit
589
     * @param Edit[] $prevEdits With 'prev', 'prevSha', 'maxAddition' and 'maxDeletion'
590
     * @return Edit[] Updated version of $prevEdits.
591
     */
592
    private function updateCounts(Edit $edit, array $prevEdits): array
593
    {
594
        // Update the counts for the year and month of the current edit.
595
        $this->updateYearMonthCounts($edit);
596
597
        // Update counts for the user who made the edit.
598
        $this->updateUserCounts($edit);
599
600
        // Update the year/month/user counts of anon and minor edits.
601
        $this->updateAnonMinorCounts($edit);
602
603
        // Update counts for automated tool usage, if applicable.
604 4
        $this->updateToolCounts($edit);
605
606
        // Increment "edits per <time>" counts
607 4
        $this->updateCountHistory($edit);
608
609
        // Update figures regarding content addition/removal, and the revert count.
610 4
        $prevEdits = $this->updateContentSizes($edit, $prevEdits);
611
612
        // Now that we've updated all the counts, we can reset
613 4
        // the prev and last edits, which are used for tracking.
614
        // But first, let's copy over the SHA of the actual previous edit
615
        // and put it in our $prevEdits['prev'], so that we'll know
616 4
        // that content added after $prevEdit['prev'] was reverted.
617
        if (null !== $prevEdits['prev']) {
618
            $prevEdits['prevSha'] = $prevEdits['prev']->getSha();
619 4
        }
620
        $prevEdits['prev'] = $edit;
621
        $this->lastEdit = $edit;
622 4
623
        return $prevEdits;
624
    }
625
626
    /**
627
     * Update various figures about content sizes based on the given edit.
628
     * @param Edit $edit
629 4
     * @param Edit[] $prevEdits With 'prev', 'prevSha', 'maxAddition' and 'maxDeletion'.
630 4
     * @return Edit[] Updated version of $prevEdits.
631
     */
632 4
    private function updateContentSizes(Edit &$edit, array $prevEdits): array
633 4
    {
634
        // Check if it was a revert
635 4
        if ($this->isRevert($edit, $prevEdits)) {
636
            $edit->setReverted(true);
637
            return $this->updateContentSizesRevert($prevEdits);
638
        } else {
639
            return $this->updateContentSizesNonRevert($edit, $prevEdits);
640
        }
641
    }
642
643
    /**
644 4
     * Is the given Edit a revert?
645
     * @param Edit $edit
646
     * @param Edit[] $prevEdits With 'prev', 'prevSha', 'maxAddition' and 'maxDeletion'.
647 4
     * @return bool
648 4
     */
649 4
    private function isRevert(Edit $edit, array $prevEdits): bool
650
    {
651 4
        return $edit->getSha() === $prevEdits['prevSha'] || $edit->isRevert($this->container);
652
    }
653
654
    /**
655
     * Updates the figures on content sizes assuming the given edit was a revert of the previous one.
656
     * In such a case, we don't want to treat the previous edit as legit content addition or removal.
657
     * @param Edit[] $prevEdits With 'prev', 'prevSha', 'maxAddition' and 'maxDeletion'.
658
     * @return Edit[] Updated version of $prevEdits, for tracking.
659
     */
660
    private function updateContentSizesRevert(array $prevEdits): array
661 4
    {
662
        $this->revertCount++;
663 4
664
        // Adjust addedBytes given this edit was a revert of the previous one.
665
        if ($prevEdits['prev'] && !$prevEdits['prev']->isReverted() && $prevEdits['prev']->getSize() > 0) {
666
            $this->addedBytes -= $prevEdits['prev']->getSize();
667
668
            // Also deduct from the user's individual added byte count.
669
            // We don't do this if the previous edit was reverted, since that would make the net bytes zero.
670
            if ($prevEdits['prev']->getUser()) {
671
                $username = $prevEdits['prev']->getUser()->getUsername();
672 4
                $this->editors[$username]['added'] -= $prevEdits['prev']->getSize();
673
            }
674 4
        }
675
676
        // @TODO: Test this against an edit war (use your sandbox).
677 4
        // Also remove as max added or deleted, if applicable.
678
        if ($this->maxAddition && $prevEdits['prev']->getId() === $this->maxAddition->getId()) {
679
            $this->maxAddition = $prevEdits['maxAddition'];
680
            $prevEdits['maxAddition'] = $prevEdits['prev']; // In the event of edit wars.
681
        } elseif ($this->maxDeletion && $prevEdits['prev']->getId() === $this->maxDeletion->getId()) {
682
            $this->maxDeletion = $prevEdits['maxDeletion'];
683
            $prevEdits['maxDeletion'] = $prevEdits['prev']; // In the event of edit wars.
684
        }
685
686
        return $prevEdits;
687
    }
688
689
    /**
690 4
     * Updates the figures on content sizes assuming the given edit was NOT a revert of the previous edit.
691
     * @param Edit $edit
692
     * @param Edit[] $prevEdits With 'prev', 'prevSha', 'maxAddition' and 'maxDeletion'.
693 4
     * @return Edit[] Updated version of $prevEdits, for tracking.
694 4
     */
695 4
    private function updateContentSizesNonRevert(Edit $edit, array $prevEdits): array
696
    {
697
        $editSize = $this->getEditSize($edit, $prevEdits);
698 4
699
        // Edit was not a revert, so treat size > 0 as content added.
700
        if ($editSize > 0) {
701
            $this->addedBytes += $editSize;
702
703
            if ($edit->getUser()) {
704
                $this->editors[$edit->getUser()->getUsername()]['added'] += $editSize;
705
            }
706
707 4
            // Keep track of edit with max addition.
708
            if (!$this->maxAddition || $editSize > $this->maxAddition->getSize()) {
709 4
                // Keep track of old maxAddition in case we find out the next $edit was reverted
710
                // (and was also a max edit), in which case we'll want to use this one ($edit).
711
                $prevEdits['maxAddition'] = $this->maxAddition;
712 4
713 4
                $this->maxAddition = $edit;
714
            }
715 4
        } elseif ($editSize < 0 && (!$this->maxDeletion || $editSize < $this->maxDeletion->getSize())) {
716 4
            // Keep track of old maxDeletion in case we find out the next edit was reverted
717
            // (and was also a max deletion), in which case we'll want to use this one.
718
            $prevEdits['maxDeletion'] = $this->maxDeletion;
719
720 4
            $this->maxDeletion = $edit;
721
        }
722
723 4
        return $prevEdits;
724
    }
725 4
726
    /**
727 4
     * Get the size of the given edit, based on the previous edit (if present).
728
     * We also don't return the actual edit size if last revision had a length of null.
729
     * This happens when the edit follows other edits that were revision-deleted.
730 4
     * @see T148857 for more information.
731
     * @todo Remove once T101631 is resolved.
732 4
     * @param Edit $edit
733
     * @param Edit[] $prevEdits With 'prev', 'prevSha', 'maxAddition' and 'maxDeletion'.
734
     * @return int
735 4
     */
736
    private function getEditSize(Edit $edit, array $prevEdits): int
737
    {
738
        if ($prevEdits['prev'] && null === $prevEdits['prev']->getLength()) {
0 ignored issues
show
introduced by
The condition null === $prevEdits['prev']->getLength() is always false.
Loading history...
739
            return 0;
740
        } else {
741
            return $edit->getSize();
742
        }
743
    }
744
745
    /**
746
     * Update counts of automated tool usage for the given edit.
747
     * @param Edit $edit
748 4
     */
749
    private function updateToolCounts(Edit $edit): void
750 4
    {
751
        $automatedTool = $edit->getTool($this->container);
752
753 4
        if (false === $automatedTool) {
754
            // Nothing to do.
755
            return;
756
        }
757
758
        $editYear = $edit->getYear();
759
        $editMonth = $edit->getMonth();
760
761 4
        $this->automatedCount++;
762
        $this->yearMonthCounts[$editYear]['automated']++;
763 4
        $this->yearMonthCounts[$editYear]['months'][$editMonth]['automated']++;
764
765 4
        if (!isset($this->tools[$automatedTool['name']])) {
766
            $this->tools[$automatedTool['name']] = [
767 4
                'count' => 1,
768
                'link' => $automatedTool['link'],
769
            ];
770 4
        } else {
771 4
            $this->tools[$automatedTool['name']]['count']++;
772
        }
773 4
    }
774 4
775 4
    /**
776
     * Update various counts for the year and month of the given edit.
777 4
     * @param Edit $edit
778 4
     */
779 4
    private function updateYearMonthCounts(Edit $edit): void
780 4
    {
781
        $editYear = $edit->getYear();
782
        $editMonth = $edit->getMonth();
783
784
        // Fill in the blank arrays for the year and 12 months if needed.
785 4
        if (!isset($this->yearMonthCounts[$editYear])) {
786
            $this->addYearMonthCountEntry($edit);
787
        }
788
789
        // Increment year and month counts for all edits
790
        $this->yearMonthCounts[$editYear]['all']++;
791 4
        $this->yearMonthCounts[$editYear]['months'][$editMonth]['all']++;
792
        // This will ultimately be the size of the page by the end of the year
793 4
        $this->yearMonthCounts[$editYear]['size'] = (int) $edit->getLength();
794 4
795
        // Keep track of which month had the most edits
796
        $editsThisMonth = $this->yearMonthCounts[$editYear]['months'][$editMonth]['all'];
797 4
        if ($editsThisMonth > $this->maxEditsPerMonth) {
798 4
            $this->maxEditsPerMonth = $editsThisMonth;
799
        }
800
    }
801
802 4
    /**
803 4
     * Add a new entry to $this->yearMonthCounts for the given year,
804
     * with blank values for each month. This called during self::parseHistory().
805 4
     * @param Edit $edit
806
     */
807
    private function addYearMonthCountEntry(Edit $edit): void
808 4
    {
809 4
        $this->yearLabels[] = $this->i18n->dateFormat($edit->getTimestamp(), 'yyyy');
810 4
        $editYear = $edit->getYear();
811
812 4
        // Beginning of the month at 00:00:00.
813
        $firstEditTime = mktime(0, 0, 0, (int)$this->firstEdit->getMonth(), 1, (int)$this->firstEdit->getYear());
814
815
        $this->yearMonthCounts[$editYear] = [
816
            'all' => 0,
817
            'minor' => 0,
818
            'anon' => 0,
819 4
            'automated' => 0,
820
            'size' => 0, // Keep track of the size by the end of the year.
821 4
            'events' => [],
822 4
            'months' => [],
823
        ];
824
825 4
        for ($i = 1; $i <= 12; $i++) {
826
            $timeObj = mktime(0, 0, 0, $i, 1, (int)$editYear);
827 4
828
            // Don't show zeros for months before the first edit or after the current month.
829
            if ($timeObj < $firstEditTime || $timeObj > $this->getLastDay()) {
830
                continue;
831
            }
832
833
            $this->monthLabels[] = $this->i18n->dateFormat($timeObj, 'yyyy-MM');
834
            $this->yearMonthCounts[$editYear]['months'][sprintf('%02d', $i)] = [
835
                'all' => 0,
836
                'minor' => 0,
837 4
                'anon' => 0,
838 4
                'automated' => 0,
839
            ];
840
        }
841 4
    }
842 4
843
    /**
844
     * Update the counts of anon and minor edits for year, month, and user of the given edit.
845 4
     * @param Edit $edit
846 4
     */
847
    private function updateAnonMinorCounts(Edit $edit): void
848
    {
849
        $editYear = $edit->getYear();
850
        $editMonth = $edit->getMonth();
851
852
        // If anonymous, increase counts
853 4
        if ($edit->isAnon()) {
854
            $this->anonCount++;
855
            $this->yearMonthCounts[$editYear]['anon']++;
856
            $this->yearMonthCounts[$editYear]['months'][$editMonth]['anon']++;
857
        }
858
859 4
        // If minor edit, increase counts
860
        if ($edit->isMinor()) {
861 4
            $this->minorCount++;
862 4
            $this->yearMonthCounts[$editYear]['minor']++;
863
            $this->yearMonthCounts[$editYear]['months'][$editMonth]['minor']++;
864
        }
865 4
    }
866 4
867 4
    /**
868 4
     * Update various counts for the user of the given edit.
869
     * @param Edit $edit
870
     */
871
    private function updateUserCounts(Edit $edit): void
872 4
    {
873 4
        if (!$edit->getUser()) {
874 4
            return;
875 4
        }
876
877 4
        $username = $edit->getUser()->getUsername();
878
879
        // Initialize various user stats if needed.
880
        if (!isset($this->editors[$username])) {
881
            $this->editors[$username] = [
882
                'all' => 0,
883 4
                'minor' => 0,
884
                'minorPercentage' => 0,
885 4
                'first' => $edit->getTimestamp(),
886
                'firstId' => $edit->getId(),
887
                'last' => null,
888
                'atbe' => null,
889 4
                'added' => 0,
890
            ];
891
        }
892 4
893 4
        // Increment user counts
894 4
        $this->editors[$username]['all']++;
895 4
        $this->editors[$username]['last'] = $edit->getTimestamp();
896 4
        $this->editors[$username]['lastId'] = $edit->getId();
897 4
898 4
        // Increment minor counts for this user
899
        if ($edit->isMinor()) {
900
            $this->editors[$username]['minor']++;
901 4
        }
902
    }
903
904
    /**
905
     * Increment "edits per <time>" counts based on the given edit.
906 4
     * @param Edit $edit
907 4
     */
908 4
    private function updateCountHistory(Edit $edit): void
909
    {
910
        $editTimestamp = $edit->getTimestamp();
911 4
912 4
        if ($editTimestamp > new DateTime('-1 day')) {
913
            $this->countHistory['day']++;
914 4
        }
915
        if ($editTimestamp > new DateTime('-1 week')) {
916
            $this->countHistory['week']++;
917
        }
918
        if ($editTimestamp > new DateTime('-1 month')) {
919
            $this->countHistory['month']++;
920 4
        }
921
        if ($editTimestamp > new DateTime('-1 year')) {
922 4
            $this->countHistory['year']++;
923
        }
924 4
    }
925
926
    /**
927 4
     * Query for log events during each year of the article's history, and set the results in $this->yearMonthCounts.
928
     */
929
    private function setLogsEvents(): void
930 4
    {
931
        $logData = $this->getRepository()->getLogEvents(
0 ignored issues
show
Bug introduced by
The method getLogEvents() does not exist on AppBundle\Repository\Repository. It seems like you code against a sub-type of AppBundle\Repository\Repository such as AppBundle\Repository\ArticleInfoRepository. ( Ignorable by Annotation )

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

931
        $logData = $this->getRepository()->/** @scrutinizer ignore-call */ getLogEvents(
Loading history...
932
            $this->page,
933 4
            $this->start,
934
            $this->end
935
        );
936 4
937
        foreach ($logData as $event) {
938
            $time = strtotime($event['timestamp']);
939
            $year = date('Y', $time);
940
941 1
            if (!isset($this->yearMonthCounts[$year])) {
942
                break;
943 1
            }
944 1
945 1
            $yearEvents = $this->yearMonthCounts[$year]['events'];
946 1
947
            // Convert log type value to i18n key.
948
            switch ($event['log_type']) {
949 1
                case 'protect':
950 1
                    $action = 'protections';
951 1
                    break;
952
                case 'delete':
953 1
                    $action = 'deletions';
954
                    break;
955
                case 'move':
956
                    $action = 'moves';
957 1
                    break;
958
                // count pending-changes protections along with normal protections.
959
                case 'stable':
960 1
                    $action = 'protections';
961 1
                    break;
962 1
            }
963 1
964 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...
965 1
                $yearEvents[$action] = 1;
966 1
            } else {
967
                $yearEvents[$action]++;
968
            }
969
970
            $this->yearMonthCounts[$year]['events'] = $yearEvents;
971
        }
972
    }
973
974
    /**
975
     * Set statistics about the top 10 editors by added text and number of edits.
976 1
     * This is ran *after* parseHistory() since we need the grand totals first.
977 1
     * Various stats are also set for each editor in $this->editors to be used in the charts.
978
     */
979
    private function doPostPrecessing(): void
980
    {
981
        $topTenCount = $counter = 0;
982 1
        $topTenEditorsByEdits = [];
983
984 1
        foreach ($this->editors as $editor => $info) {
985
            // Count how many users are in the top 10% by number of edits, excluding bots.
986
            if ($counter < 10 && !in_array($editor, array_keys($this->bots))) {
987
                $topTenCount += $info['all'];
988
                $counter++;
989
990
                // To be used in the Top Ten charts.
991 4
                $topTenEditorsByEdits[] = [
992
                    'label' => $editor,
993 4
                    'value' => $info['all'],
994 4
                ];
995
            }
996 4
997
            // Compute the percentage of minor edits the user made.
998 4
            $this->editors[$editor]['minorPercentage'] = $info['all']
999 4
                ? ($info['minor'] / $info['all']) * 100
1000 4
                : 0;
1001
1002
            if ($info['all'] > 1) {
1003 4
                // Number of seconds/days between first and last edit.
1004 4
                $secs = $info['last']->getTimestamp() - $info['first']->getTimestamp();
1005 4
                $days = $secs / (60 * 60 * 24);
1006
1007
                // Average time between edits (in days).
1008
                $this->editors[$editor]['atbe'] = round($days / $info['all'], 1);
1009
            }
1010 4
        }
1011 4
1012
        // Loop through again and add percentages.
1013
        $this->topTenEditorsByEdits = array_map(function ($editor) use ($topTenCount) {
1014 4
            $editor['percentage'] = 100 * ($editor['value'] / $topTenCount);
1015
            return $editor;
1016 4
        }, $topTenEditorsByEdits);
1017 4
1018
        $this->topTenEditorsByAdded = $this->getTopTenByAdded();
1019
1020 4
        $this->topTenCount = $topTenCount;
1021
    }
1022
1023
    /**
1024
     * Get the top ten editors by added text.
1025
     * @return array With keys 'label', 'value' and 'percentage', ready to be used by the pieChart Twig helper.
1026 4
     */
1027 4
    private function getTopTenByAdded(): array
1028 4
    {
1029
        // First sort editors array by the amount of text they added.
1030 4
        $topTenEditorsByAdded = $this->editors;
1031
        uasort($topTenEditorsByAdded, function ($a, $b) {
1032 4
            if ($a['added'] === $b['added']) {
1033 4
                return 0;
1034
            }
1035
            return $a['added'] > $b['added'] ? -1 : 1;
1036
        });
1037
1038
        // Slice to the top 10.
1039 4
        $topTenEditorsByAdded = array_keys(array_slice($topTenEditorsByAdded, 0, 10, true));
1040
1041
         // Get the sum of added text so that we can add in percentages.
1042 4
         $topTenTotalAdded = array_sum(array_map(function ($editor) {
1043
             return $this->editors[$editor]['added'];
1044 4
         }, $topTenEditorsByAdded));
1045 4
1046
        // Then build a new array of top 10 editors by added text in the data structure needed for the chart.
1047 4
        return array_map(function ($editor) use ($topTenTotalAdded) {
1048 4
            $added = $this->editors[$editor]['added'];
1049
            return [
1050
                'label' => $editor,
1051 4
                'value' => $added,
1052
                'percentage' => 0 === $this->addedBytes
1053
                    ? 0
1054
                    : 100 * ($added / $topTenTotalAdded),
1055 4
            ];
1056 4
        }, $topTenEditorsByAdded);
1057
    }
1058
1059
    /**
1060 4
     * Get the number of times the page has been viewed in the given timeframe. If the ArticleInfo instance has a
1061
     * date range, it is used instead of the value of the $latest parameter.
1062 4
     * @param  int $latest Last N days.
1063 4
     * @return int
1064 4
     */
1065
    public function getPageviews(int $latest): int
1066 4
    {
1067
        if (!$this->hasDateRange()) {
1068 4
            return $this->page->getLastPageviews($latest);
1069
        }
1070
1071
        $daterange = $this->getDateParams();
1072
        return $this->page->getPageviews($daterange['start'], $daterange['end']);
1073
    }
1074
}
1075