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

XliffFileDumper::hasMetadataArrayInfo()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 4
cp 0
rs 9.2
c 0
b 0
f 0
cc 4
eloc 2
nc 5
nop 2
crap 20
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
            $translation->setAttribute('id', md5($source));
90
91
            // changed for phrase app
92
            if (substr($source, 0, strlen($domain) + 2) === ($domain . '::')) {
93
                $translation->setAttribute('resname', $source);
94
            } else {
95
                $translation->setAttribute('resname', "$domain::$source");
96
            }
97
98
            $s = $translation->appendChild($dom->createElement('source'));
99
            $s->appendChild($dom->createTextNode($source));
100
101
            // Does the target contain characters requiring a CDATA section?
102
            $text = 1 === preg_match('/[&<>]/', $target) ? $dom->createCDATASection($target) : $dom->createTextNode($target);
103
104
            $targetElement = $dom->createElement('target');
105
            $metadata = $messages->getMetadata($source, $domain);
106
            if ($this->hasMetadataArrayInfo('target-attributes', $metadata)) {
107
                foreach ($metadata['target-attributes'] as $name => $value) {
108
                    $targetElement->setAttribute($name, $value);
109
                }
110
            }
111
            $t = $translation->appendChild($targetElement);
112
            $t->appendChild($text);
113
114
            if ($this->hasMetadataArrayInfo('notes', $metadata)) {
115
                foreach ($metadata['notes'] as $note) {
116
                    if (!isset($note['content'])) {
117
                        continue;
118
                    }
119
120
                    $n = $translation->appendChild($dom->createElement('note'));
121
                    $n->appendChild($dom->createTextNode($note['content']));
122
123
                    if (isset($note['priority'])) {
124
                        $n->setAttribute('priority', $note['priority']);
125
                    }
126
127
                    if (isset($note['from'])) {
128
                        $n->setAttribute('from', $note['from']);
129
                    }
130
                }
131
            }
132
133
            $xliffBody->appendChild($translation);
134
        }
135
136
        return $dom->saveXML();
137
    }
138
139
    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...
140
    {
141
        $dom = new \DOMDocument('1.0', 'utf-8');
142
        $dom->formatOutput = true;
143
144
        $xliff = $dom->appendChild($dom->createElement('xliff'));
145
        $xliff->setAttribute('xmlns', 'urn:oasis:names:tc:xliff:document:2.0');
146
        $xliff->setAttribute('version', '2.0');
147
        $xliff->setAttribute('srcLang', str_replace('_', '-', $defaultLocale));
148
        $xliff->setAttribute('trgLang', str_replace('_', '-', $messages->getLocale()));
149
150
        $xliffFile = $xliff->appendChild($dom->createElement('file'));
151
        $xliffFile->setAttribute('id', $domain.'.'.$messages->getLocale());
152
153
        foreach ($messages->all($domain) as $source => $target) {
154
            $translation = $dom->createElement('unit');
155
            $translation->setAttribute('id', md5($source));
156
157
            $segment = $translation->appendChild($dom->createElement('segment'));
158
159
            $s = $segment->appendChild($dom->createElement('source'));
160
            $s->appendChild($dom->createTextNode($source));
161
162
            // Does the target contain characters requiring a CDATA section?
163
            $text = 1 === preg_match('/[&<>]/', $target) ? $dom->createCDATASection($target) : $dom->createTextNode($target);
164
165
            $targetElement = $dom->createElement('target');
166
            $metadata = $messages->getMetadata($source, $domain);
167
            if ($this->hasMetadataArrayInfo('target-attributes', $metadata)) {
168
                foreach ($metadata['target-attributes'] as $name => $value) {
169
                    $targetElement->setAttribute($name, $value);
170
                }
171
            }
172
            $t = $segment->appendChild($targetElement);
173
            $t->appendChild($text);
174
175
            $xliffFile->appendChild($translation);
176
        }
177
178
        return $dom->saveXML();
179
    }
180
181
    /**
182
     * @param string     $key
183
     * @param array|null $metadata
184
     *
185
     * @return bool
186
     */
187
    private function hasMetadataArrayInfo($key, $metadata = null)
188
    {
189
        return null !== $metadata && array_key_exists($key, $metadata) && ($metadata[$key] instanceof \Traversable || is_array($metadata[$key]));
190
    }
191
}
192