Debian Codegraph @

lib/3rdParty/composer/symfony/translation/Util/XliffUtils.php

raw symbols SCIP
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <[email protected]>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Symfony\Component\Translation\Util;
13
14 use Symfony\Component\Translation\Exception\InvalidArgumentException;
15 use Symfony\Component\Translation\Exception\InvalidResourceException;
16
17 /**
18 * Provides some utility methods for XLIFF translation files, such as validating
19 * their contents according to the XSD schema.
20 *
21 * @author Fabien Potencier <[email protected]>
22 */
23 class XliffUtils
24 {
25 /**
26 * Gets xliff file version based on the root "version" attribute.
27 *
28 * Defaults to 1.2 for backwards compatibility.
29 *
30 * @throws InvalidArgumentException
31 */
32 public static function getVersionNumber(\DOMDocument $dom): string
33 {
34 foreach ($dom->getElementsByTagName('xliff') as $xliff) {
35 $version = $xliff->attributes->getNamedItem('version');
36 if ($version) {
37 return $version->nodeValue;
38 }
39
40 $namespace = $xliff->attributes->getNamedItem('xmlns');
41 if ($namespace) {
42 if (0 !== substr_compare('urn:oasis:names:tc:xliff:document:', $namespace->nodeValue, 0, 34)) {
43 throw new InvalidArgumentException(\sprintf('Not a valid XLIFF namespace "%s".', $namespace));
44 }
45
46 return substr($namespace, 34);
47 }
48 }
49
50 // Falls back to v1.2
51 return '1.2';
52 }
53
54 /**
55 * Validates and parses the given file into a DOMDocument.
56 *
57 * @throws InvalidResourceException
58 */
59 public static function validateSchema(\DOMDocument $dom): array
60 {
61 $xliffVersion = static::getVersionNumber($dom);
62 $internalErrors = libxml_use_internal_errors(true);
63 if ($shouldEnable = self::shouldEnableEntityLoader()) {
64 $disableEntities = libxml_disable_entity_loader(false);
65 }
66 try {
67 $isValid = @$dom->schemaValidateSource(self::getSchema($xliffVersion));
68 if (!$isValid) {
69 return self::getXmlErrors($internalErrors);
70 }
71 } finally {
72 if ($shouldEnable) {
73 libxml_disable_entity_loader($disableEntities);
74 }
75 }
76
77 $dom->normalizeDocument();
78
79 libxml_clear_errors();
80 libxml_use_internal_errors($internalErrors);
81
82 return [];
83 }
84
85 public static function getErrorsAsString(array $xmlErrors): string
86 {
87 $errorsAsString = '';
88
89 foreach ($xmlErrors as $error) {
90 $errorsAsString .= \sprintf("[%s %s] %s (in %s - line %d, column %d)\n",
91 \LIBXML_ERR_WARNING === $error['level'] ? 'WARNING' : 'ERROR',
92 $error['code'],
93 $error['message'],
94 $error['file'],
95 $error['line'],
96 $error['column']
97 );
98 }
99
100 return $errorsAsString;
101 }
102
103 private static function shouldEnableEntityLoader(): bool
104 {
105 static $dom, $schema;
106 if (null === $dom) {
107 $dom = new \DOMDocument();
108 $dom->loadXML('<?xml version="1.0"?><test/>');
109
110 $tmpfile = tempnam(sys_get_temp_dir(), 'symfony');
111 register_shutdown_function(static function () use ($tmpfile) {
112 @unlink($tmpfile);
113 });
114 $schema = '<?xml version="1.0" encoding="utf-8"?>
115 <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
116 <xsd:include schemaLocation="'.self::getFileUrl($tmpfile).'" />
117 </xsd:schema>';
118 file_put_contents($tmpfile, '<?xml version="1.0" encoding="utf-8"?>
119 <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
120 <xsd:element name="test" type="testType" />
121 <xsd:complexType name="testType"/>
122 </xsd:schema>');
123 }
124
125 return !@$dom->schemaValidateSource($schema);
126 }
127
128 private static function getFileUrl(string $path): string
129 {
130 if ('\\' === \DIRECTORY_SEPARATOR) {
131 $parts = explode('/', str_replace('\\', '/', $path));
132 $drive = array_shift($parts).'/';
133 } else {
134 $parts = explode('/', $path);
135 $drive = '';
136 }
137
138 return 'file:///'.$drive.implode('/', array_map('rawurlencode', $parts));
139 }
140
141 private static function getSchema(string $xliffVersion): string
142 {
143 if ('1.2' === $xliffVersion) {
144 $schemaSource = file_get_contents(__DIR__.'/../Resources/schemas/xliff-core-1.2-transitional.xsd');
145 $xmlUri = 'http://www.w3.org/2001/xml.xsd';
146 } elseif ('2.0' === $xliffVersion) {
147 $schemaSource = file_get_contents(__DIR__.'/../Resources/schemas/xliff-core-2.0.xsd');
148 $xmlUri = 'informativeCopiesOf3rdPartySchemas/w3c/xml.xsd';
149 } else {
150 throw new InvalidArgumentException(\sprintf('No support implemented for loading XLIFF version "%s".', $xliffVersion));
151 }
152
153 return self::fixXmlLocation($schemaSource, $xmlUri);
154 }
155
156 /**
157 * Internally changes the URI of a dependent xsd to be loaded locally.
158 */
159 private static function fixXmlLocation(string $schemaSource, string $xmlUri): string
160 {
161 $path = __DIR__.'/../Resources/schemas/xml.xsd';
162
163 if (0 === stripos($path, 'phar://')) {
164 if ($tmpfile = tempnam(sys_get_temp_dir(), 'symfony')) {
165 copy($path, $tmpfile);
166 $newPath = self::getFileUrl($tmpfile);
167 } else {
168 $parts = explode('/', '\\' === \DIRECTORY_SEPARATOR ? str_replace('\\', '/', $path) : $path);
169 array_shift($parts);
170 $drive = '\\' === \DIRECTORY_SEPARATOR ? array_shift($parts).'/' : '';
171 $newPath = 'phar:///'.$drive.implode('/', array_map('rawurlencode', $parts));
172 }
173 } else {
174 $newPath = self::getFileUrl($path);
175 }
176
177 return str_replace($xmlUri, $newPath, $schemaSource);
178 }
179
180 /**
181 * Returns the XML errors of the internal XML parser.
182 */
183 private static function getXmlErrors(bool $internalErrors): array
184 {
185 $errors = [];
186 foreach (libxml_get_errors() as $error) {
187 $errors[] = [
188 'level' => \LIBXML_ERR_WARNING == $error->level ? 'WARNING' : 'ERROR',
189 'code' => $error->code,
190 'message' => trim($error->message),
191 'file' => $error->file ?: 'n/a',
192 'line' => $error->line,
193 'column' => $error->column,
194 ];
195 }
196
197 libxml_clear_errors();
198 libxml_use_internal_errors($internalErrors);
199
200 return $errors;
201 }
202 }