Completed
Push — develop ( 3eb4d8...6740aa )
by Timothy
02:29
created

update_header_comments.php ➔ get_text_to_replace()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 25
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 9
nc 5
nop 1
dl 0
loc 25
rs 8.439
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
$file_patterns = [
5
	'src/*.php',
6
	'tests/**/*.php',
7
];
8
9 View Code Duplication
if ( ! function_exists('glob_recursive'))
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
10
{
11
	// Does not support flag GLOB_BRACE
12
13
	function glob_recursive($pattern, $flags = 0)
14
	{
15
		$files = glob($pattern, $flags);
16
17
		foreach (glob(dirname($pattern) . '/*', GLOB_ONLYDIR | GLOB_NOSORT) as $dir)
18
		{
19
			$files = array_merge($files, glob_recursive($dir . '/' . basename($pattern), $flags));
20
		}
21
22
		return $files;
23
	}
24
}
25
26
function get_text_to_replace($tokens)
27
{
28
	if ($tokens[0][0] !== T_OPEN_TAG)
29
	{
30
		return NULL;
31
	}
32
33
	// If there is already a docblock, as the second token after the
34
	// open tag, get the contents of that token to replace
35
	if ($tokens[1][0] === T_DOC_COMMENT)
36
	{
37
		return "<?php\n" . $tokens[1][1];
38
	}
39
	// If there is a declare strict types,
40
	else if ($tokens[1][0] === T_DECLARE && $tokens[9][0] === T_DOC_COMMENT)
41
	{
42
		// '<?php' and 'declare(strict_types=1);' makes for 8 tokens
43
		// replace it all
44
		return "<?php\ndeclare(strict_types=1);\n" . $tokens[9][1];
45
	}
46
	else if ($tokens[1][0] !== T_DOC_COMMENT)
47
	{
48
		return "<?php";
49
	}
50
}
51
52
function get_tokens($source)
53
{
54
	return token_get_all($source);
55
}
56
57
function replace_files(array $files, $template)
58
{
59
	foreach ($files as $file)
60
	{
61
		$source = file_get_contents($file);
62
		$tokens = get_tokens($source);
63
//print_r($tokens);
64
		$text_to_replace = get_text_to_replace($tokens);
65
66
		$header = file_get_contents(__DIR__ . $template);
67
		$new_text = "<?php declare(strict_types=1);\n{$header}";
68
69
		$new_source = str_replace($text_to_replace, $new_text, $source);
70
		file_put_contents($file, $new_source);
71
72
		//break;
73
	}
74
}
75
76
foreach ($file_patterns as $glob)
77
{
78
	$files = glob_recursive($glob);
79
	replace_files($files, '/header_comment.txt');
80
}
81
82
echo "Successfully updated headers \n";