Passed
Pull Request — master (#90)
by Domenico
03:06
created

Xliff20::tagOpen()   C

Complexity

Conditions 17
Paths 74

Size

Total Lines 80
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 17
eloc 29
nc 74
nop 3
dl 0
loc 80
rs 5.2166
c 1
b 0
f 0

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: 17:51
7
 *
8
 */
9
10
namespace Matecat\XliffParser\XliffReplacer;
11
12
use Matecat\XliffParser\Utils\Strings;
13
14
class Xliff20 extends AbstractXliffReplacer {
15
16
    /**
17
     * @var int
18
     */
19
    private int $mdaGroupCounter = 0;
20
21
    /**
22
     * @var array
23
     */
24
    protected array $nodesToBuffer = [
25
            'source',
26
            'mda:metadata',
27
            'memsource:additionalTagData',
28
            'originalData',
29
            'note'
30
    ];
31
32
    /**
33
     * @inheritDoc
34
     */
35
    protected function tagOpen( $parser, string $name, array $attr ) {
36
37
        $this->handleOpenUnit( $name, $attr );
38
39
        if ( 'mda:metadata' === $name ) {
40
            $this->unitContainsMda = true;
41
        }
42
43
        $this->checkSetInTarget( $name );
44
45
        // open buffer
46
        $this->setInBuffer( $name );
47
48
        // check if we are inside a <target>, obviously this happen only if there are targets inside the trans-unit
49
        // <target> must be stripped to be replaced, so this check avoids <target> reconstruction
50
        if ( !$this->inTarget ) {
51
52
            $tag = '';
53
54
            //
55
            // ============================================
56
            // only for Xliff 2.*
57
            // ============================================
58
            //
59
            // In xliff v2 we MUST add <mda:metadata> BEFORE <notes>/<originalData>/<segment>/<ignorable>
60
            //
61
            // As documentation says, <unit> contains:
62
            //
63
            // - elements from other namespaces, OPTIONAL
64
            // - Zero or one <notes> elements followed by
65
            // - Zero or one <originalData> element followed by
66
            // - One or more <segment> or <ignorable> elements in any order.
67
            //
68
            // For more info please refer to:
69
            //
70
            // http://docs.oasis-open.org/xliff/xliff-core/v2.0/os/xliff-core-v2.0-os.html#unit
71
            //
72
            if (
73
                    ( $name === 'notes' || $name === 'originalData' || $name === 'segment' || $name === 'ignorable' ) &&
74
                    $this->unitContainsMda === false &&
75
                    !empty( $this->transUnits[ $this->currentTransUnitId ] ) &&
76
                    !$this->hasWrittenCounts
77
            ) {
78
                // we need to update counts here
79
                $this->updateCounts();
80
                $this->hasWrittenCounts = true;
81
                $tag                    .= $this->getWordCountGroupForXliffV2();
82
                $this->unitContainsMda  = true;
83
            }
84
85
            // construct tag
86
            $tag .= "<$name ";
87
88
            foreach ( $attr as $k => $v ) {
89
                //normal tag flux, put attributes in it but skip for translation state and set the right value for the attribute
90
                if ( $k != 'state' ) {
91
                    $tag .= "$k=\"$v\" ";
92
                }
93
            }
94
95
            $seg = $this->getCurrentSegment();
96
97
            if ( $name === $this->tuTagName and !empty( $seg ) and isset( $seg[ 'sid' ] ) ) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
98
99
                // add `mtc:segment-id` to xliff v.2*
100
                if ( strpos( $tag, 'mtc:segment-id' ) === false ) {
101
                    $tag .= "mtc:segment-id=\"{$seg[ 'sid' ]}\" ";
102
                }
103
104
            }
105
106
            // replace state for xliff v2
107
            if ( 'segment' === $name ) { // add state to segment in Xliff v2
108
                [ $stateProp, ] = StatusToStateAttribute::getState( $seg[ 'status' ], $this->xliffVersion );
109
                $tag .= $stateProp;
110
            }
111
112
            $tag = $this->handleOpenXliffTag( $name, $attr, $tag );
113
114
            $this->checkForSelfClosedTagAndFlush( $parser, $tag );
115
116
        }
117
118
    }
119
120
    /**
121
     * @param string $name
122
     * @param array  $attr
123
     * @param string $tag
124
     *
125
     * @return string
126
     */
127
    protected function handleOpenXliffTag( string $name, array $attr, string $tag ): string {
128
        $tag = parent::handleOpenXliffTag( $name, $attr, $tag );
129
        // add oasis xliff 20 namespace
130
        if ( $name === 'xliff' && !array_key_exists( 'xmlns:mda', $attr ) ) {
131
            $tag .= 'xmlns:mda="urn:oasis:names:tc:xliff:metadata:2.0"';
132
        }
133
134
        return $tag;
135
    }
136
137
    /**
138
     * @inheritDoc
139
     */
140
    protected function tagClose( $parser, string $name ) {
141
        $tag = '';
142
143
        /**
144
         * if is a tag within <target> or
145
         * if it is an empty tag, do not add closing tag because we have already closed it in
146
         *
147
         * self::tagOpen method
148
         */
149
        if ( !$this->isEmpty ) {
150
151
            if ( !$this->inTarget ) {
152
                $tag = "</$name>";
153
            }
154
155
            if ( 'target' == $name ) {
156
157
                if ( isset( $this->transUnits[ $this->currentTransUnitId ] ) && $this->currentTransUnitIsTranslatable !== 'no' ) {
158
159
                    $seg = $this->getCurrentSegment();
160
161
                    // update counts
162
                    if ( !$this->hasWrittenCounts && !empty( $seg ) ) {
163
                        $this->updateSegmentCounts( $seg );
164
                    }
165
166
                    // delete translations so the prepareSegment
167
                    // will put source content in target tag
168
                    if ( $this->sourceInTarget ) {
169
                        $seg[ 'translation' ] = '';
170
                        $this->resetCounts();
171
                    }
172
173
                    // append $translation
174
                    $translation = $this->prepareTranslation( $seg );
175
176
                    //append translation
177
                    $tag = "<target>$translation</target>";
178
179
                }
180
181
                // signal we are leaving a target
182
                $this->targetWasWritten = true;
183
                $this->inTarget         = false;
184
                $this->postProcAndFlush( $this->outputFP, $tag, true );
185
186
            } elseif ( in_array( $name, $this->nodesToBuffer ) ) { // we are closing a critical CDATA section
187
188
                $this->bufferIsActive = false;
189
190
                // only for Xliff 2.*
191
                // write here <mda:metaGroup> and <mda:meta> if already present in the <unit>
192
                if ( 'mda:metadata' === $name && $this->unitContainsMda && !$this->hasWrittenCounts ) {
193
194
                    // we need to update counts here
195
                    $this->updateCounts();
196
                    $this->hasWrittenCounts = true;
197
198
                    $tag = $this->CDATABuffer;
199
                    $tag .= $this->getWordCountGroupForXliffV2( false );
200
                    $tag .= "    </mda:metadata>";
201
202
                } else {
203
                    $tag = $this->CDATABuffer . "</$name>";
204
                }
205
206
                $this->CDATABuffer = "";
207
208
                //flush to the pointer
209
                $this->postProcAndFlush( $this->outputFP, $tag );
210
211
            } elseif ( 'segment' === $name ) {
212
213
                // only for Xliff 2.*
214
                // if segment has no <target> add it BEFORE </segment>
215
                if ( !$this->targetWasWritten ) {
216
217
                    $seg = $this->getCurrentSegment();
218
219
                    if ( isset( $seg[ 'translation' ] ) ) {
220
221
                        $translation = $this->prepareTranslation( $seg );
222
                        // replace the tag
223
                        $tag = "<target>$translation</target>";
224
225
                        $tag .= '</segment>';
226
227
                    }
228
229
                }
230
231
                // update segmentPositionInTu
232
                $this->segmentInUnitPosition++;
233
234
                $this->postProcAndFlush( $this->outputFP, $tag );
235
236
                // we are leaving <segment>, reset $segmentHasTarget
237
                $this->targetWasWritten = false;
238
239
            } elseif ( $this->bufferIsActive ) { // this is a tag ( <g | <mrk ) inside a seg or seg-source tag
240
                $this->CDATABuffer .= "</$name>";
241
                // Do NOT Flush
242
            } else { //generic tag closure do Nothing
243
                // flush to pointer
244
                $this->postProcAndFlush( $this->outputFP, $tag );
245
            }
246
        } else {
247
            //ok, nothing to be done; reset flag for next coming tag
248
            $this->isEmpty = false;
249
        }
250
251
        // check if we are leaving a <trans-unit> (xliff v1.*) or <unit> (xliff v2.*)
252
        if ( $this->tuTagName === $name ) {
253
            $this->currentTransUnitIsTranslatable = null;
254
            $this->inTU                           = false;
255
            $this->unitContainsMda                = false;
256
            $this->hasWrittenCounts               = false;
257
258
            $this->resetCounts();
259
        }
260
    }
261
262
    /**
263
     * Update counts
264
     */
265
    private function updateCounts() {
266
267
        $seg = $this->getCurrentSegment();
268
        if ( !empty( $seg ) ) {
269
            $this->updateSegmentCounts( $seg );
270
        }
271
272
    }
273
274
    /**
275
     * @param bool $withMetadataTag
276
     *
277
     * @return string
278
     */
279
    private function getWordCountGroupForXliffV2( bool $withMetadataTag = true ): string {
280
281
        $this->mdaGroupCounter++;
282
        $segments_count_array = $this->counts[ 'segments_count_array' ];
283
284
        $tag = '';
285
286
        if ( $withMetadataTag === true ) {
287
            $tag .= '<mda:metadata>';
288
        }
289
290
        $index = 0;
291
        foreach ( $segments_count_array as $segments_count_item ) {
292
293
            $id = 'word_count_tu[' . $this->currentTransUnitId . '][' . $index . ']';
294
            $index++;
295
296
            $tag .= "    <mda:metaGroup id=\"" . $id . "\" category=\"row_xml_attribute\">
297
                                <mda:meta type=\"x-matecat-raw\">" . $segments_count_item[ 'raw_word_count' ] . "</mda:meta>
298
                                <mda:meta type=\"x-matecat-weighted\">" . $segments_count_item[ 'eq_word_count' ] . "</mda:meta>
299
                            </mda:metaGroup>";
300
        }
301
302
        if ( $withMetadataTag === true ) {
303
            $tag .= '</mda:metadata>';
304
        }
305
306
        return $tag;
307
308
    }
309
310
    /**
311
     * prepare segment tagging for xliff insertion
312
     *
313
     * @param array $seg
314
     *
315
     * @return string
316
     */
317
    protected function prepareTranslation( array $seg ): string {
318
319
        $segment     = Strings::removeDangerousChars( $seg [ 'segment' ] );
320
        $translation = Strings::removeDangerousChars( $seg [ 'translation' ] );
321
        $dataRefMap  = ( isset( $seg[ 'data_ref_map' ] ) ) ? Strings::jsonToArray( $seg[ 'data_ref_map' ] ) : [];
322
323
        if ( $seg [ 'translation' ] == '' ) {
324
            $translation = $segment;
325
        } else {
326
            if ( $this->callback instanceof XliffReplacerCallbackInterface ) {
327
                $error = ( !empty( $seg[ 'error' ] ) ) ? $seg[ 'error' ] : null;
328
                if ( $this->callback->thereAreErrors( $seg[ 'sid' ], $segment, $translation, $dataRefMap, $error ) ) {
329
                    $translation = '|||UNTRANSLATED_CONTENT_START|||' . $segment . '|||UNTRANSLATED_CONTENT_END|||';
330
                }
331
            }
332
        }
333
334
        return $translation;
335
336
    }
337
338
}