SerializedFieldReplaceStrategy::canReplace()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 5
cts 5
cp 1
rs 9.9332
c 0
b 0
f 0
cc 2
nc 2
nop 2
crap 2
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
use ptlis\SerializedDataEditor\Editor;
14
15
/**
16
 * Perform replacement on a PHP-serialized string.
17
 */
18
final class SerializedFieldReplaceStrategy implements FieldReplaceStrategy
19
{
20
    /**
21
     * @inheritdoc
22
     */
23 3
    public function canReplace(string $searchTerm, string $subject): bool
24
    {
25 3
        $editor = new Editor();
26
27
        try {
28 3
            return $editor->containsCount($subject, $searchTerm) > 0;
29 1
        } catch (\Throwable $e) {
30 1
            return false;
31
        }
32
    }
33
34
    /**
35
     * @inheritdoc
36
     */
37 10
    public function replace(
38
        ColumnMetadata $columnMetadata,
39
        string $searchTerm,
40
        string $replaceTerm,
41
        string $subject
42
    ): FieldReplaceResult {
43 10
        $editor = new Editor();
44
45
        try {
46 10
            $matchCount = $editor->containsCount($subject, $searchTerm);
47 9
            $errorList = [];
48
49 9
            if (0 === $matchCount) {
50 3
                $errorList[] = 'Search term "' . $searchTerm . '" not found in subject "' . $subject . '"';
51
            }
52
53 9
            return new FieldReplaceResult(
54 9
                $columnMetadata,
55 9
                $matchCount,
56 9
                $errorList,
57 9
                $subject,
58 9
                $editor->replace($subject, $searchTerm, $replaceTerm)
59
            );
60 1
        } catch (\Throwable $e) {
61 1
            return new FieldReplaceResult(
62 1
                $columnMetadata,
63 1
                0,
64 1
                ['Failed to deserialize field'],
65 1
                $subject,
66 1
                $subject
67
            );
68
        }
69
    }
70
}