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

SanitizeUserName::run()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 4.016

Importance

Changes 3
Bugs 2 Features 0
Metric Value
eloc 9
c 3
b 2
f 0
dl 0
loc 14
ccs 9
cts 10
cp 0.9
rs 9.9666
cc 4
nc 4
nop 0
crap 4.016
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