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

Editor   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Coupling/Cohesion

Dependencies 2

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 11
cbo 2
dl 0
loc 54
ccs 23
cts 23
cp 1
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A contains() 0 15 4
A containsCount() 0 15 4
A replace() 0 19 3
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
}