Skip to content

Instantly share code, notes, and snippets.

@zhouyl
Created July 13, 2017 07:18
Show Gist options
  • Select an option

  • Save zhouyl/9296728569baca69b24340fbdb827cb3 to your computer and use it in GitHub Desktop.

Select an option

Save zhouyl/9296728569baca69b24340fbdb827cb3 to your computer and use it in GitHub Desktop.
Resolve the service code for the protobuf protocols
#!/usr/bin/env php
<?php
$src_dir = __DIR__ . '/php-src';
$protos_dir = __DIR__ . '/protos';
foreach (new DirectoryIterator($protos_dir) as $file) {
if ($file->isFile() && $file->getExtension() === 'proto') {
generate_service_code($file->getPathname());
}
}
function generate_service_code($file)
{
echo "\nGenerate service code : $file\n----------------------------------\n";
$content = file_get_contents($file);
// echo $content;
$package = get_package_name($content);
echo "Package: $package\n";
$services = get_service_list($content);
echo "Services: \n";
var_export($services);
}
function get_package_name($content)
{
preg_match('/\npackage\s+([\w\.\_]+);\n/', $content, $matches);
return isset($matches[1]) ? str_replace('.', '\\', $matches[1]) : '';
}
function get_service_list($content)
{
$count = preg_match_all('/\n[ \t]*(rpc[ \t]+(.+?)[\};])/s', $content, $matches);
if ($count == 0) {
return [];
}
$services = [];
foreach ($matches[1] as $line) {
$services[] = parse_rpc_line($line);
}
return $services;
}
function parse_rpc_line($text)
{
$patterns = [
'' => ['/rpc\s+/', '/\s*;$/', '/\s*\{(.+?)\}$/s', '/\s+returns\s+/s'],
'.' => ['/[\(\)]/', '/\.\./'],
];
foreach ($patterns as $replace => $pattern) {
$text = preg_replace($pattern, $replace, $text);
}
return array_combine(['method', 'request', 'response'], explode('.', rtrim($text, '.')));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment