Passed
Pull Request — master (#92)
by Mauro
03:17
created
src/XliffReplacer/Xliff12.php 1 patch
Spacing   +62 added lines, -62 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,15 +106,15 @@  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
-            if ( !$this->inTarget ) {
111
+            if (!$this->inTarget) {
112 112
                 $tag = "</$name>";
113 113
             }
114 114
 
115
-            if ( 'target' == $name && !$this->inAltTrans ) {
115
+            if ('target' == $name && !$this->inAltTrans) {
116 116
 
117
-                if ( isset( $this->transUnits[ $this->currentTransUnitId ] ) ) {
117
+                if (isset($this->transUnits[$this->currentTransUnitId])) {
118 118
 
119 119
                     // get translation of current segment, by indirect indexing: id -> positional index -> segment
120 120
                     // actually there may be more than one segment to that ID if there are two mrk of the same source segment
@@ -125,45 +125,45 @@  discard block
 block discarded – undo
125 125
                 $this->targetWasWritten = true;
126 126
                 // signal we are leaving a target
127 127
                 $this->inTarget = false;
128
-                $this->postProcAndFlush( $this->outputFP, $tag, true );
128
+                $this->postProcAndFlush($this->outputFP, $tag, true);
129 129
 
130
-            } elseif ( in_array( $name, $this->nodesToBuffer ) ) { // we are closing a critical CDATA section
130
+            } elseif (in_array($name, $this->nodesToBuffer)) { // we are closing a critical CDATA section
131 131
 
132 132
                 $this->bufferIsActive = false;
133 133
                 $tag                  = $this->CDATABuffer . "</$name>";
134 134
                 $this->CDATABuffer    = "";
135 135
 
136 136
                 //flush to the pointer
137
-                $this->postProcAndFlush( $this->outputFP, $tag );
137
+                $this->postProcAndFlush($this->outputFP, $tag);
138 138
 
139
-            } elseif ( $name === $this->tuTagName ) {
139
+            } elseif ($name === $this->tuTagName) {
140 140
 
141 141
                 $tag = "";
142 142
 
143 143
                 // handling </trans-unit> closure
144
-                if ( !$this->targetWasWritten ) {
144
+                if (!$this->targetWasWritten) {
145 145
 
146
-                    if ( isset( $this->transUnits[ $this->currentTransUnitId ] ) ) {
146
+                    if (isset($this->transUnits[$this->currentTransUnitId])) {
147 147
                         $tag = $this->rebuildTarget();
148 148
                     } else {
149
-                        $tag = $this->createTargetTag( "", "" );
149
+                        $tag = $this->createTargetTag("", "");
150 150
                     }
151 151
 
152 152
                 }
153 153
 
154
-                $tag                    .= "</$this->tuTagName>";
154
+                $tag .= "</$this->tuTagName>";
155 155
                 $this->targetWasWritten = false;
156
-                $this->postProcAndFlush( $this->outputFP, $tag );
156
+                $this->postProcAndFlush($this->outputFP, $tag);
157 157
 
158
-            } elseif ( $this->bufferIsActive ) { // this is a tag ( <g | <mrk ) inside a seg or seg-source tag
158
+            } elseif ($this->bufferIsActive) { // this is a tag ( <g | <mrk ) inside a seg or seg-source tag
159 159
                 $this->CDATABuffer .= "</$name>";
160 160
                 // Do NOT Flush
161 161
             } else { //generic tag closure do Nothing
162 162
                 // flush to pointer
163
-                $this->postProcAndFlush( $this->outputFP, $tag );
163
+                $this->postProcAndFlush($this->outputFP, $tag);
164 164
             }
165 165
 
166
-        } elseif ( in_array( $name, $this->nodesToBuffer ) ) {
166
+        } elseif (in_array($name, $this->nodesToBuffer)) {
167 167
 
168 168
             $this->isEmpty        = false;
169 169
             $this->bufferIsActive = false;
@@ -171,7 +171,7 @@  discard block
 block discarded – undo
171 171
             $this->CDATABuffer    = "";
172 172
 
173 173
             //flush to the pointer
174
-            $this->postProcAndFlush( $this->outputFP, $tag );
174
+            $this->postProcAndFlush($this->outputFP, $tag);
175 175
 
176 176
         } else {
177 177
             //ok, nothing to be done; reset flag for next coming tag
@@ -179,10 +179,10 @@  discard block
 block discarded – undo
179 179
         }
180 180
 
181 181
         // try to signal that we are leaving a target
182
-        $this->tryUnsetAltTrans( $name );
182
+        $this->tryUnsetAltTrans($name);
183 183
 
184 184
         // check if we are leaving a <trans-unit> (xliff v1.*) or <unit> (xliff v2.*)
185
-        if ( $this->tuTagName === $name ) {
185
+        if ($this->tuTagName === $name) {
186 186
             $this->currentTransUnitIsTranslatable = null;
187 187
             $this->inTU                           = false;
188 188
             $this->hasWrittenCounts               = false;
@@ -199,31 +199,31 @@  discard block
 block discarded – undo
199 199
      *
200 200
      * @return string
201 201
      */
202
-    protected function prepareTranslation( array $seg, string $transUnitTranslation = "" ): string {
202
+    protected function prepareTranslation(array $seg, string $transUnitTranslation = ""): string {
203 203
 
204
-        $segment     = Strings::removeDangerousChars( $seg [ 'segment' ] );
205
-        $translation = Strings::removeDangerousChars( $seg [ 'translation' ] );
204
+        $segment     = Strings::removeDangerousChars($seg ['segment']);
205
+        $translation = Strings::removeDangerousChars($seg ['translation']);
206 206
 
207
-        if ( $seg [ 'translation' ] == '' ) {
207
+        if ($seg ['translation'] == '') {
208 208
             $translation = $segment;
209 209
         } else {
210
-            if ( $this->callback instanceof XliffReplacerCallbackInterface ) {
211
-                $error = ( !empty( $seg[ 'error' ] ) ) ? $seg[ 'error' ] : null;
212
-                if ( $this->callback->thereAreErrors( $seg[ 'sid' ], $segment, $translation, [], $error ) ) {
210
+            if ($this->callback instanceof XliffReplacerCallbackInterface) {
211
+                $error = (!empty($seg['error'])) ? $seg['error'] : null;
212
+                if ($this->callback->thereAreErrors($seg['sid'], $segment, $translation, [], $error)) {
213 213
                     $translation = '|||UNTRANSLATED_CONTENT_START|||' . $segment . '|||UNTRANSLATED_CONTENT_END|||';
214 214
                 }
215 215
             }
216 216
         }
217 217
 
218
-        $transUnitTranslation .= $seg[ 'prev_tags' ] . $this->rebuildMarks( $seg, $translation ) . ltrim( $seg[ 'succ_tags' ] );
218
+        $transUnitTranslation .= $seg['prev_tags'] . $this->rebuildMarks($seg, $translation) . ltrim($seg['succ_tags']);
219 219
 
220 220
         return $transUnitTranslation;
221 221
     }
222 222
 
223
-    protected function rebuildMarks( array $seg, string $translation ): string {
223
+    protected function rebuildMarks(array $seg, string $translation): string {
224 224
 
225
-        if ( $seg[ 'mrk_id' ] !== null && $seg[ 'mrk_id' ] != '' ) {
226
-            $translation = "<mrk mid=\"" . $seg[ 'mrk_id' ] . "\" mtype=\"seg\">" . $seg[ 'mrk_prev_tags' ] . $translation . $seg[ 'mrk_succ_tags' ] . "</mrk>";
225
+        if ($seg['mrk_id'] !== null && $seg['mrk_id'] != '') {
226
+            $translation = "<mrk mid=\"" . $seg['mrk_id'] . "\" mtype=\"seg\">" . $seg['mrk_prev_tags'] . $translation . $seg['mrk_succ_tags'] . "</mrk>";
227 227
         }
228 228
 
229 229
         return $translation;
@@ -238,10 +238,10 @@  discard block
 block discarded – undo
238 238
      *
239 239
      * @return string
240 240
      */
241
-    private function createTargetTag( string $translation, string $stateProp ): string {
241
+    private function createTargetTag(string $translation, string $stateProp): string {
242 242
         $targetLang = ' xml:lang="' . $this->targetLang . '"';
243 243
         $tag        = "<target $targetLang $stateProp>$translation</target>";
244
-        $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>';
244
+        $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>';
245 245
 
246 246
         return $tag;
247 247
 
@@ -257,7 +257,7 @@  discard block
 block discarded – undo
257 257
         // we must reset the lastMrkId found because this is a new segment.
258 258
         $lastMrkId = -1;
259 259
 
260
-        foreach ( $this->lastTransUnit as $pos => $seg ) {
260
+        foreach ($this->lastTransUnit as $pos => $seg) {
261 261
 
262 262
             /*
263 263
              * This routine works to respect the positional orders of markers.
@@ -270,8 +270,8 @@  discard block
 block discarded – undo
270 270
              * pre-assign zero to the new mrk if this is the first one ( in this segment )
271 271
              * If it is null leave it NULL
272 272
              */
273
-            if ( (int)$seg[ "mrk_id" ] < 0 && $seg[ "mrk_id" ] !== null ) {
274
-                $seg[ "mrk_id" ] = 0;
273
+            if ((int)$seg["mrk_id"] < 0 && $seg["mrk_id"] !== null) {
274
+                $seg["mrk_id"] = 0;
275 275
             }
276 276
 
277 277
             /*
@@ -280,39 +280,39 @@  discard block
 block discarded – undo
280 280
              * ( null <= -1 ) === true
281 281
              * so, cast to int
282 282
              */
283
-            if ( (int)$seg[ "mrk_id" ] <= $lastMrkId ) {
283
+            if ((int)$seg["mrk_id"] <= $lastMrkId) {
284 284
                 break;
285 285
             }
286 286
 
287 287
             // update counts
288
-            if ( !empty( $seg ) ) {
289
-                $this->updateSegmentCounts( $seg );
288
+            if (!empty($seg)) {
289
+                $this->updateSegmentCounts($seg);
290 290
             }
291 291
 
292 292
             // delete translations so the prepareSegment
293 293
             // will put source content in target tag
294
-            if ( $this->sourceInTarget ) {
295
-                $seg[ 'translation' ] = '';
294
+            if ($this->sourceInTarget) {
295
+                $seg['translation'] = '';
296 296
                 $this->resetCounts();
297 297
             }
298 298
 
299 299
             // append $translation
300
-            $translation = $this->prepareTranslation( $seg, $translation );
300
+            $translation = $this->prepareTranslation($seg, $translation);
301 301
 
302
-            $lastMrkId = $seg[ "mrk_id" ];
302
+            $lastMrkId = $seg["mrk_id"];
303 303
 
304
-            [ $stateProp, $lastMrkState ] = StatusToStateAttribute::getState( $this->xliffVersion, $seg[ 'status' ], $lastMrkState );
304
+            [$stateProp, $lastMrkState] = StatusToStateAttribute::getState($this->xliffVersion, $seg['status'], $lastMrkState);
305 305
 
306 306
         }
307 307
 
308 308
         //append translation
309
-        return $this->createTargetTag( $translation, $stateProp );
309
+        return $this->createTargetTag($translation, $stateProp);
310 310
 
311 311
     }
312 312
 
313 313
     protected function getCurrentSegment(): array {
314
-        if ( $this->currentTransUnitIsTranslatable !== 'no' && isset( $this->transUnits[ $this->currentTransUnitId ] ) ) {
315
-            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
314
+        if ($this->currentTransUnitIsTranslatable !== 'no' && isset($this->transUnits[$this->currentTransUnitId])) {
315
+            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
316 316
         }
317 317
 
318 318
         return [];
Please login to merge, or discard this patch.
src/XliffReplacer/AbstractXliffReplacer.php 1 patch
Spacing   +117 added lines, -117 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
 
@@ -79,8 +79,8 @@  discard block
 block discarded – undo
79 79
             XliffReplacerCallbackInterface $callback = null
80 80
     ) {
81 81
         self::$INTERNAL_TAG_PLACEHOLDER = $this->getInternalTagPlaceholder();
82
-        $this->createOutputFileIfDoesNotExist( $outputFilePath );
83
-        $this->setFileDescriptors( $originalXliffPath, $outputFilePath );
82
+        $this->createOutputFileIfDoesNotExist($outputFilePath);
83
+        $this->setFileDescriptors($originalXliffPath, $outputFilePath);
84 84
         $this->xliffVersion   = $xliffVersion;
85 85
         $this->segments       = $segments;
86 86
         $this->targetLang     = $trgLang;
@@ -91,17 +91,17 @@  discard block
 block discarded – undo
91 91
     }
92 92
 
93 93
     public function replaceTranslation() {
94
-        fwrite( $this->outputFP, '<?xml version="1.0" encoding="UTF-8"?>' );
94
+        fwrite($this->outputFP, '<?xml version="1.0" encoding="UTF-8"?>');
95 95
 
96 96
         //create Sax parser
97 97
         $xmlParser = $this->initSaxParser();
98 98
 
99
-        while ( $this->currentBuffer = fread( $this->originalFP, 4096 ) ) {
99
+        while ($this->currentBuffer = fread($this->originalFP, 4096)) {
100 100
             /*
101 101
                preprocess file
102 102
              */
103 103
             // obfuscate entities because sax automatically does html_entity_decode
104
-            $temporary_check_buffer = preg_replace( "/&(.*?);/", self::$INTERNAL_TAG_PLACEHOLDER . '$1' . self::$INTERNAL_TAG_PLACEHOLDER, $this->currentBuffer );
104
+            $temporary_check_buffer = preg_replace("/&(.*?);/", self::$INTERNAL_TAG_PLACEHOLDER . '$1' . self::$INTERNAL_TAG_PLACEHOLDER, $this->currentBuffer);
105 105
 
106 106
             //avoid cutting entities in half:
107 107
             //the last fread could have truncated an entity (say, '&lt;' in '&l'), thus invalidating the escaping
@@ -109,27 +109,27 @@  discard block
 block discarded – undo
109 109
             // 9 is the max length of an entity. So, suppose that the & is at the end of buffer,
110 110
             // add 9 Bytes and substitute the entities, if the & is present, and it is not at the end
111 111
             //it can't be an entity, exit the loop
112
-            while ( true ) {
113
-                $_ampPos = strpos( $temporary_check_buffer, '&' );
112
+            while (true) {
113
+                $_ampPos = strpos($temporary_check_buffer, '&');
114 114
 
115 115
                 //check for real entity or escape it to safely exit from the loop!!!
116
-                if ( $_ampPos === false || strlen( substr( $temporary_check_buffer, $_ampPos ) ) > 9 ) {
116
+                if ($_ampPos === false || strlen(substr($temporary_check_buffer, $_ampPos)) > 9) {
117 117
                     break;
118 118
                 }
119 119
 
120 120
                 //if an entity is still present, fetch some more and repeat the escaping
121
-                $this->currentBuffer    .= fread( $this->originalFP, 9 );
122
-                $temporary_check_buffer = preg_replace( "/&(.*?);/", self::$INTERNAL_TAG_PLACEHOLDER . '$1' . self::$INTERNAL_TAG_PLACEHOLDER, $this->currentBuffer );
121
+                $this->currentBuffer .= fread($this->originalFP, 9);
122
+                $temporary_check_buffer = preg_replace("/&(.*?);/", self::$INTERNAL_TAG_PLACEHOLDER . '$1' . self::$INTERNAL_TAG_PLACEHOLDER, $this->currentBuffer);
123 123
             }
124 124
 
125 125
             //free stuff outside the loop
126
-            unset( $temporary_check_buffer );
126
+            unset($temporary_check_buffer);
127 127
 
128
-            $this->currentBuffer = preg_replace( "/&(.*?);/", self::$INTERNAL_TAG_PLACEHOLDER . '$1' . self::$INTERNAL_TAG_PLACEHOLDER, $this->currentBuffer );
129
-            $this->currentBuffer = str_replace( "&", self::$INTERNAL_TAG_PLACEHOLDER . 'amp' . self::$INTERNAL_TAG_PLACEHOLDER, $this->currentBuffer );
128
+            $this->currentBuffer = preg_replace("/&(.*?);/", self::$INTERNAL_TAG_PLACEHOLDER . '$1' . self::$INTERNAL_TAG_PLACEHOLDER, $this->currentBuffer);
129
+            $this->currentBuffer = str_replace("&", self::$INTERNAL_TAG_PLACEHOLDER . 'amp' . self::$INTERNAL_TAG_PLACEHOLDER, $this->currentBuffer);
130 130
 
131 131
             //get length of chunk
132
-            $this->len = strlen( $this->currentBuffer );
132
+            $this->len = strlen($this->currentBuffer);
133 133
 
134 134
             /*
135 135
             * Get the accumulated this->offset in the document:
@@ -139,12 +139,12 @@  discard block
 block discarded – undo
139 139
             $this->offset += $this->len;
140 140
 
141 141
             //parse chunk of text
142
-            $this->runParser( $xmlParser );
142
+            $this->runParser($xmlParser);
143 143
 
144 144
         }
145 145
 
146 146
         // close Sax parser
147
-        $this->closeSaxParser( $xmlParser );
147
+        $this->closeSaxParser($xmlParser);
148 148
 
149 149
     }
150 150
 
@@ -153,15 +153,15 @@  discard block
 block discarded – undo
153 153
      *
154 154
      * @return void
155 155
      */
156
-    protected function runParser( $xmlParser ) {
156
+    protected function runParser($xmlParser) {
157 157
         //parse chunk of text
158
-        if ( !xml_parse( $xmlParser, $this->currentBuffer, feof( $this->originalFP ) ) ) {
158
+        if (!xml_parse($xmlParser, $this->currentBuffer, feof($this->originalFP))) {
159 159
             //if unable, raise an exception
160
-            throw new RuntimeException( sprintf(
160
+            throw new RuntimeException(sprintf(
161 161
                     "XML error: %s at line %d",
162
-                    xml_error_string( xml_get_error_code( $xmlParser ) ),
163
-                    xml_get_current_line_number( $xmlParser )
164
-            ) );
162
+                    xml_error_string(xml_get_error_code($xmlParser)),
163
+                    xml_get_current_line_number($xmlParser)
164
+            ));
165 165
         }
166 166
     }
167 167
 
@@ -170,18 +170,18 @@  discard block
 block discarded – undo
170 170
      *
171 171
      * @return string
172 172
      */
173
-    protected function getLastCharacter( $parser ): string {
173
+    protected function getLastCharacter($parser): string {
174 174
 
175 175
         //this logic helps detecting empty tags
176 176
         //get current position of SAX pointer in all the stream of data is has read so far:
177 177
         //it points at the end of current tag
178
-        $idx = xml_get_current_byte_index( $parser );
178
+        $idx = xml_get_current_byte_index($parser);
179 179
 
180 180
         //check whether the bounds of current tag are entirely in current buffer or the end of the current tag
181 181
         //is outside current buffer (in the latter case, it's in next buffer to be read by the while loop);
182 182
         //this check is necessary because we may have truncated a tag in half with current read,
183 183
         //and the other half may be encountered in the next buffer it will be passed
184
-        return $this->currentBuffer[ $idx - $this->offset ] ?? $this->currentBuffer[ $this->len - 1 ];
184
+        return $this->currentBuffer[$idx - $this->offset] ?? $this->currentBuffer[$this->len - 1];
185 185
 
186 186
     }
187 187
 
@@ -192,19 +192,19 @@  discard block
 block discarded – undo
192 192
         return "§" .
193 193
                 substr(
194 194
                         str_replace(
195
-                                [ '+', '/' ],
195
+                                ['+', '/'],
196 196
                                 '',
197
-                                base64_encode( openssl_random_pseudo_bytes( 10, $_crypto_strong ) )
197
+                                base64_encode(openssl_random_pseudo_bytes(10, $_crypto_strong))
198 198
                         ),
199 199
                         0,
200 200
                         4
201 201
                 );
202 202
     }
203 203
 
204
-    private function createOutputFileIfDoesNotExist( string $outputFilePath ) {
204
+    private function createOutputFileIfDoesNotExist(string $outputFilePath) {
205 205
         // create output file
206
-        if ( !file_exists( $outputFilePath ) ) {
207
-            touch( $outputFilePath );
206
+        if (!file_exists($outputFilePath)) {
207
+            touch($outputFilePath);
208 208
         }
209 209
     }
210 210
 
@@ -212,13 +212,13 @@  discard block
 block discarded – undo
212 212
      * @param string $originalXliffPath
213 213
      * @param string $outputFilePath
214 214
      */
215
-    private function setFileDescriptors( string $originalXliffPath, string $outputFilePath ) {
216
-        $this->outputFP = fopen( $outputFilePath, 'w+' );
215
+    private function setFileDescriptors(string $originalXliffPath, string $outputFilePath) {
216
+        $this->outputFP = fopen($outputFilePath, 'w+');
217 217
 
218 218
         $streamArgs = null;
219 219
 
220
-        if ( !( $this->originalFP = fopen( $originalXliffPath, "r", false, stream_context_create( $streamArgs ) ) ) ) {
221
-            throw new RuntimeException( "could not open XML input" );
220
+        if (!($this->originalFP = fopen($originalXliffPath, "r", false, stream_context_create($streamArgs)))) {
221
+            throw new RuntimeException("could not open XML input");
222 222
         }
223 223
     }
224 224
 
@@ -228,12 +228,12 @@  discard block
 block discarded – undo
228 228
     public function __destruct() {
229 229
         //this stream can be closed outside the class
230 230
         //to permit multiple concurrent downloads, so suppress warnings
231
-        if ( is_resource( $this->originalFP ) ) {
232
-            fclose( $this->originalFP );
231
+        if (is_resource($this->originalFP)) {
232
+            fclose($this->originalFP);
233 233
         }
234 234
 
235
-        if ( is_resource( $this->outputFP ) ) {
236
-            fclose( $this->outputFP );
235
+        if (is_resource($this->outputFP)) {
236
+            fclose($this->outputFP);
237 237
         }
238 238
 
239 239
     }
@@ -244,11 +244,11 @@  discard block
 block discarded – undo
244 244
      * @return resource
245 245
      */
246 246
     protected function initSaxParser() {
247
-        $xmlSaxParser = xml_parser_create( 'UTF-8' );
248
-        xml_set_object( $xmlSaxParser, $this );
249
-        xml_parser_set_option( $xmlSaxParser, XML_OPTION_CASE_FOLDING, false );
250
-        xml_set_element_handler( $xmlSaxParser, 'tagOpen', 'tagClose' );
251
-        xml_set_character_data_handler( $xmlSaxParser, 'characterData' );
247
+        $xmlSaxParser = xml_parser_create('UTF-8');
248
+        xml_set_object($xmlSaxParser, $this);
249
+        xml_parser_set_option($xmlSaxParser, XML_OPTION_CASE_FOLDING, false);
250
+        xml_set_element_handler($xmlSaxParser, 'tagOpen', 'tagClose');
251
+        xml_set_character_data_handler($xmlSaxParser, 'characterData');
252 252
 
253 253
         return $xmlSaxParser;
254 254
     }
@@ -256,8 +256,8 @@  discard block
 block discarded – undo
256 256
     /**
257 257
      * @param resource $xmlSaxParser
258 258
      */
259
-    protected function closeSaxParser( $xmlSaxParser ) {
260
-        xml_parser_free( $xmlSaxParser );
259
+    protected function closeSaxParser($xmlSaxParser) {
260
+        xml_parser_free($xmlSaxParser);
261 261
     }
262 262
 
263 263
     /**
@@ -267,7 +267,7 @@  discard block
 block discarded – undo
267 267
      *
268 268
      * @return mixed
269 269
      */
270
-    abstract protected function tagOpen( $parser, string $name, array $attr );
270
+    abstract protected function tagOpen($parser, string $name, array $attr);
271 271
 
272 272
     /**
273 273
      * @param resource $parser
@@ -275,7 +275,7 @@  discard block
 block discarded – undo
275 275
      *
276 276
      * @return mixed
277 277
      */
278
-    abstract protected function tagClose( $parser, string $name );
278
+    abstract protected function tagClose($parser, string $name);
279 279
 
280 280
     /**
281 281
      * @param resource $parser
@@ -283,11 +283,11 @@  discard block
 block discarded – undo
283 283
      *
284 284
      * @return mixed
285 285
      */
286
-    protected function characterData( $parser, string $data ): void {
286
+    protected function characterData($parser, string $data): void {
287 287
         // don't write <target> data
288
-        if ( !$this->inTarget && !$this->bufferIsActive ) {
289
-            $this->postProcAndFlush( $this->outputFP, $data );
290
-        } elseif ( $this->bufferIsActive ) {
288
+        if (!$this->inTarget && !$this->bufferIsActive) {
289
+            $this->postProcAndFlush($this->outputFP, $data);
290
+        } elseif ($this->bufferIsActive) {
291 291
             $this->CDATABuffer .= $data;
292 292
         }
293 293
     }
@@ -299,19 +299,19 @@  discard block
 block discarded – undo
299 299
      * @param string   $data
300 300
      * @param bool     $treatAsCDATA
301 301
      */
302
-    protected function postProcAndFlush( $fp, string $data, bool $treatAsCDATA = false ) {
302
+    protected function postProcAndFlush($fp, string $data, bool $treatAsCDATA = false) {
303 303
         //postprocess string
304
-        $data = preg_replace( "/" . self::$INTERNAL_TAG_PLACEHOLDER . '(.*?)' . self::$INTERNAL_TAG_PLACEHOLDER . "/", '&$1;', $data );
305
-        $data = str_replace( '&nbsp;', ' ', $data );
306
-        if ( !$treatAsCDATA ) {
304
+        $data = preg_replace("/" . self::$INTERNAL_TAG_PLACEHOLDER . '(.*?)' . self::$INTERNAL_TAG_PLACEHOLDER . "/", '&$1;', $data);
305
+        $data = str_replace('&nbsp;', ' ', $data);
306
+        if (!$treatAsCDATA) {
307 307
             //unix2dos
308
-            $data = str_replace( "\r\n", "\r", $data );
309
-            $data = str_replace( "\n", "\r", $data );
310
-            $data = str_replace( "\r", "\r\n", $data );
308
+            $data = str_replace("\r\n", "\r", $data);
309
+            $data = str_replace("\n", "\r", $data);
310
+            $data = str_replace("\r", "\r\n", $data);
311 311
         }
312 312
 
313 313
         //flush to disk
314
-        fwrite( $fp, $data );
314
+        fwrite($fp, $data);
315 315
     }
316 316
 
317 317
     /**
@@ -320,19 +320,19 @@  discard block
 block discarded – undo
320 320
      *
321 321
      * @return void
322 322
      */
323
-    protected function handleOpenUnit( string $name, array $attr ) {
323
+    protected function handleOpenUnit(string $name, array $attr) {
324 324
 
325 325
         // check if we are entering into a <trans-unit> (xliff v1.*) or <unit> (xliff v2.*)
326
-        if ( $this->tuTagName === $name ) {
326
+        if ($this->tuTagName === $name) {
327 327
             $this->inTU = true;
328 328
 
329 329
             // get id
330 330
             // trim to first 100 characters because this is the limit on Matecat's DB
331
-            $this->currentTransUnitId = substr( $attr[ 'id' ], 0, 100 );
331
+            $this->currentTransUnitId = substr($attr['id'], 0, 100);
332 332
 
333 333
             // `translate` attribute can be only yes or no
334 334
             // current 'translate' attribute of the current trans-unit
335
-            $this->currentTransUnitIsTranslatable = empty( $attr[ 'translate' ] ) ? 'yes' : $attr[ 'translate' ];
335
+            $this->currentTransUnitIsTranslatable = empty($attr['translate']) ? 'yes' : $attr['translate'];
336 336
 
337 337
             $this->setLastTransUnitSegments();
338 338
 
@@ -346,15 +346,15 @@  discard block
 block discarded – undo
346 346
      *
347 347
      * @return string
348 348
      */
349
-    protected function handleOpenXliffTag( string $name, array $attr, string $tag ): string {
349
+    protected function handleOpenXliffTag(string $name, array $attr, string $tag): string {
350 350
 
351 351
         // Add MateCat specific namespace.
352 352
         // Add trgLang
353
-        if ( $name === 'xliff' ) {
354
-            if ( !array_key_exists( 'xmlns:' . $this->namespace, $attr ) ) {
353
+        if ($name === 'xliff') {
354
+            if (!array_key_exists('xmlns:' . $this->namespace, $attr)) {
355 355
                 $tag .= ' xmlns:' . $this->namespace . '="https://www.matecat.com" ';
356 356
             }
357
-            $tag = preg_replace( '/trgLang="(.*?)"/', 'trgLang="' . $this->targetLang . '"', $tag );
357
+            $tag = preg_replace('/trgLang="(.*?)"/', 'trgLang="' . $this->targetLang . '"', $tag);
358 358
         }
359 359
 
360 360
         return $tag;
@@ -366,11 +366,11 @@  discard block
 block discarded – undo
366 366
      *
367 367
      * @return void
368 368
      */
369
-    protected function checkSetInTarget( string $name ) {
369
+    protected function checkSetInTarget(string $name) {
370 370
 
371 371
         // check if we are entering into a <target>
372
-        if ( 'target' == $name && !$this->inAltTrans ) {
373
-            if ( $this->currentTransUnitIsTranslatable === 'no' ) {
372
+        if ('target' == $name && !$this->inAltTrans) {
373
+            if ($this->currentTransUnitIsTranslatable === 'no') {
374 374
                 $this->inTarget = false;
375 375
             } else {
376 376
                 $this->inTarget = true;
@@ -379,12 +379,12 @@  discard block
 block discarded – undo
379 379
 
380 380
     }
381 381
 
382
-    protected function trySetAltTrans( string $name ) {
382
+    protected function trySetAltTrans(string $name) {
383 383
         $this->inAltTrans = $this->inAltTrans || $this->alternativeMatchesTag == $name;
384 384
     }
385 385
 
386
-    protected function tryUnsetAltTrans( string $name ) {
387
-        if ( $this->alternativeMatchesTag == $name ) {
386
+    protected function tryUnsetAltTrans(string $name) {
387
+        if ($this->alternativeMatchesTag == $name) {
388 388
             $this->inAltTrans = false;
389 389
         }
390 390
     }
@@ -394,8 +394,8 @@  discard block
 block discarded – undo
394 394
      *
395 395
      * @return void
396 396
      */
397
-    protected function setInBuffer( string $name ) {
398
-        if ( in_array( $name, $this->nodesToBuffer ) ) {
397
+    protected function setInBuffer(string $name) {
398
+        if (in_array($name, $this->nodesToBuffer)) {
399 399
             $this->bufferIsActive = true;
400 400
         }
401 401
     }
@@ -403,24 +403,24 @@  discard block
 block discarded – undo
403 403
     /**
404 404
      * @param array $seg
405 405
      */
406
-    protected function updateSegmentCounts( array $seg = [] ) {
406
+    protected function updateSegmentCounts(array $seg = []) {
407 407
 
408
-        $raw_word_count = $seg[ 'raw_word_count' ];
409
-        $eq_word_count  = ( floor( $seg[ 'eq_word_count' ] * 100 ) / 100 );
408
+        $raw_word_count = $seg['raw_word_count'];
409
+        $eq_word_count  = (floor($seg['eq_word_count'] * 100) / 100);
410 410
 
411
-        $this->counts[ 'segments_count_array' ][ $seg[ 'sid' ] ] = [
411
+        $this->counts['segments_count_array'][$seg['sid']] = [
412 412
                 'raw_word_count' => $raw_word_count,
413 413
                 'eq_word_count'  => $eq_word_count,
414 414
         ];
415 415
 
416
-        $this->counts[ 'raw_word_count' ] += $raw_word_count;
417
-        $this->counts[ 'eq_word_count' ]  += $eq_word_count;
416
+        $this->counts['raw_word_count'] += $raw_word_count;
417
+        $this->counts['eq_word_count']  += $eq_word_count;
418 418
     }
419 419
 
420 420
     protected function resetCounts() {
421
-        $this->counts[ 'segments_count_array' ] = [];
422
-        $this->counts[ 'raw_word_count' ]       = 0;
423
-        $this->counts[ 'eq_word_count' ]        = 0;
421
+        $this->counts['segments_count_array'] = [];
422
+        $this->counts['raw_word_count']       = 0;
423
+        $this->counts['eq_word_count']        = 0;
424 424
     }
425 425
 
426 426
     /**
@@ -429,16 +429,16 @@  discard block
 block discarded – undo
429 429
      *
430 430
      * @return void
431 431
      */
432
-    protected function checkForSelfClosedTagAndFlush( $parser, string $tag ) {
432
+    protected function checkForSelfClosedTagAndFlush($parser, string $tag) {
433 433
 
434
-        $lastChar = $this->getLastCharacter( $parser );
434
+        $lastChar = $this->getLastCharacter($parser);
435 435
 
436 436
         //trim last space
437
-        $tag = rtrim( $tag );
437
+        $tag = rtrim($tag);
438 438
 
439 439
         //detect empty tag
440 440
         $this->isEmpty = $lastChar == '/';
441
-        if ( $this->isEmpty ) {
441
+        if ($this->isEmpty) {
442 442
             $tag .= $lastChar;
443 443
         }
444 444
 
@@ -446,11 +446,11 @@  discard block
 block discarded – undo
446 446
         $tag .= ">";
447 447
 
448 448
         //set a Buffer for the segSource Source tag
449
-        if ( $this->bufferIsActive ) { // we are opening a critical CDATA section
449
+        if ($this->bufferIsActive) { // we are opening a critical CDATA section
450 450
             //these are NOT source/seg-source/value empty tags, THERE IS A CONTENT, write it in buffer
451 451
             $this->CDATABuffer .= $tag;
452 452
         } else {
453
-            $this->postProcAndFlush( $this->outputFP, $tag );
453
+            $this->postProcAndFlush($this->outputFP, $tag);
454 454
         }
455 455
 
456 456
     }
@@ -475,18 +475,18 @@  discard block
 block discarded – undo
475 475
          */
476 476
         $this->lastTransUnit = [];
477 477
 
478
-        if ( !isset( $this->transUnits[ $this->currentTransUnitId ] ) ) {
478
+        if (!isset($this->transUnits[$this->currentTransUnitId])) {
479 479
             return;
480 480
         }
481 481
 
482
-        $listOfSegmentsIds = $this->transUnits[ $this->currentTransUnitId ];
482
+        $listOfSegmentsIds = $this->transUnits[$this->currentTransUnitId];
483 483
         $last_value        = null;
484
-        $segmentsCount     = count( $listOfSegmentsIds );
485
-        for ( $i = 0; $i < $segmentsCount; $i++ ) {
486
-            $id = $listOfSegmentsIds[ $i ];
487
-            if ( isset( $this->segments[ $id ] ) && ( $i == 0 || $last_value + 1 == $listOfSegmentsIds[ $i ] ) ) {
488
-                $last_value            = $listOfSegmentsIds[ $i ];
489
-                $this->lastTransUnit[] = $this->segments[ $id ];
484
+        $segmentsCount     = count($listOfSegmentsIds);
485
+        for ($i = 0; $i < $segmentsCount; $i++) {
486
+            $id = $listOfSegmentsIds[$i];
487
+            if (isset($this->segments[$id]) && ($i == 0 || $last_value + 1 == $listOfSegmentsIds[$i])) {
488
+                $last_value            = $listOfSegmentsIds[$i];
489
+                $this->lastTransUnit[] = $this->segments[$id];
490 490
             }
491 491
         }
492 492
     }
@@ -497,10 +497,10 @@  discard block
 block discarded – undo
497 497
     protected function getCurrentSegment(): array {
498 498
         if (
499 499
             $this->currentTransUnitIsTranslatable !== 'no' &&
500
-            isset( $this->transUnits[ $this->currentTransUnitId ] ) &&
501
-            isset( $this->segments[ $this->segmentInUnitPosition ] )
500
+            isset($this->transUnits[$this->currentTransUnitId]) &&
501
+            isset($this->segments[$this->segmentInUnitPosition])
502 502
         ) {
503
-            return $this->segments[ $this->segmentInUnitPosition ];
503
+            return $this->segments[$this->segmentInUnitPosition];
504 504
         }
505 505
 
506 506
         return [];
Please login to merge, or discard this patch.
src/XliffReplacer/StatusToStateAttribute.php 1 patch
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -26,7 +26,7 @@  discard block
 block discarded – undo
26 26
             ?string $lastMrkState = null
27 27
     ): array {
28 28
 
29
-        $status = empty( $status ) ? TranslationStatus::STATUS_APPROVED2 : $status;
29
+        $status = empty($status) ? TranslationStatus::STATUS_APPROVED2 : $status;
30 30
 
31 31
         $stateLevelsMap = [
32 32
                 TranslationStatus::STATUS_APPROVED2  => 100,
@@ -37,26 +37,26 @@  discard block
 block discarded – undo
37 37
                 TranslationStatus::STATUS_NEW        => 50
38 38
         ];
39 39
 
40
-        $orderedValues = array_flip( $stateLevelsMap );
40
+        $orderedValues = array_flip($stateLevelsMap);
41 41
 
42 42
         // Define state mappings for different statuses
43 43
         $stateMap = [
44
-                TranslationStatus::STATUS_APPROVED2  => [ "state=\"final\"", TranslationStatus::STATUS_APPROVED2 ],
44
+                TranslationStatus::STATUS_APPROVED2  => ["state=\"final\"", TranslationStatus::STATUS_APPROVED2],
45 45
                 TranslationStatus::STATUS_APPROVED   => [
46
-                        ( $xliffVersion === 2 ) ? "state=\"reviewed\"" : "state=\"signed-off\"",
46
+                        ($xliffVersion === 2) ? "state=\"reviewed\"" : "state=\"signed-off\"",
47 47
                         TranslationStatus::STATUS_APPROVED
48 48
                 ],
49
-                TranslationStatus::STATUS_TRANSLATED => [ "state=\"translated\"", TranslationStatus::STATUS_TRANSLATED ],
49
+                TranslationStatus::STATUS_TRANSLATED => ["state=\"translated\"", TranslationStatus::STATUS_TRANSLATED],
50 50
                 TranslationStatus::STATUS_REJECTED   => [
51
-                        ( $xliffVersion === 2 ) ? "state=\"initial\"" : "state=\"needs-review-translation\"",
51
+                        ($xliffVersion === 2) ? "state=\"initial\"" : "state=\"needs-review-translation\"",
52 52
                         TranslationStatus::STATUS_REJECTED
53 53
                 ],
54 54
                 TranslationStatus::STATUS_NEW        => [
55
-                        ( $xliffVersion === 2 ) ? "state=\"initial\"" : "state=\"new\"",
55
+                        ($xliffVersion === 2) ? "state=\"initial\"" : "state=\"new\"",
56 56
                         TranslationStatus::STATUS_NEW
57 57
                 ],
58 58
                 TranslationStatus::STATUS_DRAFT      => [
59
-                        ( $xliffVersion === 2 ) ? "state=\"initial\"" : "state=\"new\"",
59
+                        ($xliffVersion === 2) ? "state=\"initial\"" : "state=\"new\"",
60 60
                         TranslationStatus::STATUS_DRAFT
61 61
                 ],
62 62
         ];
@@ -68,14 +68,14 @@  discard block
 block discarded – undo
68 68
         // ---> $seg[ 'status' ] is NULL
69 69
         // If lastMrkState is empty
70 70
         $minStatus = min(
71
-                $stateLevelsMap[ $status ],
72
-                ( $stateLevelsMap[ $lastMrkState ] ?? $stateLevelsMap[ TranslationStatus::STATUS_NEW ] )
71
+                $stateLevelsMap[$status],
72
+                ($stateLevelsMap[$lastMrkState] ?? $stateLevelsMap[TranslationStatus::STATUS_NEW])
73 73
         );
74 74
 
75 75
         // If the last mark state is set, get the minimum value, otherwise get the current state
76
-        [ $state_prop, $lastMrkState ] = empty( $lastMrkState ) ? $stateMap[ $status ] : $stateMap[ $orderedValues[ $minStatus ] ];
76
+        [$state_prop, $lastMrkState] = empty($lastMrkState) ? $stateMap[$status] : $stateMap[$orderedValues[$minStatus]];
77 77
 
78
-        return [ $state_prop, $lastMrkState ];
78
+        return [$state_prop, $lastMrkState];
79 79
 
80 80
     }
81 81
 
Please login to merge, or discard this patch.