Passed
Branch php-cs-fixer (b9836a)
by Fabio
15:02
created

MessageSource_XLIFF::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * MessageSource_XLIFF class file.
5
 *
6
 * This program is free software; you can redistribute it and/or modify
7
 * it under the terms of the BSD License.
8
 *
9
 * Copyright(c) 2004 by Qiang Xue. All rights reserved.
10
 *
11
 * To contact the author write to {@link mailto:[email protected] Qiang Xue}
12
 * The latest version of PRADO can be obtained from:
13
 * {@link http://prado.sourceforge.net/}
14
 *
15
 * @author Wei Zhuo <weizhuo[at]gmail[dot]com>
16
 * @package Prado\I18N\core
17
 */
18
19
namespace Prado\I18N\core;
20
21
use DOMDocument;
22
use DOMXPath;
23
use Prado\Exceptions\TException;
24
use Prado\Exceptions\TIOException;
25
26
/**
27
 * MessageSource_XLIFF class.
28
 *
29
 * Using XML XLIFF format as the message source for translation.
30
 * Details and example of XLIFF can be found in the following URLs.
31
 *
32
 * # http://www.opentag.com/xliff.htm
33
 * # http://www-106.ibm.com/developerworks/xml/library/x-localis2/
34
 *
35
 * See the MessageSource::factory() method to instantiate this class.
36
 *
37
 * @author Xiang Wei Zhuo <weizhuo[at]gmail[dot]com>
38
 * @package Prado\I18N\core
39
 */
40
class MessageSource_XLIFF extends MessageSource
41
{
42
	/**
43
	 * Message data filename extension.
44
	 * @var string
45
	 */
46
	protected $dataExt = '.xml';
47
48
	/**
49
	 * Separator between culture name and source.
50
	 * @var string
51
	 */
52
	protected $dataSeparator = '.';
53
54
	/**
55
	 * Constructor.
56
	 * @param string the directory where the messages are stored.
0 ignored issues
show
Bug introduced by
The type Prado\I18N\core\the was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
57
	 * @see MessageSource::factory();
58
	 */
59
	public function __construct($source)
60
	{
61
		$this->source = (string)$source;
62
	}
63
64
	/**
65
	 * Load the messages from a XLIFF file.
0 ignored issues
show
Bug introduced by
The type Prado\I18N\core\XLIFF was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
66
	 * @param string XLIFF file.
67
	 * @return array of messages.
68
	 */
69
	protected function &loadData($filename)
70
	{
71
		//load it.
72
		if(false === ($XML = simplexml_load_file($filename))) {
0 ignored issues
show
introduced by
The condition false === $XML = simplexml_load_file($filename) can never be true.
Loading history...
73
			return false;
74
		}
75
76
		$translationUnit = $XML->xpath('//trans-unit');
77
78
		$translations = [];
79
80
		foreach($translationUnit as $unit)
81
		{
82
			$source = (string)$unit->source;
83
			$translations[$source][] = (string)$unit->target;
84
			$translations[$source][] = (string)$unit['id'];
85
			$translations[$source][] = (string)$unit->note;
86
		}
87
88
		return $translations;
89
	}
90
91
	/**
92
	 * Get the last modified unix-time for this particular catalogue+variant.
93
	 * Just use the file modified time.
94
	 * @param string catalogue+variant
95
	 * @return int last modified in unix-time format.
96
	 */
0 ignored issues
show
Documentation Bug introduced by
The doc comment catalogue+variant at position 0 could not be parsed: Unknown type name 'catalogue+variant' at position 0 in catalogue+variant.
Loading history...
97
	protected function getLastModified($source)
98
	{
99
		return is_file($source) ? filemtime($source) : 0;
100
	}
101
102
	/**
103
	 * Get the XLIFF file for a specific message catalogue and cultural
104
	 * vairant.
105
	 * @param string message catalogue
106
	 * @return string full path to the XLIFF file.
107
	 */
108
	protected function getSource($variant)
109
	{
110
		return $this->source . '/' . $variant;
111
	}
112
113
	/**
114
	 * Determin if the XLIFF file source is valid.
115
	 * @param string XLIFF file
116
	 * @return boolean true if valid, false otherwise.
117
	 */
118
	protected function isValidSource($source)
119
	{
120
		return is_file($source);
121
	}
122
123
	/**
124
	 * Get all the variants of a particular catalogue.
0 ignored issues
show
Bug introduced by
The type Prado\I18N\core\catalogue was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
125
	 * @param string catalogue name
126
	 * @return array list of all variants for this catalogue.
127
	 */
128
	protected function getCatalogueList($catalogue)
129
	{
130
		$variants = explode('_', $this->culture);
131
		$source = $catalogue . $this->dataExt;
132
		$catalogues = [$source];
133
		$variant = null;
134
135
		for($i = 0, $k = count($variants); $i < $k; ++$i)
136
		{
137
			if(isset($variants[$i]{0}))
138
			{
139
				$variant .= ($variant)?'_' . $variants[$i]:$variants[$i];
140
				$catalogues[] = $catalogue . $this->dataSeparator . $variant . $this->dataExt;
141
			}
142
		}
143
144
		$byDir = $this->getCatalogueByDir($catalogue);
145
		$catalogues = array_merge($byDir, array_reverse($catalogues));
146
		$files = [];
147
148
		foreach($catalogues as $file)
149
		{
150
			$files[] = $file;
151
			$files[] = preg_replace('/\.xml$/', '.xlf', $file);
152
		}
153
154
		return $files;
155
	}
156
157
	/**
158
	 * Traverse through the directory structure to find the catalogues.
0 ignored issues
show
Bug introduced by
The type Prado\I18N\core\a was not found. Did you mean a? If so, make sure to prefix the type with \.
Loading history...
159
	 * This should only be called by getCatalogueList()
160
	 * @param string a particular catalogue.
161
	 * @return array a list of catalogues.
162
	 * @see getCatalogueList()
163
	 */
164
	private function getCatalogueByDir($catalogue)
165
	{
166
		$variants = explode('_', $this->culture);
167
		$catalogues = [];
168
		$variant = null;
169
170
		for($i = 0, $k = count($variants); $i < $k; ++$i)
171
		{
172
			if(isset($variants[$i]{0}))
173
			{
174
				$variant .= ($variant)?'_' . $variants[$i]:$variants[$i];
175
				$catalogues[] = $variant . '/' . $catalogue . $this->dataExt;
176
			}
177
		}
178
179
		return array_reverse($catalogues);
180
	}
181
182
	/**
183
	 * Returns a list of catalogue and its culture ID.
184
	 * E.g. array('messages','en_AU')
185
	 * @return array list of catalogues
186
	 * @see getCatalogues()
187
	 */
188
	public function catalogues()
189
	{
190
		return $this->getCatalogues();
191
	}
192
193
	/**
194
	 * Returns a list of catalogue and its culture ID. This takes care
195
	 * of directory structures.
196
	 * E.g. array('messages','en_AU')
197
	 * @return array list of catalogues
198
	 */
199
	protected function getCatalogues($dir = null, $variant = null)
200
	{
201
		$dir = $dir?$dir:$this->source;
202
		$files = scandir($dir);
203
		$catalogue = [];
204
205
		foreach($files as $file)
206
		{
207
			if(is_dir($dir . '/' . $file) && preg_match('/^[a-z]{2}(_[A-Z]{2,3})?$/', $file)) {
208
				$catalogue = array_merge(
209
					$catalogue,
210
					$this->getCatalogues($dir . '/' . $file, $file)
211
				);
212
			}
213
214
			$pos = strpos($file, $this->dataExt);
215
			if($pos > 0 && substr($file, -1 * strlen($this->dataExt)) == $this->dataExt)
216
			{
217
				$name = substr($file, 0, $pos);
218
				$dot = strrpos($name, $this->dataSeparator);
219
				$culture = $variant;
220
				$cat = $name;
221
222
				if(is_int($dot))
223
				{
224
					$culture = substr($name, $dot + 1, strlen($name));
225
					$cat = substr($name, 0, $dot);
226
				}
227
228
				$details[0] = $cat;
229
				$details[1] = $culture;
230
				$catalogue[] = $details;
231
			}
232
		}
233
		sort($catalogue);
234
		return $catalogue;
235
	}
236
237
	/**
238
	 * Get the variant for a catalogue depending on the current culture.
239
	 * @param string catalogue
240
	 * @return string the variant.
241
	 * @see save()
242
	 * @see update()
243
	 * @see delete()
244
	 */
245
	private function getVariants($catalogue = 'messages')
246
	{
247
		if($catalogue === null) {
248
			$catalogue = 'messages';
249
		}
250
251
		foreach($this->getCatalogueList($catalogue) as $variant)
252
		{
253
			$file = $this->getSource($variant);
254
			if(is_file($file)) {
255
				return [$variant, $file];
0 ignored issues
show
Bug Best Practice introduced by
The expression return array($variant, $file) returns the type array<integer,mixed|string> which is incompatible with the documented return type string.
Loading history...
256
			}
257
		}
258
		return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type string.
Loading history...
259
	}
260
261
	/**
262
	 * Save the list of untranslated blocks to the translation source.
263
	 * If the translation was not found, you should add those
264
	 * strings to the translation source via the <b>append()</b> method.
265
	 * @param string the catalogue to add to
266
	 * @return boolean true if saved successfuly, false otherwise.
267
	 */
268
	public function save($catalogue = 'messages')
269
	{
270
		$messages = $this->untranslated;
271
		if(count($messages) <= 0) {
272
			return false;
273
		}
274
275
		$variants = $this->getVariants($catalogue);
276
277
		if($variants) {
278
			list($variant, $filename) = $variants;
279
		} else {
280
			list($variant, $filename) = $this->createMessageTemplate($catalogue);
281
		}
282
283
		if(is_writable($filename) == false) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
284
			throw new TIOException("Unable to save to file {$filename}, file must be writable.");
285
		}
286
287
		//create a new dom, import the existing xml
288
		$dom = new DOMDocument();
289
		$dom->load($filename);
290
291
		//find the body element
292
		$xpath = new DomXPath($dom);
293
		$body = $xpath->query('//body')->item(0);
294
295
		$lastNodes = $xpath->query('//trans-unit[last()]');
296
		if(($last = $lastNodes->item(0)) !== null) {
297
			$count = (int)$last->getAttribute('id');
298
		} else {
299
			$count = 0;
300
		}
301
302
		//for each message add it to the XML file using DOM
303
		foreach($messages as $message)
304
		{
305
			$unit = $dom->createElement('trans-unit');
306
			$unit->setAttribute('id', ++$count);
307
308
			$source = $dom->createElement('source');
309
			$source->appendChild($dom->createCDATASection($message));
310
311
			$target = $dom->createElement('target');
312
			$target->appendChild($dom->createCDATASection(''));
313
314
			$unit->appendChild($dom->createTextNode("\n"));
315
			$unit->appendChild($source);
316
			$unit->appendChild($dom->createTextNode("\n"));
317
			$unit->appendChild($target);
318
			$unit->appendChild($dom->createTextNode("\n"));
319
320
			$body->appendChild($dom->createTextNode("\n"));
321
			$body->appendChild($unit);
322
			$body->appendChild($dom->createTextNode("\n"));
323
		}
324
325
326
		$fileNode = $xpath->query('//file')->item(0);
327
		$fileNode->setAttribute('date', @date('Y-m-d\TH:i:s\Z'));
328
329
		//save it and clear the cache for this variant
330
		$dom->save($filename);
331
		if(!empty($this->cache)) {
332
			$this->cache->clean($variant, $this->culture);
333
		}
334
335
		return true;
336
	}
337
338
	/**
339
	 * Update the translation.
340
	 * @param string the source string.
341
	 * @param string the new translation string.
342
	 * @param string comments
343
	 * @param string the catalogue to save to.
344
	 * @return boolean true if translation was updated, false otherwise.
345
	 */
346
	public function update($text, $target, $comments, $catalogue = 'messages')
347
	{
348
		$variants = $this->getVariants($catalogue);
349
350
		if($variants) {
351
			list($variant, $filename) = $variants;
352
		} else {
353
			return false;
354
		}
355
356
		if(is_writable($filename) == false) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
357
			throw new TIOException("Unable to update file {$filename}, file must be writable.");
358
		}
359
360
		//create a new dom, import the existing xml
361
		$dom = DOMDocument::load($filename);
0 ignored issues
show
Bug Best Practice introduced by
The method DOMDocument::load() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

361
		/** @scrutinizer ignore-call */ 
362
  $dom = DOMDocument::load($filename);
Loading history...
362
363
		//find the body element
364
		$xpath = new DomXPath($dom);
365
		$units = $xpath->query('//trans-unit');
366
367
		//for each of the existin units
368
		foreach($units as $unit)
369
		{
370
			$found = false;
371
			$targetted = false;
372
			$commented = false;
373
374
			//in each unit, need to find the source, target and comment nodes
375
			//it will assume that the source is before the target.
376
			foreach($unit->childNodes as $node)
377
			{
378
				//source node
379
				if($node->nodeName == 'source' && $node->firstChild->wholeText == $text) {
380
					$found = true;
381
				}
382
383
				//found source, get the target and notes
384
				if($found)
385
				{
386
					//set the new translated string
387
					if($node->nodeName == 'target')
388
					{
389
						$node->nodeValue = $target;
390
						$targetted = true;
391
					}
392
393
					//set the notes
394
					if(!empty($comments) && $node->nodeName == 'note')
395
					{
396
						$node->nodeValue = $comments;
397
						$commented = true;
398
					}
399
				}
400
			}
401
402
			//append a target
403
			if($found && !$targetted) {
404
				$unit->appendChild($dom->createElement('target', $target));
405
			}
406
407
			//append a note
408
			if($found && !$commented && !empty($comments)) {
409
				$unit->appendChild($dom->createElement('note', $comments));
410
			}
411
412
			//finished searching
413
			if($found) {
414
				break;
415
			}
416
		}
417
418
		$fileNode = $xpath->query('//file')->item(0);
419
		$fileNode->setAttribute('date', @date('Y-m-d\TH:i:s\Z'));
420
421
		if($dom->save($filename) > 0)
422
		{
423
			if(!empty($this->cache)) {
424
				$this->cache->clean($variant, $this->culture);
425
			}
426
427
			return true;
428
		}
429
430
		return false;
431
	}
