Passed
Pull Request — master (#90)
by Domenico
02:57
created
src/XliffReplacer/AbstractXliffReplacer.php 1 patch
Spacing   +110 added lines, -110 removed lines patch added patch discarded remove patch
@@ -7,26 +7,26 @@  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   $isEmpty          = false;  // flag to check whether we are in an empty tag (<tag/>)
16
-    protected bool   $targetWasWritten = false;  // flag to check is <target> was written in the current unit
17
-    protected string $CDATABuffer      = "";       // buffer for special tag
18
-    protected bool   $bufferIsActive   = false;    // buffer for special tag
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   $isEmpty          = false; // flag to check whether we are in an empty tag (<tag/>)
16
+    protected bool   $targetWasWritten = false; // flag to check is <target> was written in the current unit
17
+    protected string $CDATABuffer      = ""; // buffer for special tag
18
+    protected bool   $bufferIsActive   = false; // buffer for special tag
19 19
 
20
-    protected int $offset = 0;         // offset for SAX pointer
20
+    protected int $offset = 0; // offset for SAX pointer
21 21
 
22
-    protected string  $currentBuffer;             // the current piece of text it's been parsed
23
-    protected int     $len;                       // length of the currentBuffer
24
-    protected array   $segments;                  // array of translations
22
+    protected string  $currentBuffer; // the current piece of text it's been parsed
23
+    protected int     $len; // length of the currentBuffer
24
+    protected array   $segments; // array of translations
25 25
     protected array   $lastTransUnit                  = [];
26 26
     protected int     $segmentInUnitPosition          = 0;
27
-    protected ?string $currentTransUnitId             = null;        // id of current <trans-unit>
27
+    protected ?string $currentTransUnitId             = null; // id of current <trans-unit>
28 28
     protected ?string $currentTransUnitIsTranslatable = null; // 'translate' attribute of current <trans-unit>
29
-    protected bool    $hasWrittenCounts               = false;  // check if <unit> already wrote segment counts (forXliff v 2.*)
29
+    protected bool    $hasWrittenCounts               = false; // check if <unit> already wrote segment counts (forXliff v 2.*)
30 30
     protected string  $targetLang;
31 31
     protected bool    $sourceInTarget                 = false;
32 32
 
@@ -76,10 +76,10 @@  discard block
 block discarded – undo
76 76
             XliffReplacerCallbackInterface $callback = null
77 77
     ) {
78 78
         self::$INTERNAL_TAG_PLACEHOLDER = $this->getInternalTagPlaceholder();
79
-        $this->createOutputFileIfDoesNotExist( $outputFilePath );
80
-        $this->setFileDescriptors( $originalXliffPath, $outputFilePath );
79
+        $this->createOutputFileIfDoesNotExist($outputFilePath);
80
+        $this->setFileDescriptors($originalXliffPath, $outputFilePath);
81 81
         $this->xliffVersion   = $xliffVersion;
82
-        $this->tuTagName      = ( $this->xliffVersion === 2 ) ? 'unit' : 'trans-unit';
82
+        $this->tuTagName      = ($this->xliffVersion === 2) ? 'unit' : 'trans-unit';
83 83
         $this->segments       = $segments;
84 84
         $this->targetLang     = $trgLang;
85 85
         $this->sourceInTarget = $setSourceInTarget;
@@ -89,17 +89,17 @@  discard block
 block discarded – undo
89 89
     }
90 90
 
