update_header_comments.php ➔ replace_files()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
nc 3
nop 2
dl 0
loc 22
rs 9.568
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
$file_patterns = [
5
    'src/*.php',
6
    'tests/*.php',
7
    'Robofile.php'
8
];
9
10 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...
11
{
12
    // Does not support flag GLOB_BRACE
13
14
    function glob_recursive($pattern, $flags = 0)
15
    {
16
        $files = glob($pattern, $flags);
17
18
        foreach (glob(dirname($pattern) . '/*', GLOB_ONLYDIR | GLOB_NOSORT) as $dir)
19
        {
20
            $files = array_merge($files, glob_recursive($dir . '/' . basename($pattern), $flags));
21
        }
22
23
        return $files;
24
    }
25
}
26
27
function get_text_to_replace($tokens)
28
{
29
    $output = '';
30
31
    // Tokens have the follow structure if arrays:
32
    // [0] => token type constant
33
    // [1] => raw sytax parsed to that token
34
    // [2] => line number
35
    foreach($tokens as $token)
36
    {
37
        // Since we only care about opening docblocks,
38
        // bail out when we get to the namespace token
39
        if (is_array($token) && $token[0] === T_NAMESPACE)
40
        {
41
            break;
42
        }
43
44
        if (is_array($token))
45
        {
46
            $token = $token[1];
47
        }
48
49
        $output .= $token;
50
    }
51
52
    return $output;
53
}
54
55
function get_tokens($source)
56
{
57
    return token_get_all($source);
58
}
59
60
function replace_files(array $files, $template)
61
{
62
    print_r($files);
63
    foreach ($files as $file)
64
    {
65
        $source = file_get_contents($file);
66
67
        if (stripos($source, 'namespace') === FALSE)
68
        {
69
            continue;
70
        }
71
72
        $tokens = get_tokens($source);
73
        $text_to_replace = get_text_to_replace($tokens);
74
75
        $header = file_get_contents(__DIR__ . $template);
76
        $new_text = "<?php declare(strict_types=1);\n{$header}";
77
78
        $new_source = str_replace($text_to_replace, $new_text, $source);
79
        file_put_contents($file, $new_source);
80
    }
81
}
82
83
foreach ($file_patterns as $glob)
84
{
85
    $files = glob_recursive($glob);
86
    replace_files($files, '/header_comment.txt');
87
}
88
89
echo "Successfully updated headers \n";
90