Completed
Pull Request — master (#3)
by Sascha-Oliver
02:57
created

XliffFileDumper::getExtension()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 4
cp 0
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 2
1
<?php
2
3
namespace Translation\PlatformAdapter\PhraseApp\Bridge\Symfony;
4
5
use Symfony\Component\Translation\Dumper\FileDumper;
6
use Symfony\Component\Translation\MessageCatalogue;
7
8
/**
9
 * Custom XliffFileDumper for use with phrase app
10
 *
11
 * This class is required, because we have unique key names, so we have to make keyname = "$domain::$source"
12
 */
13
class XliffFileDumper extends FileDumper
14
{
15
    /**
16
     * {@inheritdoc}
17
     */
18
    public function formatCatalogue(MessageCatalogue $messages, $domain, array $options = array())
19
    {
20
        $xliffVersion = '1.2';
21
        if (array_key_exists('xliff_version', $options)) {
22
            $xliffVersion = $options['xliff_version'];
23
        }
24
25
        if (array_key_exists('default_locale', $options)) {
26
            $defaultLocale = $options['default_locale'];
27
        } else {
28
            $defaultLocale = \Locale::getDefault();
29
        }
30
31
        if ('1.2' === $xliffVersion) {
32
            return $this->dumpXliff1($defaultLocale, $messages, $domain, $options);
33
        }
34
        if ('2.0' === $xliffVersion) {
35
            return $this->dumpXliff2($defaultLocale, $messages, $domain, $options);
36
        }
37
38
        throw new \InvalidArgumentException(sprintf('No support implemented for dumping XLIFF version "%s".', $xliffVersion));
39
    }
40
41
    /**
42
     * {@inheritdoc}
43
     */
44
    protected function format(MessageCatalogue $messages, $domain)
45
    {
46
        @trigger_error('The '.__METHOD__.' method is deprecated since version 2.8 and will be removed in 3.0. Use the formatCatalogue() method instead.', E_USER_DEPRECATED);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

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...
47
48
        return $this->formatCatalogue($messages, $domain);
49
    }
50
51
    /**
52
     * {@inheritdoc}
53
     */
54
    protected function getExtension()
55
    {
56
        return 'xlf';
57
    }
58
59
    private function dumpXliff1($defaultLocale, MessageCatalogue $messages, $domain, array $options = array())
60
    {
61
        $toolInfo = array('tool-id' => 'symfony', 'tool-name' => 'Symfony');
62
        if (array_key_exists('tool_info', $options)) {
63
            $toolInfo = array_merge($toolInfo, $options['tool_info']);
64
        }
65
66
        $dom = new \DOMDocument('1.0', 'utf-8');
67
        $dom->formatOutput = true;
68
69
        $xliff = $dom->appendChild($dom->createElement('xliff'));
70
        $xliff->setAttribute('version', '1.2');
71
        $xliff->setAttribute('xmlns', 'urn:oasis:names:tc:xliff:document:1.2');
72
73
        $xliffFile = $xliff->appendChild($dom->createElement('file'));
74
        $xliffFile->setAttribute('source-language', str_replace('_', '-', $defaultLocale));
75
        $xliffFile->setAttribute('target-language', str_replace('_', '-', $messages->getLocale()));
76
        $xliffFile->setAttribute('datatype', 'plaintext');
77
        $xliffFile->setAttribute('original', 'file.ext');
78
79
        $xliffHead = $xliffFile->appendChild($dom->createElement('header'));
80
        $xliffTool = $xliffHead->appendChild($dom->createElement('tool'));
81
        foreach ($toolInfo as $id => $value) {
82
            $xliffTool->setAttribute($id, $value);
83
        }
84
85
        $xliffBody = $xliffFile->appendChild($dom->createElement('body'));
86
        foreach ($messages->all($domain) as $source => $target) {
87
            $translation = $dom->createElement('trans-unit');
88
89
            // changed for phrase app
90
            $translation->setAttribute('id', md5($source));
91
            $translation->setAttribute('resname', "$domain::$source");
92
93
            $s = $translation->appendChild($dom->createElement('source'));
94
            $s->appendChild($dom->createTextNode($source));
95
96
            // Does the target contain characters requiring a CDATA section?
97
            $text = 1 === preg_match('/[&<>]/', $target) ? $dom->createCDATASection($target) : $dom->createTextNode($target);
98
99
            $targetElement = $dom->createElement('target');
100
            $metadata = $messages->getMetadata($source, $domain);
101
            if ($this->hasMetadataArrayInfo('target-attributes', $metadata)) {
102
                foreach ($metadata['target-attributes'] as $name => $value) {
103
                    $targetElement->setAttribute($name, $value);
104
                }
105
            }
106
            $t = $translation->appendChild($targetElement);
107
            $t->appendChild($text);
108
109
            if ($this->hasMetadataArrayInfo('notes', $metadata)) {
110
                foreach ($metadata['notes'] as $note) {
111
                    if (!isset($note['content'])) {
112
                        continue;
113
                    }
114
115
                    $n = $translation->appendChild($dom->createElement('note'));
116
                    $n->appendChild($dom->createTextNode($note['content']));
117
118
                    if (isset($note['priority'])) {
119
                        $n->setAttribute('priority', $note['priority']);
120
                    }
121
122
                    if (isset($note['from'])) {
123
                        $n->setAttribute('from', $note['from']);
124
                    }
125
                }
126
            }
127
128
            $xliffBody->appendChild($translation);
129
        }
130
131
        return $dom->saveXML();
132
    }
133
134
    private function dumpXliff2($defaultLocale, MessageCatalogue $messages, $domain, array $options = array())
0 ignored issues
show
Unused Code introduced by
The parameter $options is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
135
    {
136
        $dom = new \DOMDocument('1.0', 'utf-8');
137
        $dom->formatOutput = true;
138
139
        $xliff = $dom->appendChild($dom->createElement('xliff'));
140
        $xliff->setAttribute('xmlns', 'urn:oasis:names:tc:xliff:document:2.0');
141
        $xliff->setAttribute('version', '2.0');
142
        $xliff->setAttribute('srcLang', str_replace('_', '-', $defaultLocale));
143
        $xliff->setAttribute('trgLang', str_replace('_', '-', $messages->getLocale()));
144
145
        $xliffFile = $xliff->appendChild($dom->createElement('file'));
146
        $xliffFile->setAttribute('id', $domain.'.'.$messages->getLocale());
147
148
        foreach ($messages->all($domain) as $source => $target) {
149
            $translation = $dom->createElement('unit');
150
            $translation->setAttribute('id', md5($source));
151
152
            $segment = $translation->appendChild($dom->createElement('segment'));
153
154
            $s = $segment->appendChild($dom->createElement('source'));
155
            $s->appendChild($dom->createTextNode($source));
156
157
            // Does the target contain characters requiring a CDATA section?
158
            $text = 1 === preg_match('/[&<>]/', $target) ? $dom->createCDATASection($target) : $dom->createTextNode($target);
159
160
            $targetElement = $dom->createElement('target');
161
            $metadata = $messages->getMetadata($source, $domain);
162
            if ($this->hasMetadataArrayInfo('target-attributes', $metadata)) {
163
                foreach ($metadata['target-attributes'] as $name => $value) {
164
                    $targetElement->setAttribute($name, $value);
165
                }
166
            }
167
            $t = $segment->appendChild($targetElement);
168
            $t->appendChild($text);
169
170
            $xliffFile->appendChild($translation);
171
        }
172
173
        return $dom->saveXML();
174
    }
175
176
    /**
177
     * @param string     $key
178
     * @param array|null $metadata
179
     *
180
     * @return bool
181
     */
182
    private function hasMetadataArrayInfo($key, $metadata = null)
183
    {
184
        return null !== $metadata && array_key_exists($key, $metadata) && ($metadata[$key] instanceof \Traversable || is_array($metadata[$key]));
185
    }
186
}
187