File: DataBuilder.php

package info (click to toggle)
php-giggsey-locale 2.8.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 3,160 kB
  • sloc: php: 53,967; xml: 61; makefile: 37
file content (238 lines) | stat: -rw-r--r-- 7,074 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
<?php

declare(strict_types=1);

namespace Giggsey\Locale\Build;

use InvalidArgumentException;
use RuntimeException;
use Symfony\Component\Console\Helper\ProgressBar;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\VarExporter\VarExporter;

class DataBuilder
{
    protected const GENERATION_HEADER = <<<EOT
        /**
         * Locale data file
         * This file has been @generated from Locale data
         * Do not modify or use this file directly!
         * @internal
         */

        EOT;

    /**
     * Ignore these locales
     * @var array
     */
    private $ignoredLocales = [
        'en-US-POSIX',
        'en-001',
        'en-150',
        'es-419',
    ];

    /**
     * Ignore these regions
     * @var array
     */
    private $ignoredRegions = [
        'ZZ', // Unknown region
        'QO', // Outlying Ocean Region
        'EU', // European Union
        'AN', // Antilles (no longer exists)
        'BV', // Bouvet Island (Uninhabited)
        'HM', // Heard & McDonald Islands (Uninhabited)
        'CP', // Clipperton Island (uninhabited)
        'EZ', // Eurozone
        'UN', // United Nations
        'XA', // Pseudo-Accents
        'XB', // Pseudo-Bidi
    ];

    /**
     * @param string $version Version of the CLDR data
     * @param string $inputDir Input directory to load CLDR data from
     * @param string $outputDir Output directory to write data
     */
    public function generate(string $version, string $inputDir, string $outputDir, OutputInterface $output): void
    {
        // Check Directories exist
        $this->checkDirectories($inputDir, $outputDir);

        // Load Locales from source directory
        $localeList = $this->loadLocales($inputDir);

        // Load list of Territories
        $countries = $this->loadTerritories($inputDir, $localeList);

        $progress = new ProgressBar($output, count($countries));

        // Write each file
        $writtenCountries = [];

        foreach ($countries as $locale => $countryData) {
            /*
             * Compress file (if possible)
             *
             *  - Split up the locale into the sections
             *  - Loop through each row in $countryData
             *  - If the record exists, and is the same as a higher level, remove from this level
             */

            $fallbackParts = explode('-', str_replace('_', '-', $locale));
            if (count($fallbackParts) > 1) {
                array_pop($fallbackParts);

                $newLocale = implode('-', $fallbackParts);

                if (array_key_exists($newLocale, $countries)) {
                    foreach ($countryData as $key => $value) {
                        if (array_key_exists($key, $countries[$newLocale]) && $countries[$newLocale][$key] === $value) {
                            unset($countryData[$key]);
                        }
                    }
                }
            }

            if (count($countryData) === 0) {
                // Skip empty countries
                continue;
            }

            $this->writeTerritoryFile($outputDir, $locale, $countryData);

            $writtenCountries[strtolower($locale)] = '';

            $progress->advance();
        }

        ksort($writtenCountries);

        $this->writeMappingFile($outputDir, $writtenCountries);

        $this->writeVersionFile($outputDir, $version);

        $progress->finish();
    }

    /**
     * Check and create directories
     *
     * @codeCoverageIgnore
     */
    private function checkDirectories(string $inputDir, string $outputDir): void
    {
        if (!is_dir($inputDir)) {
            throw new InvalidArgumentException(sprintf('Unable to find input directory: %s', $inputDir));
        }

        // Try to create output directory
        if (!is_dir($outputDir) && !mkdir($outputDir) && !is_dir($outputDir)) {
            throw new RuntimeException(sprintf('Unable to create output directory: %s', $outputDir));
        }
    }

    /**
     * Load Locale list from the source data
     *
     * @param string $inputDir Input Directory
     * @return array List of Locales
     */
    private function loadLocales(string $inputDir): array
    {
        $localeList = [];

        foreach (scandir($inputDir) as $item) {
            if (strpos($item, '.') !== 0 && is_dir($inputDir . $item)) {
                if (in_array($item, $this->ignoredLocales, true)) {
                    // Skip over any ignored locales
                    continue;
                }

                $localeList[] = $item;
            }
        }

        return $localeList;
    }

    protected function loadTerritories(string $inputDir, array $localeList): array
    {
        $countries = [];

        foreach ($localeList as $locale) {
            $path = $inputDir . $locale . '/territories.json';

            if (!file_exists($path)) {
                // Skip this locale
                continue;
            }

            $data = json_decode(file_get_contents($path), true);
            $territoryList = $data['main'][$locale]['localeDisplayNames']['territories'];

            $countries[$locale] = [];

            foreach ($territoryList as $territory => $name) {
                if (is_numeric($territory)) {
                    // Ignore numeric values (continents, and other special regions)
                    continue;
                }

                if (stripos($territory, '-alt-') !== false) {
                    // Ignore alternative names
                    continue;
                }

                if (in_array($territory, $this->ignoredRegions, true)) {
                    // Ignore certain regions
                    continue;
                }

                if ($territory === $name) {
                    // Ignore the data if it's the same as the territory name
                    continue;
                }

                $countries[$locale][$territory] = $name;
            }
        }

        return $countries;
    }

    private function writeTerritoryFile(string $outputDir, string $locale, array $data): void
    {
        $phpSource = '<?php'
            . PHP_EOL
            . static::GENERATION_HEADER
            . 'return ' . VarExporter::export($data) . ';'
            . PHP_EOL;

        file_put_contents($outputDir . strtolower($locale) . '.php', $phpSource);
    }

    private function writeMappingFile(string $outputDir, array $countryList): void
    {
        $phpSource = '<?php'
            . PHP_EOL
            . static::GENERATION_HEADER
            . 'return ' . VarExporter::export($countryList) . ';'
            . PHP_EOL;

        file_put_contents($outputDir . '_list.php', $phpSource);
    }

    private function writeVersionFile(string $outputDir, string $version): void
    {
        $phpSource = '<?php'
            . PHP_EOL
            . static::GENERATION_HEADER
            . 'return ' . VarExporter::export($version) . ';'
            . PHP_EOL;

        file_put_contents($outputDir . '_version.php', $phpSource);
    }
}