MateCatCustomPHToOriginalValue::transform()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 5
ccs 3
cts 3
cp 1
crap 1
rs 10
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * @author domenico [email protected] / [email protected]
5
 * Date: 11/01/19
6
 * Time: 15.11
7
 *
8
 */
9
10
namespace Matecat\SubFiltering\Filters;
11
12
use Matecat\SubFiltering\Commons\AbstractHandler;
13
14
class MateCatCustomPHToOriginalValue extends AbstractHandler {
15
16 83
    public function transform( string $segment ): string {
17
18 83
        $segment = $this->restoreOriginalTags( $segment );
19
20 83
        return $this->restoreFilteredContent( $segment );
21
22
    }
23
24
    /**
25
     * This pipeline method is needed to restore x-original content (when an entire tag is replaced with a PH)
26
     *
27
     * @param string $segment
28
     *
29
     * @return string
30
     */
31 83
    private function restoreOriginalTags( string $segment ): string {
32
33 83
        preg_match_all( '|<ph id\s*=\s*["\']mtc_[0-9]+["\'] ctype\s*=\s*["\']([^"\']+)["\'] x-orig\s*=\s*["\']([^"\']+)["\'] equiv-text\s*=\s*["\']base64:[^"\']+["\']\s*/>|iU', $segment, $html, PREG_SET_ORDER ); // Ungreedy
34 83
        foreach ( $html as $subfilter_tag ) {
35 9
            $segment = str_replace( $subfilter_tag[ 0 ], base64_decode( $subfilter_tag[ 2 ] ), $segment );
36
        }
37
38 83
        return $segment;
39
40
    }
41
42
    /**
43
     * This pipeline method is needed to restore a filtered block (as PH tag) to its original value.
44
     * It can be everything filtered out: sprintf, html, etc.
45
     *
46
     * @param string $segment
47
     *
48
     * @return string
49
     */
50 83
    private function restoreFilteredContent( string $segment ): string {
51
        // pipeline for restore PH tag of subfiltering to original encoded HTML
52 83
        preg_match_all( '|<ph id\s*=\s*["\']mtc_[0-9]+["\'] ctype\s*=\s*["\']([0-9a-zA-Z\-_]+)["\'] equiv-text\s*=\s*["\']base64:([^"\']+)["\']\s*/>|iU', $segment, $html, PREG_SET_ORDER ); // Ungreedy
53
54 83
        foreach ( $html as $subfilter_tag ) {
55
56
            /*
57
             * This code tries to handle xliff/html tags (encoded) inside an xliff.
58
             */
59 46
            $value   = base64_decode( $subfilter_tag[ 2 ] );
60 46
            $segment = str_replace( $subfilter_tag[ 0 ], $value, $segment );
61
62
        }
63
64 83
        return $segment;
65
    }
66
67
}