Spinner   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 35
Duplicated Lines 0 %

Test Coverage

Coverage 94.74%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 19
c 1
b 0
f 0
dl 0
loc 35
ccs 18
cts 19
cp 0.9474
rs 10
wmc 6

3 Methods

Rating   Name   Duplication   Size   Complexity  
A replaceOnce() 0 10 2
A removeExtraSpaces() 0 3 1
A spin() 0 14 3
1
<?php
2
3
namespace PiedWeb\TextSpinner;
4
5
class Spinner
6
{
7 3
    public static function spin(string $text): string
8
    {
9 3
        if (! preg_match('/\{(.*)\}/si', $text)) {
10 3
            return self::removeExtraSpaces($text);
11
        } else {
12 3
            preg_match_all('/\{([^{}]*)\}/si', $text, $matches);
13 3
            $occur = count($matches[1]);
14 3
            for ($i = 0; $i < $occur; ++$i) {
15 3
                $words = explode('|', $matches[1][$i]);
16 3
                shuffle($words);
17 3
                $text = self::replaceOnce($matches[0][$i], $words[0], $text);
18
            }
19
20 3
            return    self::spin($text);
21
        }
22
    }
23
24 3
    protected static function replaceOnce(string $search, string $replace, string $subject): string
25
    {
26 3
        $firstChar = strpos($subject, $search);
27 3
        if (false !== $firstChar) {
28 3
            $beforeStr = substr($subject, 0, $firstChar);
29 3
            $afterStr = substr($subject, $firstChar + strlen($search));
30
31 3
            return $beforeStr.$replace.$afterStr;
32
        } else {
33
            return $subject;
34
        }
35
    }
36
37 3
    protected static function removeExtraSpaces(string $text): string
38
    {
39 3
        return preg_replace('/\s+/', ' ', $text);
40
    }
41
}
42