Passed
Pull Request — master (#97)
by Mauro
03:42
created
src/XliffReplacer/Xliff12.php 1 patch
Spacing   +67 added lines, -67 removed lines patch added patch discarded remove patch
@@ -36,34 +36,34 @@  discard block
 block discarded – undo
36 36
     /**
37 37
      * @var string
38 38
      */
39
-    protected string $namespace = "mtc";       // Custom namespace
39
+    protected string $namespace = "mtc"; // Custom namespace
40 40
 
41 41
     /**
42 42
      * @inheritDoc
43 43
      */
44
-    protected function tagOpen( $parser, string $name, array $attr ) {
44
+    protected function tagOpen($parser, string $name, array $attr) {
45 45
 
46
-        $this->handleOpenUnit( $name, $attr );
46
+        $this->handleOpenUnit($name, $attr);
47 47
 
48
-        $this->trySetAltTrans( $name );;
49
-        $this->checkSetInTarget( $name );
48
+        $this->trySetAltTrans($name); ;
49
+        $this->checkSetInTarget($name);
50 50
 
51 51
         // open buffer
52
-        $this->setInBuffer( $name );
52
+        $this->setInBuffer($name);
53 53
 
54 54
         // check if we are inside a <target>, obviously this happen only if there are targets inside the trans-unit
55 55
         // <target> must be stripped to be replaced, so this check avoids <target> reconstruction
56
-        if ( !$this->inTarget ) {
56
+        if (!$this->inTarget) {
57 57
 
58 58
             $tag = '';
59 59
 
60 60
             // construct tag
61 61
             $tag .= "<$name ";
62 62
 
63
-            foreach ( $attr as $k => $v ) {
63
+            foreach ($attr as $k => $v) {
64 64
 
65 65
                 //if tag name is file, we must replace the target-language attribute
66
-                if ( $name === 'file' && $k === 'target-language' && !empty( $this->targetLang ) ) {
66
+                if ($name === 'file' && $k === 'target-language' && !empty($this->targetLang)) {
67 67
                     //replace Target language with job language provided from constructor
68 68
                     $tag .= "$k=\"$this->targetLang\" ";
69 69
                 } else {
@@ -74,20 +74,20 @@  discard block
 block discarded – undo
74 74
 
75 75
             $seg = $this->getCurrentSegment();
76 76
 
77
-            if ( $name === $this->tuTagName && !empty( $seg ) && isset( $seg[ 'sid' ] ) ) {
77
+            if ($name === $this->tuTagName && !empty($seg) && isset($seg['sid'])) {
78 78
 
79 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' ]}\" ";
80
+                if (strpos($tag, 'help-id') === false) {
81
+                    if (!empty($seg['sid'])) {
82
+                        $tag .= "help-id=\"{$seg['sid']}\" ";
83 83
                     }
84 84
                 }
85 85
 
86 86
             }
87 87
 
88
-            $tag = $this->handleOpenXliffTag( $name, $attr, $tag );
88
+            $tag = $this->handleOpenXliffTag($name, $attr, $tag);
89 89
 
90
-            $this->checkForSelfClosedTagAndFlush( $parser, $tag );
90
+            $this->checkForSelfClosedTagAndFlush($parser, $tag);
91 91
 
92 92
         }
93 93
 
@@ -97,7 +97,7 @@  discard block
 block discarded – undo
97 97
     /**
98 98
      * @inheritDoc
99 99
      */
100
-    protected function tagClose( $parser, string $name ) {
100
+    protected function tagClose($parser, string $name) {
101 101
         $tag = '';
102 102
 
103 103
         /**
@@ -106,23 +106,23 @@  discard block
 block discarded – undo
106 106
          *
107 107
          * self::tagOpen method
108 108
          */
109
-        if ( !$this->isEmpty ) {
109
+        if (!$this->isEmpty) {
110 110
 
111 111
             // write closing tag if is not a target
112 112
             // EXCLUDE the target nodes with currentTransUnitIsTranslatable = 'NO'
113
-            if ( !$this->inTarget and $this->currentTransUnitIsTranslatable !== 'no' ) {
113
+            if (!$this->inTarget and $this->currentTransUnitIsTranslatable !== 'no') {
114 114
                 $tag = "</$name>";
115 115
             }
116 116
 
117
-            if ( 'target' == $name && !$this->inAltTrans ) {
117
+            if ('target' == $name && !$this->inAltTrans) {
118 118
 
119
-                if ( isset( $this->transUnits[ $this->currentTransUnitId ] ) ) {
119
+                if (isset($this->transUnits[$this->currentTransUnitId])) {
120 120
 
121 121
                     // get translation of current segment, by indirect indexing: id -> positional index -> segment
122 122
                     // actually there may be more than one segment to that ID if there are two mrk of the same source segment
123 123
                     $tag = $this->rebuildTarget();
124 124
 
125
-                } elseif( !empty($this->CDATABuffer) and $this->currentTransUnitIsTranslatable === 'no' ) {
125
+                } elseif (!empty($this->CDATABuffer) and $this->currentTransUnitIsTranslatable === 'no') {
126 126
 
127 127
                     // These are target nodes with currentTransUnitIsTranslatable = 'NO'
128 128
                     $this->bufferIsActive = false;
@@ -133,45 +133,45 @@  discard block
 block discarded – undo
133 133
                 $this->targetWasWritten = true;
134 134
                 // signal we are leaving a target
135 135
                 $this->inTarget = false;
136
-                $this->postProcAndFlush( $this->outputFP, $tag, true );
136
+                $this->postProcAndFlush($this->outputFP, $tag, true);
137 137
 
138
-            } elseif ( in_array( $name, $this->nodesToBuffer ) ) { // we are closing a critical CDATA section
138
+            } elseif (in_array($name, $this->nodesToBuffer)) { // we are closing a critical CDATA section
139 139
 
140 140
                 $this->bufferIsActive = false;
141 141
                 $tag                  = $this->CDATABuffer . "</$name>";
142 142
                 $this->CDATABuffer    = "";
143 143
 
144 144
                 //flush to the pointer
145
-                $this->postProcAndFlush( $this->outputFP, $tag, false, $name === 'seg-source' );
145
+                $this->postProcAndFlush($this->outputFP, $tag, false, $name === 'seg-source');
146 146
 
147
-            } elseif ( $name === $this->tuTagName ) {
147
+            } elseif ($name === $this->tuTagName) {
148 148
 
149 149
                 $tag = "";
150 150
 
151 151
                 // handling </trans-unit> closure
152
-                if ( !$this->targetWasWritten ) {
152
+                if (!$this->targetWasWritten) {
153 153
 
154
-                    if ( isset( $this->transUnits[ $this->currentTransUnitId ] ) ) {
154
+                    if (isset($this->transUnits[$this->currentTransUnitId])) {
155 155
                         $tag = $this->rebuildTarget();
156 156
                     } else {
157
-                        $tag = $this->createTargetTag( "", "" );
157
+                        $tag = $this->createTargetTag("", "");
158 158
                     }
159 159
 
160 160
                 }
161 161
 
162
-                $tag                    .= "</$this->tuTagName>";
162
+                $tag .= "</$this->tuTagName>";
163 163
                 $this->targetWasWritten = false;
164
-                $this->postProcAndFlush( $this->outputFP, $tag );
164
+                $this->postProcAndFlush($this->outputFP, $tag);
165 165
 
166
-            } elseif ( $this->bufferIsActive ) { // this is a tag ( <g | <mrk ) inside a seg or seg-source tag
166
+            } elseif ($this->bufferIsActive) { // this is a tag ( <g | <mrk ) inside a seg or seg-source tag
167 167
                 $this->CDATABuffer .= "</$name>";
168 168
                 // Do NOT Flush
169 169
             } else { //generic tag closure do Nothing
170 170
                 // flush to pointer
171
-                $this->postProcAndFlush( $this->outputFP, $tag );
171
+                $this->postProcAndFlush($this->outputFP, $tag);
172 172
             }
173 173
 
174
-        } elseif ( in_array( $name, $this->nodesToBuffer ) ) {
174
+        } elseif (in_array($name, $this->nodesToBuffer)) {
175 175
 
176 176
             $this->isEmpty        = false;
177 177
             $this->bufferIsActive = false;
@@ -179,7 +179,7 @@  discard block
 block discarded – undo
179 179
             $this->CDATABuffer    = "";
180 180
 
181 181
             //flush to the pointer
182
-            $this->postProcAndFlush( $this->outputFP, $tag, false, $name === 'seg-source'  );
182
+            $this->postProcAndFlush($this->outputFP, $tag, false, $name === 'seg-source');
183 183
 
184 184
         } else {
185 185
             //ok, nothing to be done; reset flag for next coming tag
@@ -187,10 +187,10 @@  discard block
 block discarded – undo
187 187
         }
188 188
 
189 189
         // try to signal that we are leaving a target
190
-        $this->tryUnsetAltTrans( $name );
190
+        $this->tryUnsetAltTrans($name);
191 191
 
192 192
         // check if we are leaving a <trans-unit> (xliff v1.*) or <unit> (xliff v2.*)
193
-        if ( $this->tuTagName === $name ) {
193
+        if ($this->tuTagName === $name) {
194 194
             $this->currentTransUnitIsTranslatable = null;
195 195
             $this->inTU                           = false;
196 196
             $this->hasWrittenCounts               = false;
@@ -207,23 +207,23 @@  discard block
 block discarded – undo
207 207
      *
208 208
      * @return string
209 209
      */
210
-    protected function prepareTranslation( array $seg, string $transUnitTranslation = "" ): string {
210
+    protected function prepareTranslation(array $seg, string $transUnitTranslation = ""): string {
211 211
 
212
-        $segment     = Strings::removeDangerousChars( $seg [ 'segment' ] );
213
-        $translation = Strings::removeDangerousChars( $seg [ 'translation' ] );
212
+        $segment     = Strings::removeDangerousChars($seg ['segment']);
213
+        $translation = Strings::removeDangerousChars($seg ['translation']);
214 214
 
215
-        if ( $seg [ 'translation' ] == '' ) {
215
+        if ($seg ['translation'] == '') {
216 216
             $translation = $segment;
217 217
         } else {
218
-            if ( $this->callback instanceof XliffReplacerCallbackInterface ) {
219
-                $error = ( !empty( $seg[ 'error' ] ) ) ? $seg[ 'error' ] : null;
220
-                if ( $this->callback->thereAreErrors( $seg[ 'sid' ], $segment, $translation, [], $error ) ) {
218
+            if ($this->callback instanceof XliffReplacerCallbackInterface) {
219
+                $error = (!empty($seg['error'])) ? $seg['error'] : null;
220
+                if ($this->callback->thereAreErrors($seg['sid'], $segment, $translation, [], $error)) {
221 221
                     $translation = '|||UNTRANSLATED_CONTENT_START|||' . $segment . '|||UNTRANSLATED_CONTENT_END|||';
222 222
                 }
223 223
             }
224 224
         }
225 225
 
226
-        $transUnitTranslation .= $seg[ 'prev_tags' ] . $this->rebuildMarks( $seg, $translation ) . ltrim( $seg[ 'succ_tags' ] );
226
+        $transUnitTranslation .= $seg['prev_tags'] . $this->rebuildMarks($seg, $translation) . ltrim($seg['succ_tags']);
227 227
 
228 228
         return $transUnitTranslation;
229 229
     }
@@ -233,17 +233,17 @@  discard block
 block discarded – undo
233 233
      * @param string $translation
234 234
      * @return string
235 235
      */
236
-    protected function rebuildMarks( array $seg, string $translation ): string {
236
+    protected function rebuildMarks(array $seg, string $translation): string {
237 237
 
238
-        if ( $seg[ 'mrk_id' ] !== null && $seg[ 'mrk_id' ] != '' ) {
239
-            $translation = "<mrk mid=\"" . $seg[ 'mrk_id' ] . "\" mtype=\"seg\">" . $seg[ 'mrk_prev_tags' ] . $translation . $seg[ 'mrk_succ_tags' ] . "</mrk>";
238
+        if ($seg['mrk_id'] !== null && $seg['mrk_id'] != '') {
239
+            $translation = "<mrk mid=\"" . $seg['mrk_id'] . "\" mtype=\"seg\">" . $seg['mrk_prev_tags'] . $translation . $seg['mrk_succ_tags'] . "</mrk>";
240 240
 
241 241
             // check if there is a trailing space in the map of this trans unit
242
-            if(
242
+            if (
243 243
                 isset($this->mrkTagsMap[$this->currentTransUnitId]) and
244
-                isset($this->mrkTagsMap[$this->currentTransUnitId][$seg[ 'mrk_id' ]])
245
-            ){
246
-                $translation .= $this->mrkTagsMap[$this->currentTransUnitId][$seg[ 'mrk_id' ]];
244
+                isset($this->mrkTagsMap[$this->currentTransUnitId][$seg['mrk_id']])
245
+            ) {
246
+                $translation .= $this->mrkTagsMap[$this->currentTransUnitId][$seg['mrk_id']];
247 247
             }
248 248
         }
249 249
 
@@ -259,10 +259,10 @@  discard block
 block discarded – undo
259 259
      *
260 260
      * @return string
261 261
      */
262
-    protected function createTargetTag( string $translation, string $stateProp ): string {
262
+    protected function createTargetTag(string $translation, string $stateProp): string {
263 263
         $targetLang = ' xml:lang="' . $this->targetLang . '"';
264 264
         $tag        = "<target $targetLang $stateProp>$translation</target>";
265
-        $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>';
265
+        $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>';
266 266
 
267 267
         return $tag;
268 268
 
@@ -278,7 +278,7 @@  discard block
 block discarded – undo
278 278
         // we must reset the lastMrkId found because this is a new segment.
279 279
         $lastMrkId = -1;
280 280
 
281
-        foreach ( $this->lastTransUnit as $pos => $seg ) {
281
+        foreach ($this->lastTransUnit as $pos => $seg) {
282 282
 
283 283
             /*
284 284
              * This routine works to respect the positional orders of markers.
@@ -291,8 +291,8 @@  discard block
 block discarded – undo
291 291
              * pre-assign zero to the new mrk if this is the first one ( in this segment )
292 292
              * If it is null leave it NULL
293 293
              */
294
-            if ( (int)$seg[ "mrk_id" ] < 0 && $seg[ "mrk_id" ] !== null ) {
295
-                $seg[ "mrk_id" ] = 0;
294
+            if ((int)$seg["mrk_id"] < 0 && $seg["mrk_id"] !== null) {
295
+                $seg["mrk_id"] = 0;
296 296
             }
297 297
 
298 298
             /*
@@ -301,39 +301,39 @@  discard block
 block discarded – undo
301 301
              * ( null <= -1 ) === true
302 302
              * so, cast to int
303 303
              */
304
-            if ( (int)$seg[ "mrk_id" ] <= $lastMrkId ) {
304
+            if ((int)$seg["mrk_id"] <= $lastMrkId) {
305 305
                 break;
306 306
             }
307 307
 
308 308
             // update counts
309
-            if ( !empty( $seg ) ) {
310
-                $this->updateSegmentCounts( $seg );
309
+            if (!empty($seg)) {
310
+                $this->updateSegmentCounts($seg);
311 311
             }
312 312
 
313 313
             // delete translations so the prepareSegment
314 314
             // will put source content in target tag
315
-            if ( $this->sourceInTarget ) {
316
-                $seg[ 'translation' ] = '';
315
+            if ($this->sourceInTarget) {
316
+                $seg['translation'] = '';
317 317
                 $this->resetCounts();
318 318
             }
319 319
 
320 320
             // append $translation
321
-            $translation = $this->prepareTranslation( $seg, $translation );
321
+            $translation = $this->prepareTranslation($seg, $translation);
322 322
 
323
-            $lastMrkId = $seg[ "mrk_id" ];
323
+            $lastMrkId = $seg["mrk_id"];
324 324
 
325
-            [ $stateProp, $lastMrkState ] = StatusToStateAttribute::getState( $this->xliffVersion, $seg[ 'status' ], $lastMrkState );
325
+            [$stateProp, $lastMrkState] = StatusToStateAttribute::getState($this->xliffVersion, $seg['status'], $lastMrkState);
326 326
 
327 327
         }
328 328
 
329 329
         //append translation
330
-        return $this->createTargetTag( $translation, $stateProp );
330
+        return $this->createTargetTag($translation, $stateProp);
331 331
 
332 332
     }
333 333
 
334 334
     protected function getCurrentSegment(): array {
335
-        if ( $this->currentTransUnitIsTranslatable !== 'no' && isset( $this->transUnits[ $this->currentTransUnitId ] ) ) {
336
-            return $this->segments[ $this->transUnits[ $this->currentTransUnitId ][ 0 ] ]; // TODO try to understand why here is needed to override the method and set 0 index hardcoded
335
+        if ($this->currentTransUnitIsTranslatable !== 'no' && isset($this->transUnits[$this->currentTransUnitId])) {
336
+            return $this->segments[$this->transUnits[$this->currentTransUnitId][0]]; // TODO try to understand why here is needed to override the method and set 0 index hardcoded
337 337
         }
338 338
 
339 339
         return [];
Please login to merge, or discard this patch.
src/XliffReplacer/Xliff20.php 1 patch
Spacing   +68 added lines, -68 removed lines patch added patch discarded remove patch
@@ -20,7 +20,7 @@  discard block
 block discarded – undo
20 20
     /**
21 21
      * @var bool
22 22
      */
23
-    protected bool $unitContainsMda = false;   // check if <unit> already contains a <mda:metadata> (forXliff v 2.*)
23
+    protected bool $unitContainsMda = false; // check if <unit> already contains a <mda:metadata> (forXliff v 2.*)
24 24
 
25 25
     /**
26 26
      * @var string
@@ -35,7 +35,7 @@  discard block
 block discarded – undo
35 35
     /**
36 36
      * @var string
37 37
      */
38
-    protected string $namespace = "matecat";       // Custom namespace
38
+    protected string $namespace = "matecat"; // Custom namespace
39 39
 
40 40
     /**
41 41
      * @var array
@@ -51,23 +51,23 @@  discard block
 block discarded – undo
51 51
     /**
52 52
      * @inheritDoc
53 53
      */
54
-    protected function tagOpen( $parser, string $name, array $attr ) {
54
+    protected function tagOpen($parser, string $name, array $attr) {
55 55
 
56
-        $this->handleOpenUnit( $name, $attr );
56
+        $this->handleOpenUnit($name, $attr);
57 57
 
58
-        if ( 'mda:metadata' === $name ) {
58
+        if ('mda:metadata' === $name) {
59 59
             $this->unitContainsMda = true;
60 60
         }
61 61
 
62
-        $this->trySetAltTrans( $name );;
63
-        $this->checkSetInTarget( $name );
62
+        $this->trySetAltTrans($name); ;
63
+        $this->checkSetInTarget($name);
64 64
 
65 65
         // open buffer
66
-        $this->setInBuffer( $name );
66
+        $this->setInBuffer($name);
67 67
 
68 68
         // check if we are inside a <target>, obviously this happen only if there are targets inside the trans-unit
69 69
         // <target> must be stripped to be replaced, so this check avoids <target> reconstruction
70
-        if ( !$this->inTarget ) {
70
+        if (!$this->inTarget) {
71 71
 
72 72
             $tag = '';
73 73
 
@@ -89,48 +89,48 @@  discard block
 block discarded – undo
89 89
             //
90 90
             // http://docs.oasis-open.org/xliff/xliff-core/v2.0/os/xliff-core-v2.0-os.html#unit
91 91
             //
92
-            if ( in_array( $name, [ 'notes', 'originalData', 'segment', 'ignorable' ] ) &&
92
+            if (in_array($name, ['notes', 'originalData', 'segment', 'ignorable']) &&
93 93
                     $this->unitContainsMda === false &&
94
-                    !empty( $this->transUnits[ $this->currentTransUnitId ] ) &&
94
+                    !empty($this->transUnits[$this->currentTransUnitId]) &&
95 95
                     !$this->hasWrittenCounts
96 96
             ) {
97 97
                 // we need to update counts here
98 98
                 $this->updateCounts();
99 99
                 $this->hasWrittenCounts = true;
100
-                $tag                    .= $this->getWordCountGroupForXliffV2();
100
+                $tag .= $this->getWordCountGroupForXliffV2();
101 101
                 $this->unitContainsMda  = true;
102 102
             }
103 103
 
104 104
             // construct tag
105 105
             $tag .= "<$name ";
106 106
 
107
-            foreach ( $attr as $k => $v ) {
107
+            foreach ($attr as $k => $v) {
108 108
                 //normal tag flux, put attributes in it but skip for translation state and set the right value for the attribute
109
-                if ( $k != 'state' ) {
109
+                if ($k != 'state') {
110 110
                     $tag .= "$k=\"$v\" ";
111 111
                 }
112 112
             }
113 113
 
114 114
             $seg = $this->getCurrentSegment();
115 115
 
116
-            if ( $name === $this->tuTagName && !empty( $seg ) && isset( $seg[ 'sid' ] ) ) {
116
+            if ($name === $this->tuTagName && !empty($seg) && isset($seg['sid'])) {
117 117
 
118 118
                 // add `matecat:segment-id` to xliff v.2*
119
-                if ( strpos( $tag, 'matecat:segment-id' ) === false ) {
120
-                    $tag .= "matecat:segment-id=\"{$seg[ 'sid' ]}\" ";
119
+                if (strpos($tag, 'matecat:segment-id') === false) {
120
+                    $tag .= "matecat:segment-id=\"{$seg['sid']}\" ";
121 121
                 }
122 122
 
123 123
             }
124 124
 
125 125
             // replace state for xliff v2
126
-            if ( 'segment' === $name ) { // add state to segment in Xliff v2
127
-                [ $stateProp, ] = StatusToStateAttribute::getState( $this->xliffVersion, $seg[ 'status' ] );
126
+            if ('segment' === $name) { // add state to segment in Xliff v2
127
+                [$stateProp, ] = StatusToStateAttribute::getState($this->xliffVersion, $seg['status']);
128 128
                 $tag .= $stateProp;
129 129
             }
130 130
 
131
-            $tag = $this->handleOpenXliffTag( $name, $attr, $tag );
131
+            $tag = $this->handleOpenXliffTag($name, $attr, $tag);
132 132
 
133
-            $this->checkForSelfClosedTagAndFlush( $parser, $tag );
133
+            $this->checkForSelfClosedTagAndFlush($parser, $tag);
134 134
 
135 135
         }
136 136
 
@@ -143,10 +143,10 @@  discard block
 block discarded – undo
143 143
      *
144 144
      * @return string
145 145
      */
146
-    protected function handleOpenXliffTag( string $name, array $attr, string $tag ): string {
147
-        $tag = parent::handleOpenXliffTag( $name, $attr, $tag );
146
+    protected function handleOpenXliffTag(string $name, array $attr, string $tag): string {
147
+        $tag = parent::handleOpenXliffTag($name, $attr, $tag);
148 148
         // add oasis xliff 20 namespace
149
-        if ( $name === 'xliff' && !array_key_exists( 'xmlns:mda', $attr ) ) {
149
+        if ($name === 'xliff' && !array_key_exists('xmlns:mda', $attr)) {
150 150
             $tag .= 'xmlns:mda="urn:oasis:names:tc:xliff:metadata:2.0"';
151 151
         }
152 152
 
@@ -156,7 +156,7 @@  discard block
 block discarded – undo
156 156
     /**
157 157
      * @inheritDoc
158 158
      */
159
-    protected function tagClose( $parser, string $name ) {
159
+    protected function tagClose($parser, string $name) {
160 160
         $tag = '';
161 161
 
162 162
         /**
@@ -165,39 +165,39 @@  discard block
 block discarded – undo
165 165
          *
166 166
          * self::tagOpen method
167 167
          */
168
-        if ( !$this->isEmpty ) {
168
+        if (!$this->isEmpty) {
169 169
 
170 170
             // write closing tag if is not a target
171 171
             // EXCLUDE the target nodes with currentTransUnitIsTranslatable = 'NO'
172
-            if ( !$this->inTarget and $this->currentTransUnitIsTranslatable !== 'no' ) {
172
+            if (!$this->inTarget and $this->currentTransUnitIsTranslatable !== 'no') {
173 173
                 $tag = "</$name>";
174 174
             }
175 175
 
176
-            if ( 'target' == $name && !$this->inAltTrans ) {
176
+            if ('target' == $name && !$this->inAltTrans) {
177 177
 
178
-                if ( isset( $this->transUnits[ $this->currentTransUnitId ] ) ) {
178
+                if (isset($this->transUnits[$this->currentTransUnitId])) {
179 179
 
180 180
                     $seg = $this->getCurrentSegment();
181 181
 
182 182
                     // update counts
183
-                    if ( !$this->hasWrittenCounts && !empty( $seg ) ) {
184
-                        $this->updateSegmentCounts( $seg );
183
+                    if (!$this->hasWrittenCounts && !empty($seg)) {
184
+                        $this->updateSegmentCounts($seg);
185 185
                     }
186 186
 
187 187
                     // delete translations so the prepareSegment
188 188
                     // will put source content in target tag
189
-                    if ( $this->sourceInTarget ) {
190
-                        $seg[ 'translation' ] = '';
189
+                    if ($this->sourceInTarget) {
190
+                        $seg['translation'] = '';
191 191
                         $this->resetCounts();
192 192
                     }
193 193
 
194 194
                     // append $translation
195
-                    $translation = $this->prepareTranslation( $seg );
195
+                    $translation = $this->prepareTranslation($seg);
196 196
 
197 197
                     //append translation
198 198
                     $tag = "<target>$translation</target>";
199 199
 
200
-                } elseif( !empty($this->CDATABuffer) and $this->currentTransUnitIsTranslatable === 'no' ) {
200
+                } elseif (!empty($this->CDATABuffer) and $this->currentTransUnitIsTranslatable === 'no') {
201 201
 
202 202
                     // These are target nodes with currentTransUnitIsTranslatable = 'NO'
203 203
                     $this->bufferIsActive = false;
@@ -208,22 +208,22 @@  discard block
 block discarded – undo
208 208
                 // signal we are leaving a target
209 209
                 $this->targetWasWritten = true;
210 210
                 $this->inTarget         = false;
211
-                $this->postProcAndFlush( $this->outputFP, $tag, true );
211
+                $this->postProcAndFlush($this->outputFP, $tag, true);
212 212
 
213
-            } elseif ( in_array( $name, $this->nodesToBuffer ) ) { // we are closing a critical CDATA section
213
+            } elseif (in_array($name, $this->nodesToBuffer)) { // we are closing a critical CDATA section
214 214
 
215 215
                 $this->bufferIsActive = false;
216 216
 
217 217
                 // only for Xliff 2.*
218 218
                 // write here <mda:metaGroup> and <mda:meta> if already present in the <unit>
219
-                if ( 'mda:metadata' === $name && $this->unitContainsMda && !$this->hasWrittenCounts ) {
219
+                if ('mda:metadata' === $name && $this->unitContainsMda && !$this->hasWrittenCounts) {
220 220
 
221 221
                     // we need to update counts here
222 222
                     $this->updateCounts();
223 223
                     $this->hasWrittenCounts = true;
224 224
 
225 225
                     $tag = $this->CDATABuffer;
226
-                    $tag .= $this->getWordCountGroupForXliffV2( false );
226
+                    $tag .= $this->getWordCountGroupForXliffV2(false);
227 227
                     $tag .= "    </mda:metadata>";
228 228
 
229 229
                 } else {
@@ -233,19 +233,19 @@  discard block
 block discarded – undo
233 233
                 $this->CDATABuffer = "";
234 234
 
235 235
                 //flush to the pointer
236
-                $this->postProcAndFlush( $this->outputFP, $tag, false, $name === 'source' );
236
+                $this->postProcAndFlush($this->outputFP, $tag, false, $name === 'source');
237 237
 
238
-            } elseif ( 'segment' === $name ) {
238
+            } elseif ('segment' === $name) {
239 239
 
240 240
                 // only for Xliff 2.*
241 241
                 // if segment has no <target> add it BEFORE </segment>
242
-                if ( !$this->targetWasWritten ) {
242
+                if (!$this->targetWasWritten) {
243 243
 
244 244
                     $seg = $this->getCurrentSegment();
245 245
 
246
-                    if ( isset( $seg[ 'translation' ] ) ) {
246
+                    if (isset($seg['translation'])) {
247 247
 
248
-                        $translation = $this->prepareTranslation( $seg );
248
+                        $translation = $this->prepareTranslation($seg);
249 249
                         // replace the tag
250 250
                         $tag = "<target>$translation</target>";
251 251
 
@@ -258,19 +258,19 @@  discard block
 block discarded – undo
258 258
                 // update segmentPositionInTu
259 259
                 $this->segmentInUnitPosition++;
260 260
 
261
-                $this->postProcAndFlush( $this->outputFP, $tag );
261
+                $this->postProcAndFlush($this->outputFP, $tag);
262 262
 
263 263
                 // we are leaving <segment>, reset $segmentHasTarget
264 264
                 $this->targetWasWritten = false;
265 265
 
266
-            } elseif ( $this->bufferIsActive ) { // this is a tag ( <g | <mrk ) inside a seg or seg-source tag
266
+            } elseif ($this->bufferIsActive) { // this is a tag ( <g | <mrk ) inside a seg or seg-source tag
267 267
                 $this->CDATABuffer .= "</$name>";
268 268
                 // Do NOT Flush
269 269
             } else { //generic tag closure do Nothing
270 270
                 // flush to pointer
271
-                $this->postProcAndFlush( $this->outputFP, $tag );
271
+                $this->postProcAndFlush($this->outputFP, $tag);
272 272
             }
273
-        } elseif ( in_array( $name, $this->nodesToBuffer ) ) {
273
+        } elseif (in_array($name, $this->nodesToBuffer)) {
274 274
 
275 275
             $this->isEmpty        = false;
276 276
             $this->bufferIsActive = false;
@@ -278,7 +278,7 @@  discard block
 block discarded – undo
278 278
             $this->CDATABuffer    = "";
279 279
 
280 280
             //flush to the pointer
281
-            $this->postProcAndFlush( $this->outputFP, $tag, false, $name === 'source' );
281
+            $this->postProcAndFlush($this->outputFP, $tag, false, $name === 'source');
282 282
 
283 283
         } else {
284 284
             //ok, nothing to be done; reset flag for next coming tag
@@ -286,10 +286,10 @@  discard block
 block discarded – undo
286 286
         }
287 287
 
288 288
         // try to signal that we are leaving a target
289
-        $this->tryUnsetAltTrans( $name );
289
+        $this->tryUnsetAltTrans($name);
290 290
 
291 291
         // check if we are leaving a <trans-unit> (xliff v1.*) or <unit> (xliff v2.*)
292
-        if ( $this->tuTagName === $name ) {
292
+        if ($this->tuTagName === $name) {
293 293
             $this->currentTransUnitIsTranslatable = null;
294 294
             $this->inTU                           = false;
295 295
             $this->unitContainsMda                = false;
@@ -305,8 +305,8 @@  discard block
 block discarded – undo
305 305
     private function updateCounts() {
306 306
 
307 307
         $seg = $this->getCurrentSegment();
308
-        if ( !empty( $seg ) ) {
309
-            $this->updateSegmentCounts( $seg );
308
+        if (!empty($seg)) {
309
+            $this->updateSegmentCounts($seg);
310 310
         }
311 311
 
312 312
     }
@@ -316,30 +316,30 @@  discard block
 block discarded – undo
316 316
      *
317 317
      * @return string
318 318
      */
319
-    private function getWordCountGroupForXliffV2( bool $withMetadataTag = true ): string {
319
+    private function getWordCountGroupForXliffV2(bool $withMetadataTag = true): string {
320 320
 
321 321
         $this->mdaGroupCounter++;
322
-        $segments_count_array = $this->counts[ 'segments_count_array' ];
322
+        $segments_count_array = $this->counts['segments_count_array'];
323 323
 
324 324
         $tag = '';
325 325
 
326
-        if ( $withMetadataTag === true ) {
326
+        if ($withMetadataTag === true) {
327 327
             $tag .= '<mda:metadata>';
328 328
         }
329 329
 
330 330
         $index = 0;
331
-        foreach ( $segments_count_array as $segments_count_item ) {
331
+        foreach ($segments_count_array as $segments_count_item) {
332 332
 
333 333
             $id = 'word_count_tu.' . $this->currentTransUnitId . '.' . $index;
334 334
             $index++;
335 335
 
336 336
             $tag .= "    <mda:metaGroup id=\"" . $id . "\" category=\"row_xml_attribute\">
337
-                                <mda:meta type=\"x-matecat-raw\">" . $segments_count_item[ 'raw_word_count' ] . "</mda:meta>
338
-                                <mda:meta type=\"x-matecat-weighted\">" . $segments_count_item[ 'eq_word_count' ] . "</mda:meta>
337
+                                <mda:meta type=\"x-matecat-raw\">" . $segments_count_item['raw_word_count'] . "</mda:meta>
338
+                                <mda:meta type=\"x-matecat-weighted\">" . $segments_count_item['eq_word_count'] . "</mda:meta>
339 339
                             </mda:metaGroup>";
340 340
         }
341 341
 
342
-        if ( $withMetadataTag === true ) {
342
+        if ($withMetadataTag === true) {
343 343
             $tag .= '</mda:metadata>';
344 344
         }
345 345
 
@@ -354,18 +354,18 @@  discard block
 block discarded – undo
354 354
      *
355 355
      * @return string
356 356
      */
357
-    protected function prepareTranslation( array $seg ): string {
357
+    protected function prepareTranslation(array $seg): string {
358 358
 
359
-        $segment     = Strings::removeDangerousChars( $seg [ 'segment' ] );
360
-        $translation = Strings::removeDangerousChars( $seg [ 'translation' ] );
361
-        $dataRefMap  = ( isset( $seg[ 'data_ref_map' ] ) ) ? Strings::jsonToArray( $seg[ 'data_ref_map' ] ) : [];
359
+        $segment     = Strings::removeDangerousChars($seg ['segment']);
360
+        $translation = Strings::removeDangerousChars($seg ['translation']);
361
+        $dataRefMap  = (isset($seg['data_ref_map'])) ? Strings::jsonToArray($seg['data_ref_map']) : [];
362 362
 
363
-        if ( $seg [ 'translation' ] == '' ) {
363
+        if ($seg ['translation'] == '') {
364 364
             $translation = $segment;
365 365
         } else {
366
-            if ( $this->callback instanceof XliffReplacerCallbackInterface ) {
367
-                $error = ( !empty( $seg[ 'error' ] ) ) ? $seg[ 'error' ] : null;
368
-                if ( $this->callback->thereAreErrors( $seg[ 'sid' ], $segment, $translation, $dataRefMap, $error ) ) {
366
+            if ($this->callback instanceof XliffReplacerCallbackInterface) {
367
+                $error = (!empty($seg['error'])) ? $seg['error'] : null;
368
+                if ($this->callback->thereAreErrors($seg['sid'], $segment, $translation, $dataRefMap, $error)) {
369 369
                     $translation = '|||UNTRANSLATED_CONTENT_START|||' . $segment . '|||UNTRANSLATED_CONTENT_END|||';
370 370
                 }
371 371
             }
Please login to merge, or discard this patch.
src/XliffReplacer/AbstractXliffReplacer.php 1 patch
Spacing   +124 added lines, -124 removed lines patch added patch discarded remove patch
@@ -7,29 +7,29 @@  discard block
 block discarded – undo
7 7
 
8 8
 abstract class AbstractXliffReplacer {
9 9
     protected $originalFP;
10
-    protected $outputFP;                  // output stream pointer
10
+    protected $outputFP; // output stream pointer
11 11
 
12
-    protected string $tuTagName;                 // <trans-unit> (forXliff v 1.*) or <unit> (forXliff v 2.*)
13
-    protected bool   $inTU                  = false;  // flag to check whether we are in a <trans-unit>
14
-    protected bool   $inTarget              = false;  // flag to check whether we are in a <target>, to ignore everything
15
-    protected bool   $inAltTrans            = false;  // flag to check whether we are in an <alt-trans> (xliff 1.2) or <mtc:matches> (xliff 2.0)
12
+    protected string $tuTagName; // <trans-unit> (forXliff v 1.*) or <unit> (forXliff v 2.*)
13
+    protected bool   $inTU                  = false; // flag to check whether we are in a <trans-unit>
14
+    protected bool   $inTarget              = false; // flag to check whether we are in a <target>, to ignore everything
15
+    protected bool   $inAltTrans            = false; // flag to check whether we are in an <alt-trans> (xliff 1.2) or <mtc:matches> (xliff 2.0)
16 16
     protected string $alternativeMatchesTag = ""; // polymorphic tag name for xliff 1.2 and 2.0
17
-    protected bool   $isEmpty               = false;  // flag to check whether we are in an empty tag (<tag/>)
18
-    protected bool   $targetWasWritten      = false;  // flag to check is <target> was written in the current unit
19
-    protected string $CDATABuffer           = "";       // buffer for special tag
20
-    protected string $namespace             = "";       // Custom namespace
21
-    protected bool   $bufferIsActive        = false;    // flag for buffeting
17
+    protected bool   $isEmpty               = false; // flag to check whether we are in an empty tag (<tag/>)
18
+    protected bool   $targetWasWritten      = false; // flag to check is <target> was written in the current unit
19
+    protected string $CDATABuffer           = ""; // buffer for special tag
20
+    protected string $namespace             = ""; // Custom namespace
21
+    protected bool   $bufferIsActive        = false; // flag for buffeting
22 22
 
23
-    protected int $offset = 0;         // offset for SAX pointer
23
+    protected int $offset = 0; // offset for SAX pointer
24 24
 
25
-    protected string  $currentBuffer;             // the current piece of text it's been parsed
26
-    protected int     $len;                       // length of the currentBuffer
27
-    protected array   $segments;                  // array of translations
25
+    protected string  $currentBuffer; // the current piece of text it's been parsed
26
+    protected int     $len; // length of the currentBuffer
27
+    protected array   $segments; // array of translations
28 28
     protected array   $lastTransUnit                  = [];
29 29
     protected int     $segmentInUnitPosition          = 0;
30
-    protected ?string $currentTransUnitId             = null;        // id of current <trans-unit>
30
+    protected ?string $currentTransUnitId             = null; // id of current <trans-unit>
31 31
     protected ?string $currentTransUnitIsTranslatable = null; // 'translate' attribute of current <trans-unit>
32
-    protected bool    $hasWrittenCounts               = false;  // check if <unit> already wrote segment counts (forXliff v 2.*)
32
+    protected bool    $hasWrittenCounts               = false; // check if <unit> already wrote segment counts (forXliff v 2.*)
33 33
     protected string  $targetLang;
34 34
     protected bool    $sourceInTarget                 = false;
35 35
 
@@ -81,8 +81,8 @@  discard block
 block discarded – undo
81 81
             XliffReplacerCallbackInterface $callback = null
82 82
     ) {
83 83
         self::$INTERNAL_TAG_PLACEHOLDER = $this->getInternalTagPlaceholder();
84
-        $this->createOutputFileIfDoesNotExist( $outputFilePath );
85
-        $this->setFileDescriptors( $originalXliffPath, $outputFilePath );
84
+        $this->createOutputFileIfDoesNotExist($outputFilePath);
85
+        $this->setFileDescriptors($originalXliffPath, $outputFilePath);
86 86
         $this->xliffVersion   = $xliffVersion;
87 87
         $this->segments       = $segments;
88 88
         $this->targetLang     = $trgLang;
@@ -93,17 +93,17 @@  discard block
 block discarded – undo
93 93
     }
94 94
 
95 95
     public function replaceTranslation() {
96
-        fwrite( $this->outputFP, '<?xml version="1.0" encoding="UTF-8"?>' );
96
+        fwrite($this->outputFP, '<?xml version="1.0" encoding="UTF-8"?>');
97 97
 
98 98
         //create Sax parser
99 99
         $xmlParser = $this->initSaxParser();
100 100
 
101
-        while ( $this->currentBuffer = fread( $this->originalFP, 4096 ) ) {
101
+        while ($this->currentBuffer = fread($this->originalFP, 4096)) {
102 102
             /*
103 103
                preprocess file
104 104
              */
105 105
             // obfuscate entities because sax automatically does html_entity_decode
106
-            $temporary_check_buffer = preg_replace( "/&(.*?);/", self::$INTERNAL_TAG_PLACEHOLDER . '$1' . self::$INTERNAL_TAG_PLACEHOLDER, $this->currentBuffer );
106
+            $temporary_check_buffer = preg_replace("/&(.*?);/", self::$INTERNAL_TAG_PLACEHOLDER . '$1' . self::$INTERNAL_TAG_PLACEHOLDER, $this->currentBuffer);
107 107
 
108 108
             //avoid cutting entities in half:
109 109
             //the last fread could have truncated an entity (say, '&lt;' in '&l'), thus invalidating the escaping
@@ -111,27 +111,27 @@  discard block
 block discarded – undo
111 111
             // 9 is the max length of an entity. So, suppose that the & is at the end of buffer,
112 112
             // add 9 Bytes and substitute the entities, if the & is present, and it is not at the end
113 113
             //it can't be an entity, exit the loop
114
-            while ( true ) {
115
-                $_ampPos = strpos( $temporary_check_buffer, '&' );
114
+            while (true) {
115
+                $_ampPos = strpos($temporary_check_buffer, '&');
116 116
 
117 117
                 //check for real entity or escape it to safely exit from the loop!!!
118
-                if ( $_ampPos === false || strlen( substr( $temporary_check_buffer, $_ampPos ) ) > 9 ) {
118
+                if ($_ampPos === false || strlen(substr($temporary_check_buffer, $_ampPos)) > 9) {
119 119
                     break;
120 120
                 }
121 121
 
122 122
                 //if an entity is still present, fetch some more and repeat the escaping
123
-                $this->currentBuffer    .= fread( $this->originalFP, 9 );
124
-                $temporary_check_buffer = preg_replace( "/&(.*?);/", self::$INTERNAL_TAG_PLACEHOLDER . '$1' . self::$INTERNAL_TAG_PLACEHOLDER, $this->currentBuffer );
123
+                $this->currentBuffer .= fread($this->originalFP, 9);
124
+                $temporary_check_buffer = preg_replace("/&(.*?);/", self::$INTERNAL_TAG_PLACEHOLDER . '$1' . self::$INTERNAL_TAG_PLACEHOLDER, $this->currentBuffer);
125 125
             }
126 126
 
127 127
             //free stuff outside the loop
128
-            unset( $temporary_check_buffer );
128
+            unset($temporary_check_buffer);
129 129
 
130
-            $this->currentBuffer = preg_replace( "/&(.*?);/", self::$INTERNAL_TAG_PLACEHOLDER . '$1' . self::$INTERNAL_TAG_PLACEHOLDER, $this->currentBuffer );
131
-            $this->currentBuffer = str_replace( "&", self::$INTERNAL_TAG_PLACEHOLDER . 'amp' . self::$INTERNAL_TAG_PLACEHOLDER, $this->currentBuffer );
130
+            $this->currentBuffer = preg_replace("/&(.*?);/", self::$INTERNAL_TAG_PLACEHOLDER . '$1' . self::$INTERNAL_TAG_PLACEHOLDER, $this->currentBuffer);
131
+            $this->currentBuffer = str_replace("&", self::$INTERNAL_TAG_PLACEHOLDER . 'amp' . self::$INTERNAL_TAG_PLACEHOLDER, $this->currentBuffer);
132 132
 
133 133
             //get length of chunk
134
-            $this->len = strlen( $this->currentBuffer );
134
+            $this->len = strlen($this->currentBuffer);
135 135
 
136 136
             /*
137 137
             * Get the accumulated this->offset in the document:
@@ -141,12 +141,12 @@  discard block
 block discarded – undo
141 141
             $this->offset += $this->len;
142 142
 
143 143
             //parse chunk of text
144
-            $this->runParser( $xmlParser );
144
+            $this->runParser($xmlParser);
145 145
 
146 146
         }
147 147
 
148 148
         // close Sax parser
149
-        $this->closeSaxParser( $xmlParser );
149
+        $this->closeSaxParser($xmlParser);
150 150
 
151 151
     }
152 152
 
@@ -155,15 +155,15 @@  discard block
 block discarded – undo
155 155
      *
156 156
      * @return void
157 157
      */
158
-    protected function runParser( $xmlParser ) {
158
+    protected function runParser($xmlParser) {
159 159
         //parse chunk of text
160
-        if ( !xml_parse( $xmlParser, $this->currentBuffer, feof( $this->originalFP ) ) ) {
160
+        if (!xml_parse($xmlParser, $this->currentBuffer, feof($this->originalFP))) {
161 161
             //if unable, raise an exception
162
-            throw new RuntimeException( sprintf(
162
+            throw new RuntimeException(sprintf(
163 163
                     "XML error: %s at line %d",
164
-                    xml_error_string( xml_get_error_code( $xmlParser ) ),
165
-                    xml_get_current_line_number( $xmlParser )
166
-            ) );
164
+                    xml_error_string(xml_get_error_code($xmlParser)),
165
+                    xml_get_current_line_number($xmlParser)
166
+            ));
167 167
         }
168 168
     }
169 169
 
@@ -172,18 +172,18 @@  discard block
 block discarded – undo
172 172
      *
173 173
      * @return string
174 174
      */
175
-    protected function getLastCharacter( $parser ): string {
175
+    protected function getLastCharacter($parser): string {
176 176
 
177 177
         //this logic helps detecting empty tags
178 178
         //get current position of SAX pointer in all the stream of data is has read so far:
179 179
         //it points at the end of current tag
180
-        $idx = xml_get_current_byte_index( $parser );
180
+        $idx = xml_get_current_byte_index($parser);
181 181
 
182 182
         //check whether the bounds of current tag are entirely in current buffer or the end of the current tag
183 183
         //is outside current buffer (in the latter case, it's in next buffer to be read by the while loop);
184 184
         //this check is necessary because we may have truncated a tag in half with current read,
185 185
         //and the other half may be encountered in the next buffer it will be passed
186
-        return $this->currentBuffer[ $idx - $this->offset ] ?? $this->currentBuffer[ $this->len - 1 ];
186
+        return $this->currentBuffer[$idx - $this->offset] ?? $this->currentBuffer[$this->len - 1];
187 187
 
188 188
     }
189 189
 
@@ -194,19 +194,19 @@  discard block
 block discarded – undo
194 194
         return "§" .
195 195
                 substr(
196 196
                         str_replace(
197
-                                [ '+', '/' ],
197
+                                ['+', '/'],
198 198
                                 '',
199
-                                base64_encode( openssl_random_pseudo_bytes( 10, $_crypto_strong ) )
199
+                                base64_encode(openssl_random_pseudo_bytes(10, $_crypto_strong))
200 200
                         ),
201 201
                         0,
202 202
                         4
203 203
                 );
204 204
     }
205 205
 
206
-    private function createOutputFileIfDoesNotExist( string $outputFilePath ) {
206
+    private function createOutputFileIfDoesNotExist(string $outputFilePath) {
207 207
         // create output file
208
-        if ( !file_exists( $outputFilePath ) ) {
209
-            touch( $outputFilePath );
208
+        if (!file_exists($outputFilePath)) {
209
+            touch($outputFilePath);
210 210
         }
211 211
     }
212 212
 
@@ -214,13 +214,13 @@  discard block
 block discarded – undo
214 214
      * @param string $originalXliffPath
215 215
      * @param string $outputFilePath
216 216
      */
217
-    private function setFileDescriptors( string $originalXliffPath, string $outputFilePath ) {
218
-        $this->outputFP = fopen( $outputFilePath, 'w+' );
217
+    private function setFileDescriptors(string $originalXliffPath, string $outputFilePath) {
218
+        $this->outputFP = fopen($outputFilePath, 'w+');
219 219
 
220 220
         $streamArgs = null;
221 221
 
222
-        if ( !( $this->originalFP = fopen( $originalXliffPath, "r", false, stream_context_create( $streamArgs ) ) ) ) {
223
-            throw new RuntimeException( "could not open XML input" );
222
+        if (!($this->originalFP = fopen($originalXliffPath, "r", false, stream_context_create($streamArgs)))) {
223
+            throw new RuntimeException("could not open XML input");
224 224
         }
225 225
     }
226 226
 
@@ -230,12 +230,12 @@  discard block
 block discarded – undo
230 230
     public function __destruct() {
231 231
         //this stream can be closed outside the class
232 232
         //to permit multiple concurrent downloads, so suppress warnings
233
-        if ( is_resource( $this->originalFP ) ) {
234
-            fclose( $this->originalFP );
233
+        if (is_resource($this->originalFP)) {
234
+            fclose($this->originalFP);
235 235
         }
236 236
 
237
-        if ( is_resource( $this->outputFP ) ) {
238
-            fclose( $this->outputFP );
237
+        if (is_resource($this->outputFP)) {
238
+            fclose($this->outputFP);
239 239
         }
240 240
 
241 241
     }
@@ -246,11 +246,11 @@  discard block
 block discarded – undo
246 246
      * @return resource
247 247
      */
248 248
     protected function initSaxParser() {
249
-        $xmlSaxParser = xml_parser_create( 'UTF-8' );
250
-        xml_set_object( $xmlSaxParser, $this );
251
-        xml_parser_set_option( $xmlSaxParser, XML_OPTION_CASE_FOLDING, false );
252
-        xml_set_element_handler( $xmlSaxParser, 'tagOpen', 'tagClose' );
253
-        xml_set_character_data_handler( $xmlSaxParser, 'characterData' );
249
+        $xmlSaxParser = xml_parser_create('UTF-8');
250
+        xml_set_object($xmlSaxParser, $this);
251
+        xml_parser_set_option($xmlSaxParser, XML_OPTION_CASE_FOLDING, false);
252
+        xml_set_element_handler($xmlSaxParser, 'tagOpen', 'tagClose');
253
+        xml_set_character_data_handler($xmlSaxParser, 'characterData');
254 254
 
255 255
         return $xmlSaxParser;
256 256
     }
@@ -258,8 +258,8 @@  discard block
 block discarded – undo
258 258
     /**
259 259
      * @param resource $xmlSaxParser
260 260
      */
261
-    protected function closeSaxParser( $xmlSaxParser ) {
262
-        xml_parser_free( $xmlSaxParser );
261
+    protected function closeSaxParser($xmlSaxParser) {
262
+        xml_parser_free($xmlSaxParser);
263 263
     }
264 264
 
265 265
     /**
@@ -269,7 +269,7 @@  discard block
 block discarded – undo
269 269
      *
270 270
      * @return mixed
271 271
      */
272
-    abstract protected function tagOpen( $parser, string $name, array $attr );
272
+    abstract protected function tagOpen($parser, string $name, array $attr);
273 273
 
274 274
     /**
275 275
      * @param resource $parser
@@ -277,7 +277,7 @@  discard block
 block discarded – undo
277 277
      *
278 278
      * @return mixed
279 279
      */
280
-    abstract protected function tagClose( $parser, string $name );
280
+    abstract protected function tagClose($parser, string $name);
281 281
 
282 282
     /**
283 283
      * @param resource $parser
@@ -285,11 +285,11 @@  discard block
 block discarded – undo
285 285
      *
286 286
      * @return mixed
287 287
      */
288
-    protected function characterData( $parser, string $data ): void {
288
+    protected function characterData($parser, string $data): void {
289 289
         // don't write <target> data
290
-        if ( !$this->inTarget && !$this->bufferIsActive ) {
291
-            $this->postProcAndFlush( $this->outputFP, $data );
292
-        } elseif ( $this->bufferIsActive ) {
290
+        if (!$this->inTarget && !$this->bufferIsActive) {
291
+            $this->postProcAndFlush($this->outputFP, $data);
292
+        } elseif ($this->bufferIsActive) {
293 293
             $this->CDATABuffer .= $data;
294 294
         }
295 295
     }
@@ -302,33 +302,33 @@  discard block
 block discarded – undo
302 302
      * @param bool $treatAsCDATA
303 303
      * @param bool $parseMarks
304 304
      */
305
-    protected function postProcAndFlush($fp, string $data, bool $treatAsCDATA = false, $parseMarks = false ) {
305
+    protected function postProcAndFlush($fp, string $data, bool $treatAsCDATA = false, $parseMarks = false) {
306 306
         //postprocess string
307
-        $data = preg_replace( "/" . self::$INTERNAL_TAG_PLACEHOLDER . '(.*?)' . self::$INTERNAL_TAG_PLACEHOLDER . "/", '&$1;', $data );
308
-        $data = str_replace( '&nbsp;', ' ', $data );
307
+        $data = preg_replace("/" . self::$INTERNAL_TAG_PLACEHOLDER . '(.*?)' . self::$INTERNAL_TAG_PLACEHOLDER . "/", '&$1;', $data);
308
+        $data = str_replace('&nbsp;', ' ', $data);
309 309
 
310 310
         // extract <mrk> map only for <seg-source> tag
311
-        if($parseMarks){
311
+        if ($parseMarks) {
312 312
             // check if there are spaces between <mrk> tags
313 313
             preg_match_all('/<mrk \b[^>]*>(.*?)<\/mrk>(\s+)/', $data, $spacesBetweenMrkCheck);
314 314
 
315
-            if(!empty($spacesBetweenMrkCheck[0])){
315
+            if (!empty($spacesBetweenMrkCheck[0])) {
316 316
 
317 317
                 // $spacesBetweenMrkCheck[0] // holds the complete tags
318 318
                 // $spacesBetweenMrkCheck[1] // holds the text
319 319
                 // $spacesBetweenMrkCheck[2] // holds the spaces
320 320
 
321
-                foreach ($spacesBetweenMrkCheck[0] as $index => $mrk){
321
+                foreach ($spacesBetweenMrkCheck[0] as $index => $mrk) {
322 322
 
323
-                    if($this instanceof Xliff20){
323
+                    if ($this instanceof Xliff20) {
324 324
                         preg_match('/id="(\d+)"/', $mrk, $markMatch);
325 325
                     } else {
326 326
                         preg_match('/mid="(\d+)"/', $mrk, $markMatch);
327 327
                     }
328 328
 
329
-                    if(isset($markMatch[1])){
329
+                    if (isset($markMatch[1])) {
330 330
 
331
-                        if(!isset($this->mrkTagsMap[$this->currentTransUnitId])){
331
+                        if (!isset($this->mrkTagsMap[$this->currentTransUnitId])) {
332 332
                             $this->mrkTagsMap[$this->currentTransUnitId] = [];
333 333
                         }
334 334
 
@@ -338,15 +338,15 @@  discard block
 block discarded – undo
338 338
             }
339 339
         }
340 340
 
341
-        if ( !$treatAsCDATA ) {
341
+        if (!$treatAsCDATA) {
342 342
             //unix2dos
343
-            $data = str_replace( "\r\n", "\r", $data );
344
-            $data = str_replace( "\n", "\r", $data );
345
-            $data = str_replace( "\r", "\r\n", $data );
343
+            $data = str_replace("\r\n", "\r", $data);
344
+            $data = str_replace("\n", "\r", $data);
345
+            $data = str_replace("\r", "\r\n", $data);
346 346
         }
347 347
 
348 348
         //flush to disk
349
-        fwrite( $fp, $data );
349
+        fwrite($fp, $data);
350 350
     }
351 351
 
352 352
     /**
@@ -355,19 +355,19 @@  discard block
 block discarded – undo
355 355
      *
356 356
      * @return void
357 357
      */
358
-    protected function handleOpenUnit( string $name, array $attr ) {
358
+    protected function handleOpenUnit(string $name, array $attr) {
359 359
 
360 360
         // check if we are entering into a <trans-unit> (xliff v1.*) or <unit> (xliff v2.*)
361
-        if ( $this->tuTagName === $name ) {
361
+        if ($this->tuTagName === $name) {
362 362
             $this->inTU = true;
363 363
 
364 364
             // get id
365 365
             // trim to first 100 characters because this is the limit on Matecat's DB
366
-            $this->currentTransUnitId = substr( $attr[ 'id' ], 0, 100 );
366
+            $this->currentTransUnitId = substr($attr['id'], 0, 100);
367 367
 
368 368
             // `translate` attribute can be only yes or no
369 369
             // current 'translate' attribute of the current trans-unit
370
-            $this->currentTransUnitIsTranslatable = empty( $attr[ 'translate' ] ) ? 'yes' : $attr[ 'translate' ];
370
+            $this->currentTransUnitIsTranslatable = empty($attr['translate']) ? 'yes' : $attr['translate'];
371 371
 
372 372
             $this->setLastTransUnitSegments();
373 373
 
@@ -381,15 +381,15 @@  discard block
 block discarded – undo
381 381
      *
382 382
      * @return string
383 383
      */
384
-    protected function handleOpenXliffTag( string $name, array $attr, string $tag ): string {
384
+    protected function handleOpenXliffTag(string $name, array $attr, string $tag): string {
385 385
 
386 386
         // Add MateCat specific namespace.
387 387
         // Add trgLang
388
-        if ( $name === 'xliff' ) {
389
-            if ( !array_key_exists( 'xmlns:' . $this->namespace, $attr ) ) {
388
+        if ($name === 'xliff') {
389
+            if (!array_key_exists('xmlns:' . $this->namespace, $attr)) {
390 390
                 $tag .= ' xmlns:' . $this->namespace . '="https://www.matecat.com" ';
391 391
             }
392
-            $tag = preg_replace( '/trgLang="(.*?)"/', 'trgLang="' . $this->targetLang . '"', $tag );
392
+            $tag = preg_replace('/trgLang="(.*?)"/', 'trgLang="' . $this->targetLang . '"', $tag);
393 393
         }
394 394
 
395 395
         return $tag;
@@ -401,11 +401,11 @@  discard block
 block discarded – undo
401 401
      *
402 402
      * @return void
403 403
      */
404
-    protected function checkSetInTarget( string $name ) {
404
+    protected function checkSetInTarget(string $name) {
405 405
 
406 406
         // check if we are entering into a <target>
407
-        if ( 'target' == $name && !$this->inAltTrans ) {
408
-            if ( $this->currentTransUnitIsTranslatable === 'no' ) {
407
+        if ('target' == $name && !$this->inAltTrans) {
408
+            if ($this->currentTransUnitIsTranslatable === 'no') {
409 409
                 $this->inTarget = false;
410 410
             } else {
411 411
                 $this->inTarget = true;
@@ -414,12 +414,12 @@  discard block
 block discarded – undo
414 414
 
415 415
     }
416 416
 
417
-    protected function trySetAltTrans( string $name ) {
417
+    protected function trySetAltTrans(string $name) {
418 418
         $this->inAltTrans = $this->inAltTrans || $this->alternativeMatchesTag == $name;
419 419
     }
420 420
 
421
-    protected function tryUnsetAltTrans( string $name ) {
422
-        if ( $this->alternativeMatchesTag == $name ) {
421
+    protected function tryUnsetAltTrans(string $name) {
422
+        if ($this->alternativeMatchesTag == $name) {
423 423
             $this->inAltTrans = false;
424 424
         }
425 425
     }
@@ -429,15 +429,15 @@  discard block
 block discarded – undo
429 429
      *
430 430
      * @return void
431 431
      */
432
-    protected function setInBuffer( string $name ) {
433
-        if ( in_array( $name, $this->nodesToBuffer ) ) {
432
+    protected function setInBuffer(string $name) {
433
+        if (in_array($name, $this->nodesToBuffer)) {
434 434
             $this->bufferIsActive = true;
435 435
         }
436 436
 
437 437
         // We need bufferIsActive for <target> nodes with currentTransUnitIsTranslatable = 'NO'
438 438
         // because in the other case, the target can be chunked into pieces by xml_set_character_data_handler()
439 439
         // and this can potentially lead to a wrong string rebuild by postProcAndFlush function if the internal placeholders are split
440
-        if($name === 'target' and $this->currentTransUnitIsTranslatable === 'no'){
440
+        if ($name === 'target' and $this->currentTransUnitIsTranslatable === 'no') {
441 441
             $this->bufferIsActive = true;
442 442
         }
443 443
     }
@@ -445,24 +445,24 @@  discard block
 block discarded – undo
445 445
     /**
446 446
      * @param array $seg
447 447
      */
448
-    protected function updateSegmentCounts( array $seg = [] ) {
448
+    protected function updateSegmentCounts(array $seg = []) {
449 449
 
450
-        $raw_word_count = $seg[ 'raw_word_count' ];
451
-        $eq_word_count  = ( floor( $seg[ 'eq_word_count' ] * 100 ) / 100 );
450
+        $raw_word_count = $seg['raw_word_count'];
451
+        $eq_word_count  = (floor($seg['eq_word_count'] * 100) / 100);
452 452
 
453
-        $this->counts[ 'segments_count_array' ][ $seg[ 'sid' ] ] = [
453
+        $this->counts['segments_count_array'][$seg['sid']] = [
454 454
                 'raw_word_count' => $raw_word_count,
455 455
                 'eq_word_count'  => $eq_word_count,
456 456
         ];
457 457
 
458
-        $this->counts[ 'raw_word_count' ] += $raw_word_count;
459
-        $this->counts[ 'eq_word_count' ]  += $eq_word_count;
458
+        $this->counts['raw_word_count'] += $raw_word_count;
459
+        $this->counts['eq_word_count']  += $eq_word_count;
460 460
     }
461 461
 
462 462
     protected function resetCounts() {
463
-        $this->counts[ 'segments_count_array' ] = [];
464
-        $this->counts[ 'raw_word_count' ]       = 0;
465
-        $this->counts[ 'eq_word_count' ]        = 0;
463
+        $this->counts['segments_count_array'] = [];
464
+        $this->counts['raw_word_count']       = 0;
465
+        $this->counts['eq_word_count']        = 0;
466 466
     }
467 467
 
468 468
     /**
@@ -471,16 +471,16 @@  discard block
 block discarded – undo
471 471
      *
472 472
      * @return void
473 473
      */
474
-    protected function checkForSelfClosedTagAndFlush( $parser, string $tag ) {
474
+    protected function checkForSelfClosedTagAndFlush($parser, string $tag) {
475 475
 
476
-        $lastChar = $this->getLastCharacter( $parser );
476
+        $lastChar = $this->getLastCharacter($parser);
477 477
 
478 478
         //trim last space
479
-        $tag = rtrim( $tag );
479
+        $tag = rtrim($tag);
480 480
 
481 481
         //detect empty tag
482 482
         $this->isEmpty = $lastChar == '/';
483
-        if ( $this->isEmpty ) {
483
+        if ($this->isEmpty) {
484 484
             $tag .= $lastChar;
485 485
         }
486 486
 
@@ -488,11 +488,11 @@  discard block
 block discarded – undo
488 488
         $tag .= ">";
489 489
 
490 490
         //set a Buffer for the segSource Source tag
491
-        if ( $this->bufferIsActive ) { // we are opening a critical CDATA section
491
+        if ($this->bufferIsActive) { // we are opening a critical CDATA section
492 492
             //these are NOT source/seg-source/value empty tags, THERE IS A CONTENT, write it in buffer
493 493
             $this->CDATABuffer .= $tag;
494 494
         } else {
495
-            $this->postProcAndFlush( $this->outputFP, $tag );
495
+            $this->postProcAndFlush($this->outputFP, $tag);
496 496
         }
497 497
 
498 498
     }
@@ -517,18 +517,18 @@  discard block
 block discarded – undo
517 517
          */
518 518
         $this->lastTransUnit = [];
519 519
 
520
-        if ( !isset( $this->transUnits[ $this->currentTransUnitId ] ) ) {
520
+        if (!isset($this->transUnits[$this->currentTransUnitId])) {
521 521
             return;
522 522
         }
523 523
 
524
-        $listOfSegmentsIds = $this->transUnits[ $this->currentTransUnitId ];
524
+        $listOfSegmentsIds = $this->transUnits[$this->currentTransUnitId];
525 525
         $last_value        = null;
526
-        $segmentsCount     = count( $listOfSegmentsIds );
527
-        for ( $i = 0; $i < $segmentsCount; $i++ ) {
528
-            $id = $listOfSegmentsIds[ $i ];
529
-            if ( isset( $this->segments[ $id ] ) && ( $i == 0 || $last_value + 1 == $listOfSegmentsIds[ $i ] ) ) {
530
-                $last_value            = $listOfSegmentsIds[ $i ];
531
-                $this->lastTransUnit[] = $this->segments[ $id ];
526
+        $segmentsCount     = count($listOfSegmentsIds);
527
+        for ($i = 0; $i < $segmentsCount; $i++) {
528
+            $id = $listOfSegmentsIds[$i];
529
+            if (isset($this->segments[$id]) && ($i == 0 || $last_value + 1 == $listOfSegmentsIds[$i])) {
530
+                $last_value            = $listOfSegmentsIds[$i];
531
+                $this->lastTransUnit[] = $this->segments[$id];
532 532
             }
533 533
         }
534 534
     }
@@ -539,10 +539,10 @@  discard block
 block discarded – undo
539 539
     protected function getCurrentSegment(): array {
540 540
         if (
541 541
             $this->currentTransUnitIsTranslatable !== 'no' &&
542
-            isset( $this->transUnits[ $this->currentTransUnitId ] ) &&
543
-            isset( $this->segments[ $this->segmentInUnitPosition ] )
542
+            isset($this->transUnits[$this->currentTransUnitId]) &&
543
+            isset($this->segments[$this->segmentInUnitPosition])
544 544
         ) {
545
-            return $this->segments[ $this->segmentInUnitPosition ];
545
+            return $this->segments[$this->segmentInUnitPosition];
546 546
         }
547 547
 
548 548
         return [];
Please login to merge, or discard this patch.