Query/tools/update_header_comments.php

90 lines
1.9 KiB
PHP
Raw Normal View History

2016-09-07 13:17:17 -04:00
<?php
2016-10-12 22:12:25 -04:00
declare(strict_types=1);
2016-09-07 13:17:17 -04:00
$file_patterns = [
2018-01-19 13:43:19 -05:00
'src/*.php',
'tests/*.php',
'Robofile.php'
2016-09-07 13:17:17 -04:00
];
if ( ! function_exists('glob_recursive'))
{
2018-01-19 13:43:19 -05:00
// Does not support flag GLOB_BRACE
2016-09-07 13:17:17 -04:00
2018-01-19 13:43:19 -05:00
function glob_recursive($pattern, $flags = 0)
{
$files = glob($pattern, $flags);
2016-09-07 13:17:17 -04:00
2018-01-19 13:43:19 -05:00
foreach (glob(dirname($pattern) . '/*', GLOB_ONLYDIR | GLOB_NOSORT) as $dir)
{
$files = array_merge($files, glob_recursive($dir . '/' . basename($pattern), $flags));
}
2016-09-07 13:17:17 -04:00
2018-01-19 13:43:19 -05:00
return $files;
}
2016-09-07 13:17:17 -04:00
}
function get_text_to_replace($tokens)
{
2018-01-19 13:43:19 -05:00
$output = '';
// Tokens have the follow structure if arrays:
// [0] => token type constant
// [1] => raw sytax parsed to that token
// [2] => line number
foreach($tokens as $token)
{
// Since we only care about opening docblocks,
// bail out when we get to the namespace token
if (is_array($token) && $token[0] === T_NAMESPACE)
{
break;
}
if (is_array($token))
{
$token = $token[1];
}
$output .= $token;
}
return $output;
2016-09-07 13:17:17 -04:00
}
function get_tokens($source)
{
2018-01-19 13:43:19 -05:00
return token_get_all($source);
2016-09-07 13:17:17 -04:00
}
function replace_files(array $files, $template)
{
2018-01-19 13:43:19 -05:00
print_r($files);
foreach ($files as $file)
{
$source = file_get_contents($file);
if (stripos($source, 'namespace') === FALSE)
{
continue;
}
2016-09-07 13:17:17 -04:00
2018-01-19 13:43:19 -05:00
$tokens = get_tokens($source);
$text_to_replace = get_text_to_replace($tokens);
2016-09-07 13:17:17 -04:00
2018-01-19 13:43:19 -05:00
$header = file_get_contents(__DIR__ . $template);
$new_text = "<?php declare(strict_types=1);\n{$header}";
2016-10-12 22:12:25 -04:00
2018-01-19 13:43:19 -05:00
$new_source = str_replace($text_to_replace, $new_text, $source);
file_put_contents($file, $new_source);
}
2016-09-07 13:17:17 -04:00
}
foreach ($file_patterns as $glob)
{
2018-01-19 13:43:19 -05:00
$files = glob_recursive($glob);
replace_files($files, '/header_comment.txt');
2016-09-07 13:17:17 -04:00
}
2018-01-19 13:43:19 -05:00
echo "Successfully updated headers \n";