forked from pestphp/pest-plugin-profanity
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProfanityAnalyser.php
More file actions
73 lines (61 loc) · 2.16 KB
/
ProfanityAnalyser.php
File metadata and controls
73 lines (61 loc) · 2.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
<?php
declare(strict_types=1);
namespace Pest\Profanity;
/**
* @internal
*/
final class ProfanityAnalyser
{
/**
* Scan a file for profanity
*
* @param array<string> $excludingWords
* @param array<string> $includingWords
* @param array<string>|null $languages
* @return array<int, Error>
*/
public static function analyse(string $file, array $excludingWords = [], array $includingWords = [], $languages = null): array
{
$words = [];
$profanitiesDir = __DIR__.'/Config/profanities';
$errors = [];
if (str_contains($file, '/Config/profanities/')) {
return [];
}
if (($profanitiesFiles = scandir($profanitiesDir)) === false) {
return [];
}
$profanitiesFiles = array_diff($profanitiesFiles, ['.', '..']);
if ($languages) {
foreach ($languages as $lang) {
$specificLanguage = "$profanitiesDir/$lang.php";
if (file_exists($specificLanguage)) {
$words = array_merge(
$words,
include $specificLanguage
);
}
}
} else {
$words = include "$profanitiesDir/en.php";
}
$words = array_merge($words, $includingWords);
$words = array_diff($words, $excludingWords);
$fileContents = (string) file_get_contents($file);
$lines = explode("\n", $fileContents);
$foundProfanity = [];
foreach ($words as $word) {
foreach ($lines as $lineNumber => $line) {
$key = $lineNumber.'-'.$word;
if (preg_match('/(?<!\p{L})'.preg_quote($word, '/').'(?!\p{L})/iu', $line) === 1 && ! isset($foundProfanity[$key])) {
// Skip reporting profanity if the line contains the ignore annotation
if (! str_contains($line, '@pest-ignore-profanity')) {
$errors[] = new Error($file, $lineNumber + 1, $word);
$foundProfanity[$key] = true;
}
}
}
}
return $errors;
}
}