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

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

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