Test Failed
Pull Request — master (#372)
by MusikAnimal
12:26 queued 01:27
created

AutomatedEditsHelper::isAutomated()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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

179
                $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

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