StringFieldReplaceStrategy::canReplace()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
crap 1
1
<?php declare(strict_types=1);
2
3
/**
4
 * @copyright   (c) 2017-present brian ridley
5
 * @author      brian ridley <[email protected]>
6
 * @license     http://opensource.org/licenses/MIT MIT
7
 */
8
9
namespace ptlis\GrepDb\Replace\Strategy;
10
11
use ptlis\GrepDb\Metadata\MySQL\ColumnMetadata;
12
use ptlis\GrepDb\Replace\Result\FieldReplaceResult;
13
14
/**
15
 * Perform replacement on a simple string.
16
 */
17
final class StringFieldReplaceStrategy implements FieldReplaceStrategy
18
{
19
    /**
20
     * @inheritdoc
21
     */
22 2
    public function canReplace(string $searchTerm, string $subject): bool
23
    {
24 2
        return substr_count($subject, $searchTerm) > 0;
25
    }
26
27
    /**
28
     * @inheritdoc
29
     */
30 3
    public function replace(
31
        ColumnMetadata $columnMetadata,
32
        string $searchTerm,
33
        string $replaceTerm,
34
        string $subject
35
    ): FieldReplaceResult {
36 3
        $matchCount = substr_count($subject, $searchTerm);
37 3
        $errorList = [];
38 3
        if (0 === $matchCount) {
39 1
            $errorList[] = 'Search term "' . $searchTerm . '" not found in subject "' . $subject . '"';
40
        }
41
42 3
        return new FieldReplaceResult(
43 3
            $columnMetadata,
44 3
            $matchCount,
45 3
            $errorList,
46 3
            $subject,
47 3
            str_replace($searchTerm, $replaceTerm, $subject)
48
        );
49
    }
50
}