Passed
Push — main ( db602c...8b7c2e )
by Paul
06:19
created

SanitizeUserName   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 33
Duplicated Lines 0 %

Test Coverage

Coverage 94.12%

Importance

Changes 3
Bugs 2 Features 0
Metric Value
wmc 5
eloc 16
c 3
b 2
f 0
dl 0
loc 33
ccs 16
cts 17
cp 0.9412
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A sanitizeDisplayName() 0 8 1
A run() 0 14 4
1
<?php
2
3
namespace GeminiLabs\SiteReviews\Modules\Sanitizers;
4
5
class SanitizeUserName extends StringSanitizer
6
{
7 26
    public function run(): string
8
    {
9 26
        $value = $this->sanitizeDisplayName($this->value());
10 26
        if (defined('WP_IMPORTING')) {
11
            return $value;
12
        }
13 26
        if (!empty($value)) {
14 22
            return $value;
15
        }
16 9
        $user = wp_get_current_user();
17 9
        if (!$user->exists()) {
18 9
            return $value;
19
        }
20 2
        return $this->sanitizeDisplayName($user->display_name);
21
    }
22
23
    /**
24
     * \p{L} = any kind of letter from any language.
25
     * \p{M} = any character intended to be combined with another character (e.g. accents, umlauts, enclosing boxes, etc.).
26
     * \p{N} = any kind of numeric character in any script.
27
     * \p{Pf} = any kind of closing quote.
28
     * @see https://www.regular-expressions.info/unicode.html
29
     */
30 26
    protected function sanitizeDisplayName(string $value): string
31
    {
32 26
        $value = wp_strip_all_tags($value);
33 26
        $value = preg_replace('/%([a-fA-F0-9][a-fA-F0-9])/', '', $value); // Remove percent-encoded characters.
34 26
        $value = preg_replace('/&.+?;/', '', $value); // Remove HTML entities.
35 26
        $value = preg_replace('/[^\p{L}\p{M}\p{N}\p{Pf}\'\.\,\- ]/u', '', $value);
36 26
        $value = sanitize_text_field($value); // Remove extra whitespace.
37 26
        return $value;
38
    }
39
}
40