Passed
Push — 1.0.x ( 3a2c37...ccae28 )
by Julien
14:07 queued 06:59
created

Slug::cleanString()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 6
c 0
b 0
f 0
nc 1
nop 2
dl 0
loc 11
ccs 7
cts 7
cp 1
crap 1
rs 10
1
<?php
2
3
/**
4
 * This file is part of the Zemit Framework.
5
 *
6
 * (c) Zemit Team <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE.txt
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Zemit\Support;
13
14
use Transliterator;
15
16
class Slug
17
{
18
    /**
19
     * Creates a slug to be used for pretty URLs
20
     */
21 1
    public static function generate(string $string, array $replace = [], string $delimiter = '-'): string
22
    {
23
        // Save the old locale and set the new locale to UTF-8
24 1
        $oldLocale = setlocale(LC_ALL, '0');
25 1
        setlocale(LC_ALL, 'en_US.UTF-8');
26 1
        if (!empty($replace)) {
27 1
            $string = str_replace(array_keys($replace), array_values($replace), $string);
28
        }
29 1
        $transliterator = Transliterator::create('Any-Latin; Latin-ASCII');
30 1
        $string = $transliterator->transliterate((string)mb_convert_encoding(htmlspecialchars_decode($string), 'UTF-8', 'auto'));
31 1
        self::restoreLocale($oldLocale);
32 1
        return self::cleanString($string, $delimiter);
33
    }
34
    
35
    /**
36
     * Revert back to the old locale
37
     */
38 1
    private static function restoreLocale(string $oldLocale): void
39
    {
40 1
        if ((stripos($oldLocale, '=') > 0)) {
41
            parse_str(str_replace(';', '&', $oldLocale), $locales);
42
            $oldLocale = array_values($locales);
43
        }
44 1
        setlocale(LC_ALL, $oldLocale);
45
    }
46
    
47
    /**
48
     * Replace non-letter or non-digits by -
49
     * Trim trailing -
50
     */
51 1
    public static function cleanString(string $string, string $delimiter): string
52
    {
53
        // replace non letter or non digits by -
54 1
        $string = preg_replace('#[^\pL\d]+#u', '-', $string);
55
        
56
        // Trim trailing -
57 1
        $string = trim($string, '-');
58 1
        $clean = preg_replace('~[^-\w]+~', '', $string);
59 1
        $clean = strtolower($clean);
60 1
        $clean = preg_replace('#[\/_|+ -]+#', $delimiter, $clean);
61 1
        return trim($clean, $delimiter);
62
    }
63
}
64