Passed
Push — master ( 88fd01...d897a2 )
by MusikAnimal
11:18
created

AutomatedEditsHelper::isAutomated()   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 2
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 AutomatedEditsHelper class.
4
 */
5
6
declare(strict_types = 1);
7
8
namespace AppBundle\Helper;
9
10
use AppBundle\Model\Project;
11
use DateInterval;
12
use Psr\Cache\CacheItemPoolInterface;
13
use Symfony\Component\DependencyInjection\ContainerInterface;
14
15
/**
16
 * Helper class for fetching semi-automated definitions.
17
 */
18
class AutomatedEditsHelper
19
{
20
    /** @var array The list of tools that are considered reverting. */
21
    protected $revertTools = [];
22
23
    /** @var array The list of tool names and their regexes/tags. */
24
    protected $tools = [];
25
26
    /** @var ContainerInterface */
27
    private $container;
28
29
    /** @var CacheItemPoolInterface */
30
    protected $cache;
31
32
    /**
33
     * AutomatedEditsHelper constructor.
34
     * @param ContainerInterface $container
35
     */
36 14
    public function __construct(ContainerInterface $container)
37
    {
38 14
        $this->container = $container;
39 14
        $this->cache = $container->get('cache.app');
40 14
    }
41
42
    /**
43
     * Get the tool that matched the given edit summary.
44
     * This only works for tools defined with regular expressions, not tags.
45
     * @param string $summary Edit summary
46
     * @param Project $project
47
     * @return string[]|false Tool entry including key for 'name', or false if nothing was found
48
     */
49 9
    public function getTool(string $summary, Project $project)
50
    {
51 9
        foreach ($this->getTools($project) as $tool => $values) {
52 9
            if (isset($values['regex']) && preg_match('/'.$values['regex'].'/', $summary)) {
53 9
                return array_merge([
54 9
                    'name' => $tool,
55 9
                ], $values);
56
            }
57
        }
58
59 7
        return false;
60
    }
61
62
    /**
63
     * Was the edit (semi-)automated, based on the edit summary?
64
     * This only works for tools defined with regular expressions, not tags.
65
     * @param string $summary Edit summary
66
     * @param Project $project
67
     * @return bool
68
     */
69 1
    public function isAutomated(string $summary, Project $project): bool
70
    {
71 1
        return (bool)$this->getTool($summary, $project);
72
    }
73
74
    /**
75
     * Fetch the config from https://meta.wikimedia.org/wiki/MediaWiki:XTools-AutoEdits.json
76
     * @param bool $useSandbox Use the sandbox version of the config, located at MediaWiki:XTools-AutoEdits.json/sandbox
77
     * @return array
78
     */
79 14
    public function getConfig(bool $useSandbox = false): array
80
    {
81 14
        $cacheKey = 'autoedits_config';
82 14
        if (!$useSandbox && $this->cache->hasItem($cacheKey)) {
83 13
            return $this->cache->getItem($cacheKey)->get();
84
        }
85
86 1
        $title = 'MediaWiki:XTools-AutoEdits.json' . ($useSandbox ? '/sandbox' : '');
87 1
        $ret = json_decode(file_get_contents(
88 1
            "https://meta.wikimedia.org/w/index.php?action=raw&ctype=application/json&title=$title"
89 1
        ), true);
90
91 1
        if (!$useSandbox) {
92 1
            $cacheItem = $this->cache
93 1
                ->getItem($cacheKey)
94 1
                ->set($ret)
95 1
                ->expiresAfter(new DateInterval('PT20M'));
96 1
            $this->cache->save($cacheItem);
97
        }
98
99 1
        return $ret;
100
    }
101
102
    /**
103
     * Get list of automated tools and their associated info for the given project.
104
     * This defaults to the 'default_project' if entries for the given project are not found.
105
     * @param Project $project
106
     * @param bool $useSandbox Whether to use the /sandbox version for testing (also bypasses caching).
107
     * @return array Each tool with the tool name as the key and 'link', 'regex' and/or 'tag' as the subarray keys.
108
     */
109 14
    public function getTools(Project $project, bool $useSandbox = false): array
110
    {
111 14
        $projectDomain = $project->getDomain();
112
113 14
        if (isset($this->tools[$projectDomain])) {
114 7
            return $this->tools[$projectDomain];
115
        }
116
117
        // Load the semi-automated edit types.
118 14
        $tools = $this->getConfig($useSandbox);
119
120 14
        if (isset($tools[$projectDomain])) {
121 14
            $localRules = $tools[$projectDomain];
122
        } else {
123
            $localRules = [];
124
        }
125
126 14
        $langRules = $tools[$project->getLang()] ?? [];
127
128
        // Per-wiki rules have priority, followed by language-specific and global.
129 14
        $globalWithLangRules = $this->mergeRules($tools['global'], $langRules);
130
131 14
        $this->tools[$projectDomain] = $this->mergeRules(
132 14
            $globalWithLangRules,
133 14
            $localRules
134
        );
135
136
        // Finally, populate the 'label' with the tool name, if a label doesn't already exist.
137 14
        array_walk($this->tools[$projectDomain], function (&$data, $tool): void {
138 14
            $data['label'] = $data['label'] ?? $tool;
139
140
            // 'namespaces' should be an array of ints.
141 14
            $data['namespaces'] = $data['namespaces'] ?? [];
142 14
            if (isset($data['namespace'])) {
143
                $data['namespaces'][] = $data['namespace'];
144
                unset($data['namespace']);
145
            }
146
147
            // 'tags' should be an array of strings.
148 14
            $data['tags'] = $data['tags'] ?? [];
149 14
            if (isset($data['tag'])) {
150
                $data['tags'][] = $data['tag'];
151
                unset($data['tag']);
152
            }
153 14
        });
154
155 14
        uksort($this->tools[$projectDomain], 'strcasecmp');
156
157 14
        return $this->tools[$projectDomain];
158
    }
159
160
    /**
161
     * Merges the given rule sets, giving priority to the local set. Regex is concatenated, not overridden.
162
     * @param string[] $globalRules The global rule set.
163
     * @param string[] $localRules The rule set for the local wiki.
164
     * @return string[] Merged rules.
165
     */
166 14
    private function mergeRules(array $globalRules, array $localRules): array
167
    {
168
        // Initial set, including just the global rules.
169 14
        $tools = $globalRules;
170
171
        // Loop through local rules and override/merge as necessary.
172 14
        foreach ($localRules as $tool => $rules) {
173 14
            $newRules = $rules;
174
175 14
            if (isset($globalRules[$tool])) {
176
                // Order within array_merge is important, so that local rules get priority.
177 14
                $newRules = array_merge($globalRules[$tool], $rules);
0 ignored issues
show
Bug introduced by
$rules of type string is incompatible with the type array|null expected by parameter $array2 of array_merge(). ( Ignorable by Annotation )

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

177
                $newRules = array_merge($globalRules[$tool], /** @scrutinizer ignore-type */ $rules);
Loading history...
Bug introduced by
$globalRules[$tool] of type string is incompatible with the type array expected by parameter $array1 of array_merge(). ( Ignorable by Annotation )

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

177
                $newRules = array_merge(/** @scrutinizer ignore-type */ $globalRules[$tool], $rules);
Loading history...
178
            }
179
180
            // Regex should be merged, not overridden.
181 14
            if (isset($rules['regex']) && isset($globalRules[$tool]['regex'])) {
182 1
                $newRules['regex'] = implode('|', [
183 1
                    $rules['regex'],
184 1
                    $globalRules[$tool]['regex'],
185
                ]);
186
            }
187
188 14
            $tools[$tool] = $newRules;
189
        }
190
191 14
        return $tools;
192
    }
193
194
    /**
195
     * Get only tools that are used to revert edits.
196
     * Revert detection happens only by testing against a regular expression, and not by checking tags.
197
     * @param Project $project
198
     * @return string[][] Each tool with the tool name as the key,
199
     *   and 'link' and 'regex' as the subarray keys.
200
     */
201 7
    public function getRevertTools(Project $project): array
202
    {
203 7
        $projectDomain = $project->getDomain();
204
205 7
        if (isset($this->revertTools[$projectDomain])) {
206 7
            return $this->revertTools[$projectDomain];
207
        }
208
209 7
        $revertEntries = array_filter(
210 7
            $this->getTools($project),
211 7
            function ($tool) {
212 7
                return isset($tool['revert']) && isset($tool['regex']);
213 7
            }
214
        );
215
216
        // If 'revert' is set to `true`, then use 'regex' as the regular expression,
217
        //  otherwise 'revert' is assumed to be the regex string.
218 7
        $this->revertTools[$projectDomain] = array_map(function ($revertTool) {
219
            return [
220 7
                'link' => $revertTool['link'],
221 7
                'regex' => true === $revertTool['revert'] ? $revertTool['regex'] : $revertTool['revert'],
222
            ];
223 7
        }, $revertEntries);
224
225 7
        return $this->revertTools[$projectDomain];
226
    }
227
228
    /**
229
     * Was the edit a revert, based on the edit summary?
230
     * This only works for tools defined with regular expressions, not tags.
231
     * @param string|null $summary Edit summary. Can be null for instance for suppressed edits.
232
     * @param Project $project
233
     * @return bool
234
     */
235 7
    public function isRevert(?string $summary, Project $project): bool
236
    {
237 7
        foreach (array_values($this->getRevertTools($project)) as $values) {
238 7
            if (preg_match('/'.$values['regex'].'/', (string)$summary)) {
239 7
                return true;
240
            }
241
        }
242
243 7
        return false;
244
    }
245
}
246