Passed
Push — master ( c28222...9253d7 )
by Sebastian
02:41
created

replaceContent()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 4
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 8
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Mailcode;
6
7
use AppUtils\ConvertHelper;
8
9
trait Mailcode_Traits_Commands_ProtectedContent
10
{
11
    protected static $protectedCounter = 0;
12
    protected $protectedContent = '';
13
    protected $protectedPlaceholder = '';
14
15
    public function getContent() : string
16
    {
17
        return $this->protectedContent;
18
    }
19
20
    public function getContentPlaceholder() : string
21
    {
22
        return $this->protectedPlaceholder;
23
    }
24
25
    public function protectContent(string $string, Mailcode_Parser_Safeguard_Placeholder $open, Mailcode_Parser_Safeguard_Placeholder $end) : string
26
    {
27
        if(!$end->getCommand() instanceof Mailcode_Commands_Command_End)
28
        {
29
            throw new Mailcode_Exception(
30
                'Invalid commands nesting',
31
                'The code command was not closed with an end command.',
32
                Mailcode_Interfaces_Commands_ProtectedContent::ERROR_INVALID_NESTING_NO_END
33
            );
34
        }
35
36
        $start = strpos($string, $open->getReplacementText()) + $open->getReplacementLength();
37
        $end = strpos($string, $end->getReplacementText());
38
39
        $content = substr($string, $start, ($end-$start));
40
41
        /**
42
        echo PHP_EOL;
43
        print_r(array(
44
            'string' => $string,
45
            'start' => $start,
46
            'end' => $end,
47
            'content' => $content
48
        ));
49
        echo PHP_EOL;
50
         */
51
52
        return $this->replaceContent($string, $content);
53
    }
54
55
    protected function replaceContent(string $string, string $content) : string
56
    {
57
        self::$protectedCounter++;
58
59
        $this->protectedContent = trim($content);
60
        $this->protectedPlaceholder = '__CT'.self::$protectedCounter.'__';
61
62
        return str_replace($content, $this->protectedPlaceholder, $string);
63
    }
64
65
    public function restoreContent($string) : string
66
    {
67
        return str_replace($this->protectedPlaceholder, $this->protectedContent, $string);
68
    }
69
}
70