Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
101 / 101
100.00% covered (success)
100.00%
9 / 9
CRAP
100.00% covered (success)
100.00%
1 / 1
Sync
100.00% covered (success)
100.00%
101 / 101
100.00% covered (success)
100.00%
9 / 9
32
100.00% covered (success)
100.00%
1 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 run
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
2
 reconcile
100.00% covered (success)
100.00%
36 / 36
100.00% covered (success)
100.00%
1 / 1
5
 reconcileSection
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
4
 parkSection
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
6
 parkContexts
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
3
 contextSize
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 write
100.00% covered (success)
100.00%
21 / 21
100.00% covered (success)
100.00%
1 / 1
8
 filesystemError
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
1<?php
2
3declare(strict_types=1);
4
5namespace Celema\Verba\Tool;
6
7use RuntimeException;
8
9/**
10 * Reconciles a domain's catalog files against the current source: fresh ids are
11 * added as untranslated, existing translations are kept, a reappearing id is
12 * restored from its ordinary or contextual obsolete section, and a vanished id
13 * is parked there unless pruning. Rewrites are deterministic.
14 *
15 * @api
16 */
17final class Sync
18{
19    public function __construct(
20        private readonly Domain $domain,
21        private readonly bool $prune = false,
22    ) {}
23
24    public function run(): SyncReport
25    {
26        $extraction = new Extractor($this->domain)->extract();
27        $fresh = $extraction['messages'];
28        $freshContexts = $extraction['contexts'];
29
30        $locales = [];
31
32        foreach ($this->domain->locales as $locale) {
33            $locales[$locale] = $this->reconcile($locale, $fresh, $freshContexts);
34        }
35
36        return new SyncReport($this->domain->name, $locales, $extraction['warnings']);
37    }
38
39    /**
40     * @param array<string, Message> $fresh
41     * @param array<string, array<string, Message>> $freshContexts
42     * @return array{added: int, obsolete: int, total: int, changed: bool}
43     */
44    private function reconcile(string $locale, array $fresh, array $freshContexts): array
45    {
46        $file = $this->domain->file($locale);
47        $catalog = CatalogFile::load($file);
48        $section = $this->reconcileSection($fresh, $catalog->messages, $catalog->obsolete);
49        $messages = $section['messages'];
50        $added = $section['added'];
51        $contexts = [];
52
53        foreach ($freshContexts as $context => $contextFresh) {
54            $section = $this->reconcileSection(
55                $contextFresh,
56                $catalog->contexts[$context] ?? [],
57                $catalog->obsoleteContexts[$context] ?? [],
58            );
59            $contexts[$context] = $section['messages'];
60            $added += $section['added'];
61        }
62
63        if ($this->prune) {
64            $obsolete = [];
65            $obsoleteContexts = [];
66        } else {
67            $obsolete = self::parkSection($catalog->messages, $catalog->obsolete, $fresh);
68            $obsoleteContexts = $this->parkContexts($catalog, $freshContexts);
69        }
70
71        $next = new CatalogFile(
72            $messages,
73            $obsolete,
74            $catalog->plural,
75            $contexts,
76            $obsoleteContexts,
77        );
78        $rendered = $next->render();
79        $changed = !is_file($file) || file_get_contents($file) !== $rendered;
80
81        if ($changed) {
82            $this->write($file, $rendered);
83        }
84
85        return [
86            'added' => $added,
87            'obsolete' => count($obsolete) + self::contextSize($obsoleteContexts),
88            'total' => count($messages) + self::contextSize($contexts),
89            'changed' => $changed,
90        ];
91    }
92
93    /**
94     * @param array<string, Message> $fresh
95     * @param array<string, string|list<string>|null> $messages
96     * @param array<string, string|list<string>|null> $obsolete
97     * @return array{messages: array<string, string|list<string>|null>, added: int}
98     */
99    private function reconcileSection(array $fresh, array $messages, array $obsolete): array
100    {
101        $next = [];
102        $added = 0;
103
104        foreach (array_keys($fresh) as $id) {
105            if (array_key_exists($id, $messages)) {
106                $next[$id] = $messages[$id];
107            } elseif (array_key_exists($id, $obsolete)) {
108                $next[$id] = $obsolete[$id];
109            } else {
110                $next[$id] = null;
111                $added++;
112            }
113        }
114
115        return ['messages' => $next, 'added' => $added];
116    }
117
118    /**
119     * @param array<string, string|list<string>|null> $messages
120     * @param array<string, string|list<string>|null> $parked
121     * @param array<string, Message> $fresh
122     * @return array<string, string|list<string>|null>
123     */
124    private static function parkSection(array $messages, array $parked, array $fresh): array
125    {
126        $obsolete = [];
127
128        foreach ($messages as $id => $value) {
129            if (array_key_exists($id, $fresh)) {
130                continue;
131            }
132
133            $obsolete[$id] = $value;
134        }
135
136        foreach ($parked as $id => $value) {
137            if (array_key_exists($id, $fresh) || array_key_exists($id, $obsolete)) {
138                continue;
139            }
140
141            $obsolete[$id] = $value;
142        }
143
144        return $obsolete;
145    }
146
147    /**
148     * @param array<string, array<string, Message>> $fresh
149     * @return array<string, array<string, string|list<string>|null>>
150     */
151    private function parkContexts(CatalogFile $catalog, array $fresh): array
152    {
153        $contexts = [];
154        $names = array_unique([
155            ...array_keys($catalog->contexts),
156            ...array_keys($catalog->obsoleteContexts),
157        ]);
158
159        foreach ($names as $context) {
160            $messages = self::parkSection(
161                $catalog->contexts[$context] ?? [],
162                $catalog->obsoleteContexts[$context] ?? [],
163                $fresh[$context] ?? [],
164            );
165
166            if ($messages !== []) {
167                $contexts[$context] = $messages;
168            }
169        }
170
171        return $contexts;
172    }
173
174    /** @param array<string, array<string, string|list<string>|null>> $contexts */
175    private static function contextSize(array $contexts): int
176    {
177        return array_sum(array_map(count(...), $contexts));
178    }
179
180    private function write(string $file, string $contents): void
181    {
182        $dir = dirname($file);
183        $temp = null;
184        $error = null;
185
186        // Filesystem functions warn before returning failure; this method checks every result below.
187        set_error_handler(static function (int $_severity, string $message) use (&$error): bool {
188            $error = $message;
189
190            return true;
191        });
192
193        try {
194            if (!is_dir($dir)) {
195                $error = null;
196
197                if (!mkdir($dir, 0o755, true) && !is_dir($dir)) {
198                    throw self::filesystemError("Cannot create catalog directory '{$dir}'", $error);
199                }
200            }
201
202            $temp = $file . '.' . bin2hex(random_bytes(6)) . '.tmp';
203            $error = null;
204
205            if (file_put_contents($temp, $contents) !== strlen($contents)) {
206                throw self::filesystemError("Cannot write temporary catalog for '{$file}'", $error);
207            }
208
209            $error = null;
210
211            if (!rename($temp, $file)) {
212                throw self::filesystemError("Cannot replace catalog '{$file}'", $error);
213            }
214        } finally {
215            if ($temp !== null && is_file($temp)) {
216                unlink($temp);
217            }
218
219            restore_error_handler();
220        }
221    }
222
223    private static function filesystemError(string $message, ?string $cause): RuntimeException
224    {
225        return new RuntimeException($cause === null ? $message : $message . ': ' . $cause);
226    }
227}