91 91
     public function replaceTranslation() {
92
-        fwrite( $this->outputFP, '<?xml version="1.0" encoding="UTF-8"?>' );
92
+        fwrite($this->outputFP, '<?xml version="1.0" encoding="UTF-8"?>');
93 93
 
94 94
         //create Sax parser
95 95
         $xmlParser = $this->initSaxParser();
96 96
 
97
-        while ( $this->currentBuffer = fread( $this->originalFP, 4096 ) ) {
97
+        while ($this->currentBuffer = fread($this->originalFP, 4096)) {
98 98
             /*
99 99
                preprocess file
100 100
              */
101 101
             // obfuscate entities because sax automatically does html_entity_decode
102
-            $temporary_check_buffer = preg_replace( "/&(.*?);/", self::$INTERNAL_TAG_PLACEHOLDER . '$1' . self::$INTERNAL_TAG_PLACEHOLDER, $this->currentBuffer );
102
+            $temporary_check_buffer = preg_replace("/&(.*?);/", self::$INTERNAL_TAG_PLACEHOLDER . '$1' . self::$INTERNAL_TAG_PLACEHOLDER, $this->currentBuffer);
103 103
 
104 104
             //avoid cutting entities in half:
105 105
             //the last fread could have truncated an entity (say, '&lt;' in '&l'), thus invalidating the escaping
@@ -107,36 +107,36 @@  discard block
 block discarded – undo
107 107
             // 9 is the max length of an entity. So, suppose that the & is at the end of buffer,
108 108
             // add 9 Bytes and substitute the entities, if the & is present, and it is not at the end
109 109
             //it can't be an entity, exit the loop
110
-            while ( true ) {
111
-                $_ampPos = strpos( $temporary_check_buffer, '&' );
110
+            while (true) {
111
+                $_ampPos = strpos($temporary_check_buffer, '&');
112 112
 
113 113
                 //check for real entity or escape it to safely exit from the loop!!!
114
-                if ( $_ampPos === false || strlen( substr( $temporary_check_buffer, $_ampPos ) ) > 9 ) {
114
+                if ($_ampPos === false || strlen(substr($temporary_check_buffer, $_ampPos)) > 9) {
115 115
                     break;
116 116
                 }
117 117
 
118 118
                 //if an entity is still present, fetch some more and repeat the escaping
119
-                $this->currentBuffer    .= fread( $this->originalFP, 9 );
120
-                $temporary_check_buffer = preg_replace( "/&(.*?);/", self::$INTERNAL_TAG_PLACEHOLDER . '$1' . self::$INTERNAL_TAG_PLACEHOLDER, $this->currentBuffer );
119
+                $this->currentBuffer .= fread($this->originalFP, 9);
120
+                $temporary_check_buffer = preg_replace("/&(.*?);/", self::$INTERNAL_TAG_PLACEHOLDER . '$1' . self::$INTERNAL_TAG_PLACEHOLDER, $this->currentBuffer);
121 121
             }
122 122
 
123 123
             //free stuff outside the loop
124
-            unset( $temporary_check_buffer );
124
+            unset($temporary_check_buffer);
125 125
 
126
-            $this->currentBuffer = preg_replace( "/&(.*?);/", self::$INTERNAL_TAG_PLACEHOLDER . '$1' . self::$INTERNAL_TAG_PLACEHOLDER, $this->currentBuffer );
127
-            $this->currentBuffer = str_replace( "&", self::$INTERNAL_TAG_PLACEHOLDER . 'amp' . self::$INTERNAL_TAG_PLACEHOLDER, $this->currentBuffer );
126
+            $this->currentBuffer = preg_replace("/&(.*?);/", self::$INTERNAL_TAG_PLACEHOLDER . '$1' . self::$INTERNAL_TAG_PLACEHOLDER, $this->currentBuffer);
127
+            $this->currentBuffer = str_replace("&", self::$INTERNAL_TAG_PLACEHOLDER . 'amp' . self::$INTERNAL_TAG_PLACEHOLDER, $this->currentBuffer);
128 128
 
129 129
             //get length of chunk
130
-            $this->len = strlen( $this->currentBuffer );
130
+            $this->len = strlen($this->currentBuffer);
131 131
 
132 132
             //parse chunk of text
133
-            if ( !xml_parse( $xmlParser, $this->currentBuffer, feof( $this->originalFP ) ) ) {
133
+            if (!xml_parse($xmlParser, $this->currentBuffer, feof($this->originalFP))) {
134 134
                 //if unable, raise an exception
135
-                throw new RuntimeException( sprintf(
135
+                throw new RuntimeException(sprintf(
136 136
                         "XML error: %s at line %d",
137
-                        xml_error_string( xml_get_error_code( $xmlParser ) ),
138
-                        xml_get_current_line_number( $xmlParser )
139
-                ) );
137
+                        xml_error_string(xml_get_error_code($xmlParser)),
138
+                        xml_get_current_line_number($xmlParser)
139
+                ));
140 140
             }
141 141
             /*
142 142
             * Get the accumulated this->offset in the document:
@@ -147,7 +147,7 @@  discard block
 block discarded – undo
147 147
         }
148 148
 
149 149
         // close Sax parser
150
-        $this->closeSaxParser( $xmlParser );
150
+        $this->closeSaxParser($xmlParser);
151 151
 
152 152
     }
153 153
 
@@ -156,24 +156,24 @@  discard block
 block discarded – undo
156 156
      *
157 157
      * @return string
158 158
      */
159
-    protected function getLastCharacter( $parser ): string {
159
+    protected function getLastCharacter($parser): string {
160 160
 
161 161
         //this logic helps detecting empty tags
162 162
         //get current position of SAX pointer in all the stream of data is has read so far:
163 163
         //it points at the end of current tag
164
-        $idx = xml_get_current_byte_index( $parser );
164
+        $idx = xml_get_current_byte_index($parser);
165 165
 
166 166
         //check whether the bounds of current tag are entirely in current buffer or the end of the current tag
167 167
         //is outside current buffer (in the latter case, it's in next buffer to be read by the while loop);
168 168
         //this check is necessary because we may have truncated a tag in half with current read,
169 169
         //and the other half may be encountered in the next buffer it will be passed
170
-        if ( isset( $this->currentBuffer[ $idx - $this->offset ] ) ) {
170
+        if (isset($this->currentBuffer[$idx - $this->offset])) {
171 171
             //if this tag entire lenght fitted in the buffer, the last char must be the last
172 172
             //symbol before the '>'; if it's an empty tag, it is assumed that it's a '/'
173
-            $lastChar = $this->currentBuffer[ $idx - $this->offset ];
173
+            $lastChar = $this->currentBuffer[$idx - $this->offset];
174 174
         } else {
175 175
             //if it's out, simple use the last character of the chunk
176
-            $lastChar = $this->currentBuffer[ $this->len - 1 ];
176
+            $lastChar = $this->currentBuffer[$this->len - 1];
177 177
         }
178 178
 
179 179
         return $lastChar;
@@ -187,19 +187,19 @@  discard block
 block discarded – undo
187 187
         return "§" .
188 188
                 substr(
189 189
                         str_replace(
190
-                                [ '+', '/' ],
190
+                                ['+', '/'],
191 191
                                 '',
192
-                                base64_encode( openssl_random_pseudo_bytes( 10, $_crypto_strong ) )
192
+                                base64_encode(openssl_random_pseudo_bytes(10, $_crypto_strong))
193 193
                         ),
194 194
                         0,
195 195
                         4
196 196
                 );
197 197
     }
198 198
 
199
-    private function createOutputFileIfDoesNotExist( string $outputFilePath ) {
199
+    private function createOutputFileIfDoesNotExist(string $outputFilePath) {
200 200
         // create output file
201
-        if ( !file_exists( $outputFilePath ) ) {
202
-            touch( $outputFilePath );
201
+        if (!file_exists($outputFilePath)) {
202
+            touch($outputFilePath);
203 203
         }
204 204
     }
205 205
 
@@ -207,13 +207,13 @@  discard block
 block discarded – undo
207 207
      * @param string $originalXliffPath
208 208
      * @param string $outputFilePath
209 209
      */
210
-    private function setFileDescriptors( string $originalXliffPath, string $outputFilePath ) {
211
-        $this->outputFP = fopen( $outputFilePath, 'w+' );
210
+    private function setFileDescriptors(string $originalXliffPath, string $outputFilePath) {
211
+        $this->outputFP = fopen($outputFilePath, 'w+');
212 212
 
213 213
         $streamArgs = null;
214 214
 
215
-        if ( !( $this->originalFP = fopen( $originalXliffPath, "r", false, stream_context_create( $streamArgs ) ) ) ) {
216
-            throw new RuntimeException( "could not open XML input" );
215
+        if (!($this->originalFP = fopen($originalXliffPath, "r", false, stream_context_create($streamArgs)))) {
216
+            throw new RuntimeException("could not open XML input");
217 217
         }
218 218
     }
219 219
 
@@ -223,8 +223,8 @@  discard block
 block discarded – undo
223 223
     public function __destruct() {
224 224
         //this stream can be closed outside the class
225 225
         //to permit multiple concurrent downloads, so suppress warnings
226
-        @fclose( $this->originalFP );
227
-        fclose( $this->outputFP );
226
+        @fclose($this->originalFP);
227
+        fclose($this->outputFP);
228 228
     }
229 229
 
230 230
     /**
@@ -233,11 +233,11 @@  discard block
 block discarded – undo
233 233
      * @return resource
234 234
      */
235 235
     protected function initSaxParser() {
236
-        $xmlSaxParser = xml_parser_create( 'UTF-8' );
237
-        xml_set_object( $xmlSaxParser, $this );
238
-        xml_parser_set_option( $xmlSaxParser, XML_OPTION_CASE_FOLDING, false );
239
-        xml_set_element_handler( $xmlSaxParser, 'tagOpen', 'tagClose' );
240
-        xml_set_character_data_handler( $xmlSaxParser, 'characterData' );
236
+        $xmlSaxParser = xml_parser_create('UTF-8');
237
+        xml_set_object($xmlSaxParser, $this);
238
+        xml_parser_set_option($xmlSaxParser, XML_OPTION_CASE_FOLDING, false);
239
+        xml_set_element_handler($xmlSaxParser, 'tagOpen', 'tagClose');
240
+        xml_set_character_data_handler($xmlSaxParser, 'characterData');
241 241
 
242 242
         return $xmlSaxParser;
243 243
     }
@@ -245,8 +245,8 @@  discard block
 block discarded – undo
245 245
     /**
246 246
      * @param resource $xmlSaxParser
247 247
      */
248
-    protected function closeSaxParser( $xmlSaxParser ) {
249
-        xml_parser_free( $xmlSaxParser );
248
+    protected function closeSaxParser($xmlSaxParser) {
249
+        xml_parser_free($xmlSaxParser);
250 250
     }
251 251
 
252 252
     /**
@@ -256,7 +256,7 @@  discard block
 block discarded – undo
256 256
      *
257 257
      * @return mixed
258 258
      */
259
-    abstract protected function tagOpen( $parser, string $name, array $attr );
259
+    abstract protected function tagOpen($parser, string $name, array $attr);
260 260
 
261 261
     /**
262 262
      * @param resource $parser
@@ -264,7 +264,7 @@  discard block
 block discarded – undo
264 264
      *
265 265
      * @return mixed
266 266
      */
267
-    abstract protected function tagClose( $parser, string $name );
267
+    abstract protected function tagClose($parser, string $name);
268 268
 
269 269
     /**
270 270
      * @param resource $parser
@@ -272,11 +272,11 @@  discard block
 block discarded – undo
272 272
      *
273 273
      * @return mixed
274 274
      */
275
-    protected function characterData( $parser, string $data ): void {
275
+    protected function characterData($parser, string $data): void {
276 276
         // don't write <target> data
277
-        if ( !$this->inTarget && !$this->bufferIsActive ) {
278
-            $this->postProcAndFlush( $this->outputFP, $data );
279
-        } elseif ( $this->bufferIsActive ) {
277
+        if (!$this->inTarget && !$this->bufferIsActive) {
278
+            $this->postProcAndFlush($this->outputFP, $data);
279
+        } elseif ($this->bufferIsActive) {
280 280
             $this->CDATABuffer .= $data;
281 281
         }
282 282
     }
@@ -288,19 +288,19 @@  discard block
 block discarded – undo
288 288
      * @param string   $data
289 289
      * @param bool     $treatAsCDATA
290 290
      */
291
-    protected function postProcAndFlush( $fp, string $data, bool $treatAsCDATA = false ) {
291
+    protected function postProcAndFlush($fp, string $data, bool $treatAsCDATA = false) {
292 292
         //postprocess string
293
-        $data = preg_replace( "/" . self::$INTERNAL_TAG_PLACEHOLDER . '(.*?)' . self::$INTERNAL_TAG_PLACEHOLDER . "/", '&$1;', $data );
294
-        $data = str_replace( '&nbsp;', ' ', $data );
295
-        if ( !$treatAsCDATA ) {
293
+        $data = preg_replace("/" . self::$INTERNAL_TAG_PLACEHOLDER . '(.*?)' . self::$INTERNAL_TAG_PLACEHOLDER . "/", '&$1;', $data);
294
+        $data = str_replace('&nbsp;', ' ', $data);
295
+        if (!$treatAsCDATA) {
296 296
             //unix2dos
297
-            $data = str_replace( "\r\n", "\r", $data );
298
-            $data = str_replace( "\n", "\r", $data );
299
-            $data = str_replace( "\r", "\r\n", $data );
297
+            $data = str_replace("\r\n", "\r", $data);
298
+            $data = str_replace("\n", "\r", $data);
299
+            $data = str_replace("\r", "\r\n", $data);
300 300
         }
301 301
 
302 302
         //flush to disk
303
-        fwrite( $fp, $data );
303
+        fwrite($fp, $data);
304 304
     }
305 305
 
306 306
     /**
@@ -309,19 +309,19 @@  discard block
 block discarded – undo
309 309
      *
310 310
      * @return void
311 311
      */
312
-    protected function handleOpenUnit( string $name, array $attr ) {
312
+    protected function handleOpenUnit(string $name, array $attr) {
313 313
 
314 314
         // check if we are entering into a <trans-unit> (xliff v1.*) or <unit> (xliff v2.*)
315
-        if ( $this->tuTagName === $name ) {
315
+        if ($this->tuTagName === $name) {
316 316
             $this->inTU = true;
317 317
 
318 318
             // get id
319 319
             // trim to first 100 characters because this is the limit on Matecat's DB
320
-            $this->currentTransUnitId = substr( $attr[ 'id' ], 0, 100 );
320
+            $this->currentTransUnitId = substr($attr['id'], 0, 100);
321 321
 
322 322
             // `translate` attribute can be only yes or no
323 323
             // current 'translate' attribute of the current trans-unit
324
-            $this->currentTransUnitIsTranslatable = empty( $attr[ 'translate' ] ) ? 'yes' : $attr[ 'translate' ];
324
+            $this->currentTransUnitIsTranslatable = empty($attr['translate']) ? 'yes' : $attr['translate'];
325 325
 
326 326
             $this->setLastTransUnitSegments();
327 327
 
@@ -335,15 +335,15 @@  discard block
 block discarded – undo
335 335
      *
336 336
      * @return string
337 337
      */
338
-    protected function handleOpenXliffTag( string $name, array $attr, string $tag ): string {
338
+    protected function handleOpenXliffTag(string $name, array $attr, string $tag): string {
339 339
 
340 340
         // Add MateCat specific namespace.
341 341
         // Add trgLang
342
-        if ( $name === 'xliff' ) {
343
-            if ( !array_key_exists( 'xmlns:mtc', $attr ) ) {
342
+        if ($name === 'xliff') {
343
+            if (!array_key_exists('xmlns:mtc', $attr)) {
344 344
                 $tag .= ' xmlns:mtc="https://www.matecat.com" ';
345 345
             }
346
-            $tag = preg_replace( '/trgLang="(.*?)"/', 'trgLang="' . $this->targetLang . '"', $tag );
346
+            $tag = preg_replace('/trgLang="(.*?)"/', 'trgLang="' . $this->targetLang . '"', $tag);
347 347
         }
348 348
 
349 349
         return $tag;
@@ -355,10 +355,10 @@  discard block
 block discarded – undo
355 355
      *
356 356
      * @return void
357 357
      */
358
-    protected function checkSetInTarget( string $name ) {
358
+    protected function checkSetInTarget(string $name) {
359 359
         // check if we are entering into a <target>
360
-        if ( 'target' === $name ) {
361
-            if ( $this->currentTransUnitIsTranslatable === 'no' ) {
360
+        if ('target' === $name) {
361
+            if ($this->currentTransUnitIsTranslatable === 'no') {
362 362
                 $this->inTarget = false;
363 363
             } else {
364 364
                 $this->inTarget = true;
@@ -371,8 +371,8 @@  discard block
 block discarded – undo
371 371
      *
372 372
      * @return void
373 373
      */
374
-    protected function setInBuffer( string $name ) {
375
-        if ( in_array( $name, $this->nodesToBuffer ) ) {
374
+    protected function setInBuffer(string $name) {
375
+        if (in_array($name, $this->nodesToBuffer)) {
376 376
             $this->bufferIsActive = true;
377 377
         }
378 378
     }
@@ -380,24 +380,24 @@  discard block
 block discarded – undo
380 380
     /**
381 381
      * @param array $seg
382 382
      */
383
-    protected function updateSegmentCounts( array $seg = [] ) {
383
+    protected function updateSegmentCounts(array $seg = []) {
384 384
 
385
-        $raw_word_count = $seg[ 'raw_word_count' ];
386
-        $eq_word_count  = ( floor( $seg[ 'eq_word_count' ] * 100 ) / 100 );
385
+        $raw_word_count = $seg['raw_word_count'];
386
+        $eq_word_count  = (floor($seg['eq_word_count'] * 100) / 100);
387 387
 
388
-        $this->counts[ 'segments_count_array' ][ $seg[ 'sid' ] ] = [
388
+        $this->counts['segments_count_array'][$seg['sid']] = [
389 389
                 'raw_word_count' => $raw_word_count,
390 390
                 'eq_word_count'  => $eq_word_count,
391 391
         ];
392 392
 
393
-        $this->counts[ 'raw_word_count' ] += $raw_word_count;
394
-        $this->counts[ 'eq_word_count' ]  += $eq_word_count;
393
+        $this->counts['raw_word_count'] += $raw_word_count;
394
+        $this->counts['eq_word_count']  += $eq_word_count;
395 395
     }
396 396
 
397 397
     protected function resetCounts() {
398
-        $this->counts[ 'segments_count_array' ] = [];
399
-        $this->counts[ 'raw_word_count' ]       = 0;
400
-        $this->counts[ 'eq_word_count' ]        = 0;
398
+        $this->counts['segments_count_array'] = [];
399
+        $this->counts['raw_word_count']       = 0;
400
+        $this->counts['eq_word_count']        = 0;
401 401
     }
402 402
 
403 403
     /**
@@ -406,16 +406,16 @@  discard block
 block discarded – undo
406 406
      *
407 407
      * @return void
408 408
      */
409
-    protected function checkForSelfClosedTagAndFlush( $parser, string $tag ) {
409
+    protected function checkForSelfClosedTagAndFlush($parser, string $tag) {
410 410
 
411
-        $lastChar = $this->getLastCharacter( $parser );
411
+        $lastChar = $this->getLastCharacter($parser);
412 412
 
413 413
         //trim last space
414
-        $tag = rtrim( $tag );
414
+        $tag = rtrim($tag);
415 415
 
416 416
         //detect empty tag
417 417
         $this->isEmpty = $lastChar == '/';
418
-        if ( $this->isEmpty ) {
418
+        if ($this->isEmpty) {
419 419
             $tag .= $lastChar;
420 420
         }
421 421
 
@@ -423,11 +423,11 @@  discard block
 block discarded – undo
423 423
         $tag .= ">";
424 424
 
425 425
         //set a Buffer for the segSource Source tag
426
-        if ( $this->bufferIsActive ) { // we are opening a critical CDATA section
426
+        if ($this->bufferIsActive) { // we are opening a critical CDATA section
427 427
             //these are NOT source/seg-source/value empty tags, THERE IS A CONTENT, write it in buffer
428 428
             $this->CDATABuffer .= $tag;
429 429
         } else {
430
-            $this->postProcAndFlush( $this->outputFP, $tag );
430
+            $this->postProcAndFlush($this->outputFP, $tag);
431 431
         }
432 432
 
433 433
     }
@@ -452,18 +452,18 @@  discard block
 block discarded – undo
452 452
          */
453 453
         $this->lastTransUnit = [];
454 454
 
455
-        if ( !isset( $this->transUnits[ $this->currentTransUnitId ] ) ) {
455
+        if (!isset($this->transUnits[$this->currentTransUnitId])) {
456 456
             return;
457 457
         }
458 458
 
459
-        $listOfSegmentsIds = $this->transUnits[ $this->currentTransUnitId ];
459
+        $listOfSegmentsIds = $this->transUnits[$this->currentTransUnitId];
460 460
         $last_value        = null;
461
-        $segmentsCount     = count( $listOfSegmentsIds );
462
-        for ( $i = 0; $i < $segmentsCount; $i++ ) {
463
-            $id = $listOfSegmentsIds[ $i ];
464
-            if ( isset( $this->segments[ $id ] ) && ( $i == 0 || $last_value + 1 == $listOfSegmentsIds[ $i ] ) ) {
465
-                $last_value            = $listOfSegmentsIds[ $i ];
466
-                $this->lastTransUnit[] = $this->segments[ $id ];
461
+        $segmentsCount     = count($listOfSegmentsIds);
462
+        for ($i = 0; $i < $segmentsCount; $i++) {
463
+            $id = $listOfSegmentsIds[$i];
464
+            if (isset($this->segments[$id]) && ($i == 0 || $last_value + 1 == $listOfSegmentsIds[$i])) {
465
+                $last_value            = $listOfSegmentsIds[$i];
466
+                $this->lastTransUnit[] = $this->segments[$id];
467 467
             }
468 468
         }
469 469
 
@@ -473,8 +473,8 @@  discard block
 block discarded – undo
473 473
      * @return array
474 474
      */
475 475
     protected function getCurrentSegment(): array {
476
-        if ( $this->currentTransUnitIsTranslatable !== 'no' && isset( $this->transUnits[ $this->currentTransUnitId ] ) ) {
477
-            return $this->segments[ $this->segmentInUnitPosition ];
476
+        if ($this->currentTransUnitIsTranslatable !== 'no' && isset($this->transUnits[$this->currentTransUnitId])) {
477
+            return $this->segments[$this->segmentInUnitPosition];
478 478
         }
479 479
 
480 480
         return [];
Please login to merge, or discard this patch.
src/Utils/Files.php 1 patch
Spacing   +28 added lines, -28 removed lines patch added patch discarded remove patch
@@ -18,15 +18,15 @@  discard block
 block discarded – undo
18 18
      *
19 19
      * @return array|mixed
20 20
      */
21
-    public static function pathInfo( string $path, ?int $options = 15 ) {
22
-        $rawPath = explode( DIRECTORY_SEPARATOR, $path );
21
+    public static function pathInfo(string $path, ?int $options = 15) {
22
+        $rawPath = explode(DIRECTORY_SEPARATOR, $path);
23 23
 
24
-        $basename = array_pop( $rawPath );
25
-        $dirname  = implode( DIRECTORY_SEPARATOR, $rawPath );
24
+        $basename = array_pop($rawPath);
25
+        $dirname  = implode(DIRECTORY_SEPARATOR, $rawPath);
26 26
 
27
-        $explodedFileName = explode( ".", $basename );
28
-        $extension        = strtolower( array_pop( $explodedFileName ) );
29
-        $filename         = implode( ".", $explodedFileName );
27
+        $explodedFileName = explode(".", $basename);
28
+        $extension        = strtolower(array_pop($explodedFileName));
29
+        $filename         = implode(".", $explodedFileName);
30 30
 
31 31
         $returnArray = [];
32 32
 
@@ -39,17 +39,17 @@  discard block
 block discarded – undo
39 39
 
40 40
         // foreach flag, add in $return_array the corresponding field,
41 41
         // obtained by variable name correspondence
42
-        foreach ( $flagMap as $field => $i ) {
42
+        foreach ($flagMap as $field => $i) {
43 43
             //binary AND
44
-            if ( ( $options & $i ) > 0 ) {
44
+            if (($options & $i) > 0) {
45 45
                 //variable substitution: $field can be one between 'dirname', 'basename', 'extension', 'filename'
46 46
                 // $$field gets the value of the variable named $field
47
-                $returnArray[ $field ] = $$field;
47
+                $returnArray[$field] = $$field;
48 48
             }
49 49
         }
50 50
 
51
-        if ( count( $returnArray ) == 1 ) {
52
-            $returnArray = array_pop( $returnArray );
51
+        if (count($returnArray) == 1) {
52
+            $returnArray = array_pop($returnArray);
53 53
         }
54 54
 
55 55
         return $returnArray;
@@ -60,14 +60,14 @@  discard block
 block discarded – undo
60 60
      *
61 61
      * @return ?string
62 62
      */
63
-    public static function getExtension( $path ): ?string {
64
-        $pathInfo = self::pathInfo( $path );
63
+    public static function getExtension($path): ?string {
64
+        $pathInfo = self::pathInfo($path);
65 65
 
66
-        if ( empty( $pathInfo ) ) {
66
+        if (empty($pathInfo)) {
67 67
             return null;
68 68
         }
69 69
 
70
-        return strtolower( $pathInfo[ 'extension' ] );
70
+        return strtolower($pathInfo['extension']);
71 71
     }
72 72
 
73 73
     /**
@@ -75,14 +75,14 @@  discard block
 block discarded – undo
75 75
      *
76 76
      * @return bool
77 77
      */
78
-    public static function isXliff( ?string $path ): bool {
79
-        $extension = self::getExtension( $path );
78
+    public static function isXliff(?string $path): bool {
79
+        $extension = self::getExtension($path);
80 80
 
81
-        if ( !$extension ) {
81
+        if (!$extension) {
82 82
             return false;
83 83
         }
84 84
 
85
-        switch ( $extension ) {
85
+        switch ($extension) {
86 86
             case 'xliff':
87 87
             case 'sdlxliff':
88 88
             case 'tmx':
@@ -98,14 +98,14 @@  discard block
 block discarded – undo
98 98
      *
99 99
      * @return bool|string
100 100
      */
101
-    public static function getMemoryFileType( string $path ) {
102
-        $pathInfo = self::pathInfo( $path );
101
+    public static function getMemoryFileType(string $path) {
102
+        $pathInfo = self::pathInfo($path);
103 103
 
104
-        if ( empty( $pathInfo ) ) {
104
+        if (empty($pathInfo)) {
105 105
             return false;
106 106
         }
107 107
 
108
-        switch ( strtolower( $pathInfo[ 'extension' ] ) ) {
108
+        switch (strtolower($pathInfo['extension'])) {
109 109
             case 'tmx':
110 110
                 return 'tmx';
111 111
             case 'g':
@@ -120,8 +120,8 @@  discard block
 block discarded – undo
120 120
      *
121 121
      * @return bool
122 122
      */
123
-    public static function isTMXFile( $path ): bool {
124
-        return self::getMemoryFileType( $path ) === 'tmx';
123
+    public static function isTMXFile($path): bool {
124
+        return self::getMemoryFileType($path) === 'tmx';
125 125
     }
126 126
 
127 127
     /**
@@ -129,7 +129,7 @@  discard block
 block discarded – undo
129 129
      *
130 130
      * @return bool
131 131
      */
132
-    public static function isGlossaryFile( $path ): bool {
133
-        return self::getMemoryFileType( $path ) === 'glossary';
132
+    public static function isGlossaryFile($path): bool {
133
+        return self::getMemoryFileType($path) === 'glossary';
134 134
     }
135 135
 }
Please login to merge, or discard this patch.
src/XliffUtils/XliffProprietaryDetect.php 1 patch
Spacing   +57 added lines, -57 removed lines patch added patch discarded remove patch
@@ -22,11 +22,11 @@  discard block
 block discarded – undo
22 22
      *
23 23
      * @return array
24 24
      */
25
-    public static function getInfoFromXliffContent( string $xliffContent ): array {
25
+    public static function getInfoFromXliffContent(string $xliffContent): array {
26 26
         self::reset();
27
-        $tmp = self::getFirst1024CharsFromXliff( $xliffContent );
27
+        $tmp = self::getFirst1024CharsFromXliff($xliffContent);
28 28
 
29
-        return self::getInfoFromTmp( $tmp );
29
+        return self::getInfoFromTmp($tmp);
30 30
     }
31 31
 
32 32
     /**
@@ -34,12 +34,12 @@  discard block
 block discarded – undo
34 34
      *
35 35
      * @return array
36 36
      */
37
-    public static function getInfo( string $fullPathToFile ): array {
37
+    public static function getInfo(string $fullPathToFile): array {
38 38
         self::reset();
39
-        $tmp                      = self::getFirst1024CharsFromXliff( null, $fullPathToFile );
40
-        self::$fileType[ 'info' ] = Files::pathInfo( $fullPathToFile );
39
+        $tmp                      = self::getFirst1024CharsFromXliff(null, $fullPathToFile);
40
+        self::$fileType['info'] = Files::pathInfo($fullPathToFile);
41 41
 
42
-        return self::getInfoFromTmp( $tmp );
42
+        return self::getInfoFromTmp($tmp);
43 43
     }
44 44
 
45 45
     /**
@@ -47,21 +47,21 @@  discard block
 block discarded – undo
47 47
      *
48 48
      * @return array
49 49
      */
50
-    private static function getInfoFromTmp( array $tmp ): array {
50
+    private static function getInfoFromTmp(array $tmp): array {
51 51
         try {
52
-            self::checkVersion( $tmp );
53
-        } catch ( Exception $ignore ) {
52
+            self::checkVersion($tmp);
53
+        } catch (Exception $ignore) {
54 54
             // do nothing
55 55
             // self::$fileType[ 'version' ] is left empty
56 56
         }
57 57
 
58 58
         // run CheckXliffProprietaryPipeline
59
-        $pipeline = self::runPipeline( $tmp );
59
+        $pipeline = self::runPipeline($tmp);
60 60
 
61
-        self::$fileType[ 'proprietary' ]            = $pipeline[ 'proprietary' ];
62
-        self::$fileType[ 'proprietary_name' ]       = $pipeline[ 'proprietary_name' ];
63
-        self::$fileType[ 'proprietary_short_name' ] = $pipeline[ 'proprietary_short_name' ];
64
-        self::$fileType[ 'converter_version' ]      = $pipeline[ 'converter_version' ];
61
+        self::$fileType['proprietary']            = $pipeline['proprietary'];
62
+        self::$fileType['proprietary_name']       = $pipeline['proprietary_name'];
63
+        self::$fileType['proprietary_short_name'] = $pipeline['proprietary_short_name'];
64
+        self::$fileType['converter_version']      = $pipeline['converter_version'];
65 65
 
66 66
         return self::$fileType;
67 67
     }
@@ -71,12 +71,12 @@  discard block
 block discarded – undo
71 71
      *
72 72
      * @return array
73 73
      */
74
-    private static function runPipeline( ?array $tmp = [] ): array {
75
-        $pipeline = new CheckXliffProprietaryPipeline( $tmp );
76
-        $pipeline->addCheck( new CheckSDL() );
77
-        $pipeline->addCheck( new CheckGlobalSight() );
78
-        $pipeline->addCheck( new CheckMateCATConverter() );
79
-        $pipeline->addCheck( new CheckXliffVersion2() );
74
+    private static function runPipeline(?array $tmp = []): array {
75
+        $pipeline = new CheckXliffProprietaryPipeline($tmp);
76
+        $pipeline->addCheck(new CheckSDL());
77
+        $pipeline->addCheck(new CheckGlobalSight());
78
+        $pipeline->addCheck(new CheckMateCATConverter());
79
+        $pipeline->addCheck(new CheckXliffVersion2());
80 80
 
81 81
         return $pipeline->run();
82 82
     }
@@ -93,21 +93,21 @@  discard block
 block discarded – undo
93 93
         ];
94 94
     }
95 95
 
96
-    private static function getFirst1024CharsFromString( ?string $stringData ): string {
97
-        if ( !empty( $stringData ) ) {
98
-            return substr( $stringData, 0, 1024 );
96
+    private static function getFirst1024CharsFromString(?string $stringData): string {
97
+        if (!empty($stringData)) {
98
+            return substr($stringData, 0, 1024);
99 99
         }
100 100
 
101 101
         return '';
102 102
     }
103 103
 
104
-    private static function getFirst1024CharsFromFile( string $fullPathToFile ): string {
104
+    private static function getFirst1024CharsFromFile(string $fullPathToFile): string {
105 105
         $stringData = '';
106
-        if ( !empty( $fullPathToFile ) && is_file( $fullPathToFile ) ) {
107
-            $file_pointer = fopen( "$fullPathToFile", 'r' );
106
+        if (!empty($fullPathToFile) && is_file($fullPathToFile)) {
107
+            $file_pointer = fopen("$fullPathToFile", 'r');
108 108
             // Checking Requirements (By specs, I know that xliff version is in the first 1KB)
109
-            $stringData = fread( $file_pointer, 1024 );
110
-            fclose( $file_pointer );
109
+            $stringData = fread($file_pointer, 1024);
110
+            fclose($file_pointer);
111 111
         }
112 112
 
113 113
         return $stringData;
@@ -120,13 +120,13 @@  discard block
 block discarded – undo
120 120
      *
121 121
      * @return string[]
122 122
      */
123
-    private static function getFirst1024CharsFromXliff( ?string $stringData = null, string $fullPathToFile = null ): ?array {
124
-        $stringData = static::getFirst1024CharsFromString( $stringData );
125
-        if ( empty( $stringData ) ) {
126
-            $stringData = static::getFirst1024CharsFromFile( $fullPathToFile );
123
+    private static function getFirst1024CharsFromXliff(?string $stringData = null, string $fullPathToFile = null): ?array {
124
+        $stringData = static::getFirst1024CharsFromString($stringData);
125
+        if (empty($stringData)) {
126
+            $stringData = static::getFirst1024CharsFromFile($fullPathToFile);
127 127
         }
128 128
 
129
-        return !empty( $stringData ) ? [ $stringData ] : [];
129
+        return !empty($stringData) ? [$stringData] : [];
130 130
     }
131 131
 
132 132
     /**
@@ -135,9 +135,9 @@  discard block
 block discarded – undo
135 135
      * @throws NotSupportedVersionException
136 136
      * @throws NotValidFileException
137 137
      */
138
-    protected static function checkVersion( array $tmp ) {
139
-        if ( isset( $tmp[ 0 ] ) ) {
140
-            self::$fileType[ 'version' ] = XliffVersionDetector::detect( $tmp[ 0 ] );
138
+    protected static function checkVersion(array $tmp) {
139
+        if (isset($tmp[0])) {
140
+            self::$fileType['version'] = XliffVersionDetector::detect($tmp[0]);
141 141
         }
142 142
     }
143 143
 
@@ -148,20 +148,20 @@  discard block
 block discarded – undo
148 148
      * @throws NotSupportedVersionException
149 149
      * @throws NotValidFileException
150 150
      */
151
-    public static function getInfoByStringData( string $stringData ): array {
151
+    public static function getInfoByStringData(string $stringData): array {
152 152
         self::reset();
153 153
 
154
-        $tmp                      = self::getFirst1024CharsFromXliff( $stringData );
155
-        self::$fileType[ 'info' ] = [];
156
-        self::checkVersion( $tmp );
154
+        $tmp                      = self::getFirst1024CharsFromXliff($stringData);
155
+        self::$fileType['info'] = [];
156
+        self::checkVersion($tmp);
157 157
 
158 158
         // run CheckXliffProprietaryPipeline
159
-        $pipeline = self::runPipeline( $tmp );
159
+        $pipeline = self::runPipeline($tmp);
160 160
 
161
-        self::$fileType[ 'proprietary' ]            = $pipeline[ 'proprietary' ];
162
-        self::$fileType[ 'proprietary_name' ]       = $pipeline[ 'proprietary_name' ];
163
-        self::$fileType[ 'proprietary_short_name' ] = $pipeline[ 'proprietary_short_name' ];
164
-        self::$fileType[ 'converter_version' ]      = $pipeline[ 'converter_version' ];
161
+        self::$fileType['proprietary']            = $pipeline['proprietary'];
162
+        self::$fileType['proprietary_name']       = $pipeline['proprietary_name'];
163
+        self::$fileType['proprietary_short_name'] = $pipeline['proprietary_short_name'];
164
+        self::$fileType['converter_version']      = $pipeline['converter_version'];
165 165
 
166 166
         return self::$fileType;
167 167
     }
@@ -173,21 +173,21 @@  discard block
 block discarded – undo
173 173
      *
174 174
      * @return bool|int
175 175
      */
176
-    public static function fileMustBeConverted( string $fullPath, ?bool $enforceOnXliff = false, ?string $filterAddress = null ) {
176
+    public static function fileMustBeConverted(string $fullPath, ?bool $enforceOnXliff = false, ?string $filterAddress = null) {
177 177
         $convert = true;
178 178
 
179
-        $fileType       = self::getInfo( $fullPath );
180
-        $memoryFileType = Files::getMemoryFileType( $fullPath );
179
+        $fileType       = self::getInfo($fullPath);
180
+        $memoryFileType = Files::getMemoryFileType($fullPath);
181 181
 
182
-        if ( Files::isXliff( $fullPath ) || $memoryFileType ) {
183
-            if ( !empty( $filterAddress ) ) {
182
+        if (Files::isXliff($fullPath) || $memoryFileType) {
183
+            if (!empty($filterAddress)) {
184 184
 
185 185
                 //conversion enforce
186
-                if ( !$enforceOnXliff ) {
186
+                if (!$enforceOnXliff) {
187 187
 
188 188
                     //if file is not proprietary AND Enforce is disabled
189 189
                     //we take it as is
190
-                    if ( !$fileType[ 'proprietary' ] || $memoryFileType ) {
190
+                    if (!$fileType['proprietary'] || $memoryFileType) {
191 191
                         $convert = false;
192 192
                         //ok don't convert a standard sdlxliff
193 193
                     }
@@ -195,16 +195,16 @@  discard block
 block discarded – undo
195 195
                     //if conversion enforce is active
196 196
                     //we force all xliff files but not files produced by SDL Studio because we can handle them
197 197
                     if (
198
-                            $fileType[ 'proprietary_short_name' ] == 'matecat_converter'
199
-                            || $fileType[ 'proprietary_short_name' ] == 'trados'
200
-                            || $fileType[ 'proprietary_short_name' ] == 'xliff_v2'
198
+                            $fileType['proprietary_short_name'] == 'matecat_converter'
199
+                            || $fileType['proprietary_short_name'] == 'trados'
200
+                            || $fileType['proprietary_short_name'] == 'xliff_v2'
201 201
                             || $memoryFileType
202 202
                     ) {
203 203
                         $convert = false;
204 204
                         //ok don't convert a standard sdlxliff
205 205
                     }
206 206
                 }
207
-            } elseif ( $fileType[ 'proprietary' ] ) {
207
+            } elseif ($fileType['proprietary']) {
208 208
 
209 209
                 /**
210 210
                  * Application misconfiguration.
Please login to merge, or discard this patch.