Test Failed
Pull Request — master (#372)
by MusikAnimal
07:01
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
    /**
76 14
     * Fetch the config from https://meta.wikimedia.org/wiki/MediaWiki:XTools-AutoEdits.json
77
     * @param bool $useSandbox
78 14
     * @return array
79 7
     */
80
    public function getConfig(bool $useSandbox = false): array
81
    {
82
        $cacheKey = 'autoedits_config';
83 14
        if (!$useSandbox && $this->cache->hasItem($cacheKey)) {
84
            return $this->cache->getItem($cacheKey)->get();
85 14
        }
86 14
87
        $centralAuthProject = $this->container->getParameter('central_auth_project');
88
        $metaProject = ProjectRepository::getProject($centralAuthProject, $this->container);
89
90
        $title = 'MediaWiki:XTools-AutoEdits.json' . ($useSandbox ? '/sandbox' : '');
91 14
        $ret = json_decode(file_get_contents(
92
            $metaProject->getUrl() . "w/index.php?action=raw&ctype=application/json&title=$title"
93
        ), true);
94 14
95
        if (!$useSandbox) {
96 14
            $cacheItem = $this->cache
97 14
                ->getItem($cacheKey)
98 14
                ->set($ret)
99
                ->expiresAfter(new DateInterval('PT20M'));
100
            $this->cache->save($cacheItem);
101
        }
102 14
103 14
        return $ret;
104
    }
105
106 14
    /**
107 14
     * Get list of automated tools and their associated info for the given project.
108
     * This defaults to the 'default_project' if entries for the given project are not found.
109
     * @param Project $project
110
     * @param bool $useSandbox Whether to use the /sandbox version for testing (also bypasses caching).
111
     * @return array Each tool with the tool name as the key and 'link', 'regex' and/or 'tag' as the subarray keys.
112
     */
113 14
    public function getTools(Project $project, bool $useSandbox = false): array
114 14
    {
115
        $projectDomain = $project->getDomain();
116
117
        if (isset($this->tools[$projectDomain])) {
118 14
            return $this->tools[$projectDomain];
119
        }
120 14
121
        // Load the semi-automated edit types.
122 14
        $tools = $this->getConfig($useSandbox);
123
124
        if (isset($tools[$projectDomain])) {
125
            $localRules = $tools[$projectDomain];
126
        } else {
127
            $localRules = [];
128
        }
129
130
        $langRules = $tools[$project->getLang()] ?? [];
131 14
132
        // Per-wiki rules have priority, followed by language-specific and global.
133
        $globalWithLangRules = $this->mergeRules($tools['global'], $langRules);
134 14
135
        $this->tools[$projectDomain] = $this->mergeRules(
136
            $globalWithLangRules,
137 14
            $localRules
138 14
        );
139
140 14
        // Finally, populate the 'label' with the tool name, if a label doesn't already exist.
141
        array_walk($this->tools[$projectDomain], function (&$data, $tool): void {
142 14
            $data['label'] = $data['label'] ?? $tool;
143
144
            // 'namespaces' should be an array of ints.
145
            $data['namespaces'] = $data['namespaces'] ?? [];
146 14
            if (isset($data['namespace'])) {
147 1
                $data['namespaces'][] = $data['namespace'];
148 1
                unset($data['namespace']);
149 1
            }
150
151
            // 'tags' should be an array of strings.
152
            $data['tags'] = $data['tags'] ?? [];
153 14
            if (isset($data['tag'])) {
154
                $data['tags'][] = $data['tag'];
155
                unset($data['tag']);
156 14
            }
157
        });
158
159
        uksort($this->tools[$projectDomain], 'strcasecmp');
160
161
        return $this->tools[$projectDomain];
162
    }
163
164
    /**
165
     * Merges the given rule sets, giving priority to the local set. Regex is concatenated, not overridden.
166 7
     * @param string[] $globalRules The global rule set.
167
     * @param string[] $localRules The rule set for the local wiki.
168 7
     * @return string[] Merged rules.
169
     */
170 7
    private function mergeRules(array $globalRules, array $localRules): array
171 7
    {
172
        // Initial set, including just the global rules.
173
        $tools = $globalRules;
174 7
175 7
        // Loop through local rules and override/merge as necessary.
176 7
        foreach ($localRules as $tool => $rules) {
177 7
            $newRules = $rules;
178 7
179
            if (isset($globalRules[$tool])) {
180
                // Order within array_merge is important, so that local rules get priority.
181
                $newRules = array_merge($globalRules[$tool], $rules);
0 ignored issues
show
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

181
                $newRules = array_merge(/** @scrutinizer ignore-type */ $globalRules[$tool], $rules);
Loading history...
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

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