432
433
	/**
434
	 * Delete a particular message from the specified catalogue.
435
	 * @param string the source message to delete.
436
	 * @param string the catalogue to delete from.
437
	 * @return boolean true if deleted, false otherwise.
438
	 */
439
	public function delete($message, $catalogue = 'messages')
440
	{
441
		$variants = $this->getVariants($catalogue);
442
		if($variants) {
443
			list($variant, $filename) = $variants;
444
		} else {
445
			return false;
446
		}
447
448
		if(is_writable($filename) == false) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
449
			throw new TIOException("Unable to modify file {$filename}, file must be writable.");
450
		}
451
452
		//create a new dom, import the existing xml
453
		$dom = DOMDocument::load($filename);
0 ignored issues
show
Bug Best Practice introduced by
The method DOMDocument::load() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

453
		/** @scrutinizer ignore-call */ 
454
  $dom = DOMDocument::load($filename);
Loading history...
454
455
		//find the body element
456
		$xpath = new DomXPath($dom);
457
		$units = $xpath->query('//trans-unit');
458
459
		//for each of the existin units
460
		foreach($units as $unit)
461
		{
462
			//in each unit, need to find the source, target and comment nodes
463
			//it will assume that the source is before the target.
464
			foreach($unit->childNodes as $node)
465
			{
466
				//source node
467
				if($node->nodeName == 'source' && $node->firstChild->wholeText == $message)
468
				{
469
					//we found it, remove and save the xml file.
470
					$unit->parentNode->removeChild($unit);
471
					$fileNode = $xpath->query('//file')->item(0);
472
					$fileNode->setAttribute('date', @date('Y-m-d\TH:i:s\Z'));
473
474
					if(false !== $dom->save($filename)) {
475
						if(!empty($this->cache)) {
476
							$this->cache->clean($variant, $this->culture);
477
						}
478
						return true;
479
					}
480
481
					return false;
482
				}
483
			}
484
		}
