Passed
Push — master ( c6a496...f5104b )
by Domenico
03:00
created

Xliff12::tagClose()   C

Complexity

Conditions 12
Paths 34

Size

Total Lines 81
Code Lines 37

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 12
eloc 37
c 1
b 0
f 0
nc 34
nop 2
dl 0
loc 81
rs 6.9666

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * @author hashashiyyin [email protected] / [email protected]
5
 * Date: 02/08/24
6
 * Time: 11:45
7
 *
8
 */
9
10
namespace Matecat\XliffParser\XliffReplacer;
11
12
use Matecat\XliffParser\Utils\Strings;
13
14
class Xliff12 extends AbstractXliffReplacer {
15
16
    /**
17
     * @var array
18
     */
19
    protected array $nodesToBuffer = [
20
            'source',
21
            'seg-source',
22
            'note',
23
            'context-group'
24
    ];
25
26
    /**
27
     * @var string
28
     */
29
    protected string $tuTagName = 'trans-unit';
30
31
    /**
32
     * @var string
33
     */
34
    protected string $alternativeMatchesTag = 'alt-trans';
35
36
    /**
37
     * @var string
38
     */
39
    protected string $namespace             = "mtc";       // Custom namespace
40
41
    /**
42
     * @inheritDoc
43
     */
44
    protected function tagOpen( $parser, string $name, array $attr ) {
45
46
        $this->handleOpenUnit( $name, $attr );
47
48
        $this->trySetAltTrans( $name );;
49
        $this->checkSetInTarget( $name );
50
51
        // open buffer
52
        $this->setInBuffer( $name );
53
54
        // check if we are inside a <target>, obviously this happen only if there are targets inside the trans-unit
55
        // <target> must be stripped to be replaced, so this check avoids <target> reconstruction
56
        if ( !$this->inTarget ) {
57
58
            $tag = '';
59
60
            // construct tag
61
            $tag .= "<$name ";
62
63
            foreach ( $attr as $k => $v ) {
64
65
                //if tag name is file, we must replace the target-language attribute
66
                if ( $name === 'file' && $k === 'target-language' && !empty( $this->targetLang ) ) {
67
                    //replace Target language with job language provided from constructor
68
                    $tag .= "$k=\"$this->targetLang\" ";
69
                } else {
70
                    $tag .= "$k=\"$v\" ";
71
                }
72
73
            }
74
75
            $seg = $this->getCurrentSegment();
76
77
            if ( $name === $this->tuTagName && !empty( $seg ) && isset( $seg[ 'sid' ] ) ) {
78
79
                // add `help-id` to xliff v.1*
80
                if ( strpos( $tag, 'help-id' ) === false ) {
81
                    if ( !empty( $seg[ 'sid' ] ) ) {
82
                        $tag .= "help-id=\"{$seg[ 'sid' ]}\" ";
83
                    }
84
                }
85
86
            }
87
88
            $tag = $this->handleOpenXliffTag( $name, $attr, $tag );
89
90
            $this->checkForSelfClosedTagAndFlush( $parser, $tag );
91
92
        }
93
94
    }
95
96
97
    /**
98
     * @inheritDoc
99
     */
100
    protected function tagClose( $parser, string $name ) {
101
        $tag = '';
102
103
        /**
104
         * if is a tag within <target> or
105
         * if it is an empty tag, do not add closing tag because we have already closed it in
106
         *
107
         * self::tagOpen method
108
         */
109
        if ( !$this->isEmpty ) {
110
111
            if ( !$this->inTarget ) {
112
                $tag = "</$name>";
113
            }
114
115
            if ( 'target' == $name && !$this->inAltTrans ) {
116
117
                if ( isset( $this->transUnits[ $this->currentTransUnitId ] ) ) {
118
119
                    // get translation of current segment, by indirect indexing: id -> positional index -> segment
120
                    // actually there may be more than one segment to that ID if there are two mrk of the same source segment
121
                    $tag = $this->rebuildTarget();
122
123
                }
124
125
                $this->targetWasWritten = true;
126
                // signal we are leaving a target
127
                $this->inTarget = false;
128
                $this->postProcAndFlush( $this->outputFP, $tag, true );
129
130
            } elseif ( in_array( $name, $this->nodesToBuffer ) ) { // we are closing a critical CDATA section
131
132
                $this->bufferIsActive = false;
133
                $tag                  = $this->CDATABuffer . "</$name>";
134
                $this->CDATABuffer    = "";
135
136
                //flush to the pointer
137
                $this->postProcAndFlush( $this->outputFP, $tag );
138
139
            } elseif ( $name === $this->tuTagName ) {
140
141
                $tag = "";
142
143
                // handling </trans-unit> closure
144
                if ( !$this->targetWasWritten ) {
145
146
                    if ( isset( $this->transUnits[ $this->currentTransUnitId ] ) ) {
147
                        $tag = $this->rebuildTarget();
148
                    } else {
149
                        $tag = $this->createTargetTag( "", "" );
150
                    }
151
152
                }
153
154
                $tag                    .= "</$this->tuTagName>";
155
                $this->targetWasWritten = false;
156
                $this->postProcAndFlush( $this->outputFP, $tag );
157
158
            } elseif ( $this->bufferIsActive ) { // this is a tag ( <g | <mrk ) inside a seg or seg-source tag
159
                $this->CDATABuffer .= "</$name>";
160
                // Do NOT Flush
161
            } else { //generic tag closure do Nothing
162
                // flush to pointer
163
                $this->postProcAndFlush( $this->outputFP, $tag );
164
            }
165
166
        } else {
167
            //ok, nothing to be done; reset flag for next coming tag
168
            $this->isEmpty = false;
169
        }
170
171
        // try to signal that we are leaving a target
172
        $this->tryUnsetAltTrans( $name );
173
174
        // check if we are leaving a <trans-unit> (xliff v1.*) or <unit> (xliff v2.*)
175
        if ( $this->tuTagName === $name ) {
176
            $this->currentTransUnitIsTranslatable = null;
177
            $this->inTU                           = false;
178
            $this->hasWrittenCounts               = false;
179
180
            $this->resetCounts();
181
        }
182
    }
183
184
    /**
185
     * prepare segment tagging for xliff insertion
186
     *
187
     * @param array  $seg
188
     * @param string $transUnitTranslation
189
     *
190
     * @return string
191
     */
192
    protected function prepareTranslation( array $seg, string $transUnitTranslation = "" ): string {
193
194
        $segment     = Strings::removeDangerousChars( $seg [ 'segment' ] );
195
        $translation = Strings::removeDangerousChars( $seg [ 'translation' ] );
196
197
        if ( $seg [ 'translation' ] == '' ) {
198
            $translation = $segment;
199
        } else {
200
            if ( $this->callback instanceof XliffReplacerCallbackInterface ) {
201
                $error = ( !empty( $seg[ 'error' ] ) ) ? $seg[ 'error' ] : null;
202
                if ( $this->callback->thereAreErrors( $seg[ 'sid' ], $segment, $translation, [], $error ) ) {
203
                    $translation = '|||UNTRANSLATED_CONTENT_START|||' . $segment . '|||UNTRANSLATED_CONTENT_END|||';
204
                }
205
            }
206
        }
207
208
        $transUnitTranslation .= $seg[ 'prev_tags' ] . $this->rebuildMarks( $seg, $translation ) . ltrim( $seg[ 'succ_tags' ] );
209
210
        return $transUnitTranslation;
211
    }
212
213
    protected function rebuildMarks( array $seg, string $translation ): string {
214
215
        if ( $seg[ 'mrk_id' ] !== null && $seg[ 'mrk_id' ] != '' ) {
216
            $translation = "<mrk mid=\"" . $seg[ 'mrk_id' ] . "\" mtype=\"seg\">" . $seg[ 'mrk_prev_tags' ] . $translation . $seg[ 'mrk_succ_tags' ] . "</mrk>";
217
        }
218
219
        return $translation;
220
221
    }
222
223
    /**
224
     * This function creates a <target>
225
     *
226
     * @param string $translation
227
     * @param string $stateProp
228
     *
229
     * @return string
230
     */
231
    private function createTargetTag( string $translation, string $stateProp ): string {
232
        $targetLang = ' xml:lang="' . $this->targetLang . '"';
233
        $tag        = "<target $targetLang $stateProp>$translation</target>";
234
        $tag        .= "\n<count-group name=\"$this->currentTransUnitId\"><count count-type=\"x-matecat-raw\">" . $this->counts[ 'raw_word_count' ] . "</count><count count-type=\"x-matecat-weighted\">" . $this->counts[ 'eq_word_count' ] . '</count></count-group>';
235
236
        return $tag;
237
238
    }
239
240
    protected function rebuildTarget(): string {
241
242
        // init translation and state
243
        $translation  = '';
244
        $lastMrkState = null;
245
        $stateProp    = '';
246
247
        // we must reset the lastMrkId found because this is a new segment.
248
        $lastMrkId = -1;
249
250
        foreach ( $this->lastTransUnit as $pos => $seg ) {
251
252
            /*
253
             * This routine works to respect the positional orders of markers.
254
             * In every cycle we check if the mrk of the segment is below or equal the last one.
255
             * When this is true, means that the mrk id belongs to the next segment with the same internal_id
256
             * so we MUST stop to apply markers and translations
257
             * and stop to add eq_word_count
258
             *
259
             * Begin:
260
             * pre-assign zero to the new mrk if this is the first one ( in this segment )
261
             * If it is null leave it NULL
262
             */
263
            if ( (int)$seg[ "mrk_id" ] < 0 && $seg[ "mrk_id" ] !== null ) {
264
                $seg[ "mrk_id" ] = 0;
265
            }
266
267
            /*
268
             * WARNING:
269
             * For those seg-source that doesn't have a mrk ( having a mrk id === null )
270
             * ( null <= -1 ) === true
271
             * so, cast to int
272
             */
273
            if ( (int)$seg[ "mrk_id" ] <= $lastMrkId ) {
274
                break;
275
            }
276
277
            // update counts
278
            if ( !empty( $seg ) ) {
279
                $this->updateSegmentCounts( $seg );
280
            }
281
282
            // delete translations so the prepareSegment
283
            // will put source content in target tag
284
            if ( $this->sourceInTarget ) {
285
                $seg[ 'translation' ] = '';
286
                $this->resetCounts();
287
            }
288
289
            // append $translation
290
            $translation = $this->prepareTranslation( $seg, $translation );
291
292
            $lastMrkId = $seg[ "mrk_id" ];
293
294
            [ $stateProp, $lastMrkState ] = StatusToStateAttribute::getState( $this->xliffVersion, $seg[ 'status' ], $lastMrkState );
295
296
        }
297
298
        //append translation
299
        return $this->createTargetTag( $translation, $stateProp );
300
301
    }
302
303
}