summaryrefslogtreecommitdiff
path: root/php-generator/generate.php
blob: 3f7e574668ed966692edf0e5a876f97b38d10939 (plain)
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
<?php

declare(strict_types=1);

use Symfony\Component\VarExporter\VarExporter;

require __DIR__.'/vendor/autoload.php';

// Requires three parameters
// 1. The script name
// 2. The source path for metadata JSON files
// 3. The destination path to store the artifact
if ($argc !== 3) {
    printf('Usage: php %s <src> <dst>'.PHP_EOL, $argv[0]);
    exit(1);
}

[$src, $dst] = [$argv[1], $argv[2]];
$srcPath = new \SplFileInfo($src);
$dstPath = new \SplFileInfo($dst);

// Validate the source path
if ($srcPath->getRealPath() === false) {
    printf('The source path "%s" does not exist.'.PHP_EOL, $srcPath->getPathname());
    exit(1);
}

if ($srcPath->isDir() === false) {
    printf('The source path "%s" is not a directory.'.PHP_EOL, $srcPath->getPathname());
    exit(1);
}

// Validate the destination path
if ($dstPath->getRealPath() === false) {
    printf('The destination path "%s" does not exist.'.PHP_EOL, $dstPath->getPathname());
    exit(1);
}

if ($dstPath->isDir() === false) {
    printf('The destination path "%s" is not a directory.'.PHP_EOL, $dstPath->getPathname());
    exit(1);
}

$iterator = new \RecursiveIteratorIterator(new \RecursiveCallbackFilterIterator(
    new \RecursiveDirectoryIterator($srcPath->getRealPath(), \FilesystemIterator::SKIP_DOTS),
    static function (\SplFileInfo $file) use ($srcPath): bool {
        if ($file->isDir()) {
            $relativePath = substr($file->getRealPath(), strlen($srcPath->getRealPath()));

            return str_starts_with($relativePath, DIRECTORY_SEPARATOR.'en_us')
                || str_starts_with($relativePath, DIRECTORY_SEPARATOR.'zh_cn');
        }

        return $file->isFile() && $file->getExtension() === 'json';
    }
));

foreach ($iterator as $file) {
    $relativePath = substr($file->getRealPath(), strlen($srcPath->getRealPath()));

    printf('[-] Generate %s'.PHP_EOL, $relativePath);

    // Change the file extension from json to php
    $out = $dstPath->getRealPath().substr($relativePath, 0, -4).'php';
    $outdir = dirname($out);

    if (! file_exists($outdir)) {
        mkdir($outdir, 0o755, recursive: true);
    }

    $contents = file_get_contents($file->getRealPath());
    $decoded = json_decode($contents, associative: true, flags: JSON_THROW_ON_ERROR);
    $result = sprintf('<?php return %s;'.PHP_EOL, VarExporter::export($decoded));

    file_put_contents($out, $result, flags: LOCK_EX);
}

echo '[-] Generate successfully'.PHP_EOL;