Completed
Pull Request — master (#1673)
by Martin
02:35
created

Inflector::slug()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 11
rs 9.4285
cc 3
eloc 7
nc 3
nop 4
1
<?php
2
3
namespace luya\helpers;
4
5
/**
6
 * Helper methods which can be used for string transformations
7
 *
8
 * Extends the {{yii\helpers\BaseInflector}} class by:
9
 *
10
 * + {{luya\helpers\Inflector::slug()}}
11
 *
12
 * @author Martin Petrasch <[email protected]>
13
 * @since 1.0.0
14
 */
15
class Inflector extends \yii\helpers\BaseInflector
16
{
17
    /**
18
     * From yii/helpers/BaseInflector:
19
     *
20
     * Returns a string with all spaces converted to given replacement,
21
     * non word characters removed and the rest of characters transliterated.
22
     *
23
     * If intl extension isn't available uses fallback that converts latin characters only
24
     * and removes the rest. You may customize characters map via $transliteration property
25
     * of the helper.
26
     *
27
     * @param string $string An arbitrary string to convert
28
     * @param string $replacement The replacement to use for spaces
29
     * @param bool $lowercase whether to return the string in lowercase or not. Defaults to `true`.
30
     * @param bool $transliterate whether to use a transliteration transformation or not. Defaults to `true` (=BaseInflector implementation)
31
     * @return string The converted string.
32
     */
33
    public static function slug($string, $replacement = '-', $lowercase = true, $transliterate = true)
34
    {
35
        if ($transliterate) {
36
            return parent::slug($string, $replacement, $lowercase);
37
        }
38
39
        $string = preg_replace('/[`%\+=\{\}\|\\\.<>\/]+/u', '', $string);
40
        $string = preg_replace('/[=\s—–-]+/u', $replacement, $string);
41
        $string = trim($string, $replacement);
42
        return $lowercase ? strtolower($string) : $string;
43
    }
44
}