1<?php
2/**
3* Generate the API endpoints
4*
5* @author Enrico Zimuel (enrico.zimuel@elastic.co)
6*/
7declare(strict_types = 1);
8
9use GitWrapper\GitWrapper;
10
11require_once dirname(__DIR__) . '/vendor/autoload.php';
12
13if (!isset($argv[1])) {
14    print_usage_msg();
15    exit(1);
16}
17$version = 'v' . $argv[1];
18
19$gitWrapper = new GitWrapper();
20$git = $gitWrapper->workingCopy(dirname(__DIR__) . '/util/elasticsearch');
21
22$git->run('fetch', ['--tags']);
23$tags = explode("\n", $git->run('tag'));
24if (!in_array($version, $tags)) {
25    printf("Error: the version %s specified doesnot exist\n", $version);
26    exit(1);
27}
28
29$git->run('checkout', [$version]);
30
31$result = $git->run(
32    'ls-files',
33    [ "rest-api-spec/src/main/resources/rest-api-spec/api/*.json" ]
34);
35$files = explode("\n", $result);
36$endpoints = [];
37foreach ($files as $file) {
38    if (empty($file)) {
39        continue;
40    }
41    $endpoints[] = basename($file, '.json');
42}
43foreach ($files as $file) {
44    if (empty($file)) {
45        continue;
46    }
47    $endpoint = basename($file, '.json');
48    if ($endpoint === '_common') {
49        continue;
50    }
51
52    printf("Endpoint: %s ...", $endpoint);
53    try {
54        $json = json_decode(
55            $git->run('show', [':' . trim($file)]),
56            true,
57            512,
58            JSON_THROW_ON_ERROR
59        );
60    } catch (JsonException $e) {
61        printf("Error: %s\n", $e->getMessage());
62        exit(1);
63    }
64
65    printf("%s\n", getFilePathByEndpoint($endpoint, $endpoints));
66    continue;
67
68    if (preg_match('/^[a-z]+$/', $endpoint)) {
69        $class = file_get_contents(__DIR__ . '/EndpointClassSkeleton');
70        $class = str_replace(':params', extractParameters($json[$endpoint]), $class);
71        $class = str_replace(':endpoint', ucfirst($endpoint), $class);
72        $class = str_replace(':method', $json[$endpoint]['methods'][0], $class);
73        file_put_contents(__DIR__ . '/Endpoints/'. ucfirst($endpoint) . '.php', $class);
74    } elseif (preg_match('/^[a-z]+\.')) {
75
76    }
77    printf(" done\n");
78}
79
80function print_usage_msg(): void
81{
82    printf("Usage: php %s <ES_VERSION>\n", basename(__FILE__));
83    printf("where <ES_VERSION> is the Elasticsearch version to check (e.g. 7.0.0)\n");
84}
85
86function extractParameters(array $json): string
87{
88    if (!isset($json['url']['params'])) {
89        return '';
90    }
91    $tab = str_repeat(' ', 12);
92    $result = '';
93    foreach (array_keys($json['url']['params']) as $param) {
94        $result .=  "'$param'," . "\n" . $tab;
95    }
96    return rtrim(trim($result), ',');
97}
98
99function getFilePathByEndpoint(string $endpoint, array $endpoints): string
100{
101    if (preg_match('/^[a-z]+$/', $endpoint)) {
102        return ucfirst($endpoint);
103    } elseif (preg_match('/^(([a-z]+)\_)+([a-z]+)$/', $endpoint, $matches)) {
104        $result = '';
105        for($i=1; $i<count($matches); $i++) {
106            $result .= ucfirst($matches[$i]);
107        }
108        return $result;
109    } elseif (preg_match('/^([a-z]+)\.([a-z]+)$/', $endpoint, $matches)) {
110        return ucfirst($matches[1]) . '/' . ucfirst($matches[2]);
111    } elseif (preg_match('/^([a-z]+)\.([a-z]+)\_([a-z]+)$/', $endpoint, $matches)) {
112        return areMoreEndpointStartAndEndBy($matches[1], $matches[3], $endpoints)
113            ? ucfirst($matches[1]) . '/' . ucfirst($matches[3]) . '/' . ucfirst($matches[2])
114            : ucfirst($matches[1]) . '/' . ucfirst($matches[2]) . ucfirst($matches[3]);
115    }
116    return '';
117}
118
119function areMoreEndpointStartAndEndBy(string $start, string $end, array $endpoints): bool
120{
121    $i = 0;
122    foreach ($endpoints as $ep) {
123        if (preg_match('/^' . $start . '\.[a-z]+\_' . $end . '$/', $ep)) {
124            $i++;
125        }
126        if ($i > 1) {
127            return true;
128        }
129    }
130    return false;
131}
132