Completed
Push — master ( 444c1c...3a5730 )
by brian
01:56
created

Editor::containsCount()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 15
ccs 7
cts 7
cp 1
rs 9.7666
c 0
b 0
f 0
cc 4
nc 3
nop 2
crap 4
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\SerializedDataEditor;
10
11
use ptlis\SerializedDataEditor\Tokenizer\Token;
12
use ptlis\SerializedDataEditor\Tokenizer\Tokenizer;
13
14
/**
15
 * Allows editing of serialized datastructures.
16
 */
17
final class Editor
18
{
19 2
    public function contains(
20
        string $serializedData,
21
        string $searchTerm
22
    ): bool {
23 2
        $tokenizer = new Tokenizer();
24
25 2
        $containsString = false;
26 2
        foreach ($tokenizer->tokenize($serializedData) as $token) {
27 2
            if (Token::STRING === $token->getType() && strstr($token->getValue(), $searchTerm)) {
28 2
                $containsString = true;
29
            }
30
        }
31
32 2
        return $containsString;
33
    }
34
35 2
    public function containsCount(
36
        string $serializedData,
37
        string $searchTerm
38
    ): int {
39 2
        $tokenizer = new Tokenizer();
40
41 2
        $count = 0;
42 2
        foreach ($tokenizer->tokenize($serializedData) as $token) {
43 2
            if (Token::STRING === $token->getType() && strstr($token->getValue(), $searchTerm)) {
44 2
                $count += substr_count($token->getValue(), $searchTerm);
45
            }
46
        }
47
48 2
        return $count;
49
    }
50
51 1
    public function replace(
52
        string $serializedData,
53
        string $searchTerm,
54
        string $replaceTerm
55
    ): string {
56 1
        $tokenizer = new Tokenizer();
57
58 1
        $tokenList = $tokenizer->tokenize($serializedData);
59 1
        foreach ($tokenList as $index => $token) {
60 1
            if (Token::STRING === $token->getType()) {
61 1
                $tokenList[$index] = new Token(
62 1
                    Token::STRING,
63 1
                    str_replace($searchTerm, $replaceTerm, $token->getValue())
64
                );
65
            }
66
        }
67
68 1
        return join('', $tokenList);
69
    }
70
}