Passed
Push — master ( 6a210c...1c40ea )
by MusikAnimal
07:35
created

AutomatedEditsHelper::getTools()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 42
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 4.0406

Importance

Changes 0
Metric Value
cc 4
eloc 21
nc 3
nop 1
dl 0
loc 42
rs 9.584
c 0
b 0
f 0
ccs 19
cts 22
cp 0.8636
crap 4.0406
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 Symfony\Component\DependencyInjection\ContainerInterface;
12
13
/**
14
 * Helper class for fetching semi-automated definitions.
15
 */
16
class AutomatedEditsHelper extends HelperBase
17
{
18
    /** @var array The list of tools that are considered reverting. */
19
    protected $revertTools = [];
20
21
    /** @var array The list of tool names and their regexes/tags. */
22
    protected $tools = [];
23
24
    /**
25
     * AutomatedEditsHelper constructor.
26
     * @param ContainerInterface $container
27
     */
28 14
    public function __construct(ContainerInterface $container)
29
    {
30 14
        $this->container = $container;
31 14
    }
32
33
    /**
34
     * Get the tool that matched the given edit summary.
35
     * This only works for tools defined with regular expressions, not tags.
36
     * @param string $summary Edit summary
37
     * @param Project $project
38
     * @return string[]|false Tool entry including key for 'name', or false if nothing was found
39
     */
40 9
    public function getTool(string $summary, Project $project)
41
    {
42 9
        foreach ($this->getTools($project) as $tool => $values) {
43 9
            if (isset($values['regex']) && preg_match('/'.$values['regex'].'/', $summary)) {
44 9
                return array_merge([
45 9
                    'name' => $tool,
46 9
                ], $values);
47
            }
48
        }
49
50 7
        return false;
51
    }
52
53
    /**
54
     * Was the edit (semi-)automated, based on the edit summary?
55
     * This only works for tools defined with regular expressions, not tags.
56
     * @param string $summary Edit summary
57
     * @param Project $project
58
     * @return bool
59
     */
60 1
    public function isAutomated(string $summary, Project $project): bool
61
    {
62 1
        return (bool)$this->getTool($summary, $project);
63
    }
64
65
    /**
66
     * Get list of automated tools and their associated info for the given project.
67
     * This defaults to the 'default_project' if entries for the given project are not found.
68
     * @param Project $project
69
     * @return array Each tool with the tool name as the key and 'link', 'regex' and/or 'tag' as the subarray keys.
70
     */
71 14
    public function getTools(Project $project): array
72
    {
73 14
        $projectDomain = $project->getDomain();
74
75 14
        if (isset($this->tools[$projectDomain])) {
76 7
            return $this->tools[$projectDomain];
77
        }
78
79
        // Load the semi-automated edit types.
80 14
        $tools = $this->container->getParameter('automated_tools');
81
82 14
        if (isset($tools[$projectDomain])) {
83 14
            $localRules = $tools[$projectDomain];
84
        } else {
85
            $localRules = [];
86
        }
87
88 14
        $langRules = $tools[$project->getLang()] ?? [];
89
90
        // Per-wiki rules have priority, followed by language-specific and global.
91 14
        $globalWithLangRules = $this->mergeRules($tools['global'], $langRules);
92
93 14
        $this->tools[$projectDomain] = $this->mergeRules(
94 14
            $globalWithLangRules,
95 14
            $localRules
96
        );
97
98
        // Finally, populate the 'label' with the tool name, if a label doesn't already exist.
99 14
        array_walk($this->tools[$projectDomain], function (&$data, $tool): void {
100 14
            $data['label'] = $data['label'] ?? $tool;
101
102
            // 'namespaces' should be an array of ints.
103 14
            $data['namespaces'] = $data['namespaces'] ?? [];
104 14
            if (isset($data['namespace'])) {
105
                $data['namespaces'][] = $data['namespace'];
106
                unset($data['namespace']);
107
            }
108 14
        });
109
110 14
        uksort($this->tools[$projectDomain], 'strcasecmp');
111
112 14
        return $this->tools[$projectDomain];
113
    }
114
115
    /**
116
     * Merges the given rule sets, giving priority to the local set. Regex is concatenated, not overridden.
117
     * @param string[] $globalRules The global rule set.
118
     * @param string[] $localRules The rule set for the local wiki.
119
     * @return string[] Merged rules.
120
     */
121 14
    private function mergeRules(array $globalRules, array $localRules): array
122
    {
123
        // Initial set, including just the global rules.
124 14
        $tools = $globalRules;
125
126
        // Loop through local rules and override/merge as necessary.
127 14
        foreach ($localRules as $tool => $rules) {
128 14
            $newRules = $rules;
129
130 14
            if (isset($globalRules[$tool])) {
131
                // Order within array_merge is important, so that local rules get priority.
132 14
                $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

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

132
                $newRules = array_merge($globalRules[$tool], /** @scrutinizer ignore-type */ $rules);
Loading history...
133
            }
134
135
            // Regex should be merged, not overridden.
136 14
            if (isset($rules['regex']) && isset($globalRules[$tool]['regex'])) {
137 1
                $newRules['regex'] = implode('|', [
138 1
                    $rules['regex'],
139 1
                    $globalRules[$tool]['regex'],
140
                ]);
141
            }
142
143 14
            $tools[$tool] = $newRules;
144
        }
145
146 14
        return $tools;
147
    }
148
149
    /**
150
     * Get only tools that are used to revert edits.
151
     * Revert detection happens only by testing against a regular expression, and not by checking tags.
152
     * @param Project $project
153
     * @return string[][] Each tool with the tool name as the key,
154
     *   and 'link' and 'regex' as the subarray keys.
155
     */
156 7
    public function getRevertTools(Project $project): array
157
    {
158 7
        $projectDomain = $project->getDomain();
159
160 7
        if (isset($this->revertTools[$projectDomain])) {
161 7
            return $this->revertTools[$projectDomain];
162
        }
163
164 7
        $revertEntries = array_filter(
165 7
            $this->getTools($project),
166 7
            function ($tool) {
167 7
                return isset($tool['revert']);
168 7
            }
169
        );
170
171
        // If 'revert' is set to `true`, then use 'regex' as the regular expression,
172
        //  otherwise 'revert' is assumed to be the regex string.
173 7
        $this->revertTools[$projectDomain] = array_map(function ($revertTool) {
174
            return [
175 7
                'link' => $revertTool['link'],
176 7
                'regex' => true === $revertTool['revert'] ? $revertTool['regex'] : $revertTool['revert'],
177
            ];
178 7
        }, $revertEntries);
179
180 7
        return $this->revertTools[$projectDomain];
181
    }
182
183
    /**
184
     * Was the edit a revert, based on the edit summary?
185
     * This only works for tools defined with regular expressions, not tags.
186
     * @param string|null $summary Edit summary. Can be null for instance for suppressed edits.
187
     * @param Project $project
188
     * @return bool
189
     */
190 7
    public function isRevert(?string $summary, Project $project): bool
191
    {
192 7
        foreach (array_values($this->getRevertTools($project)) as $values) {
193 7
            if (preg_match('/'.$values['regex'].'/', (string)$summary)) {
194 7
                return true;
195
            }
196
        }
197
198 7
        return false;
199
    }
200
}
201