485
486
		return false;
487
	}
488
489
	protected function createMessageTemplate($catalogue)
490
	{
491
		if($catalogue === null) {
492
			$catalogue = 'messages';
493
		}
494
		
495
		$variants = $this->getCatalogueList($catalogue);
496
		$variant = array_shift($variants);
497
		$file = $this->getSource($variant);
498
		$dir = dirname($file);
499
500
		if(!is_dir($dir)) {
501
			@mkdir($dir);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for mkdir(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

501
			/** @scrutinizer ignore-unhandled */ @mkdir($dir);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
502
			@chmod($dir, PRADO_CHMOD);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for chmod(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

502
			/** @scrutinizer ignore-unhandled */ @chmod($dir, PRADO_CHMOD);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
503
		}
504
505
		if(!is_dir($dir)) {
506
			throw new TException("Unable to create directory $dir");
507
		}
508
		
509
		file_put_contents($file, $this->getTemplate($catalogue));
510
		chmod($file, PRADO_CHMOD);
511
512
		return [$variant, $file];
513
	}
514
515
	protected function getTemplate($catalogue)
516
	{
517
		$date = @date('c');
518
		$xml = <<<EOD
519
<?xml version="1.0" encoding="UTF-8"?>
520
<xliff version="1.0">
521
 <file source-language="EN" target-language="{$this->culture}" datatype="plaintext" original="$catalogue" date="$date" product-name="$catalogue">
522
  <body>
523
  </body>
524
 </file>
525
</xliff>
526
EOD;
527
		return $xml;
528
	}
529
}
530