Spinner::replaceOnce()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2.0116

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 7
c 1
b 0
f 0
nc 2
nop 3
dl 0
loc 10
ccs 6
cts 7
cp 0.8571
crap 2.0116
rs 10
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