root/namespace-unused @ 1509

Revision 1509, 1.7 kB (checked in by Torben Brodt, 16 months ago)

tool to remove unused namespaces

  • Property svn:executable set to *
Line 
1#!/usr/bin/php
2<?php
3if(!isset($_SERVER['argv'][1]) || in_array($_SERVER['argv'][1], array('--help', '-h', '-?'))) {
4        help();
5        exit;
6}
7$dir = $_SERVER['argv'][1];
8$pattern = isset($_SERVER['argv'][2]) ? $_SERVER['argv'][2] : '/\.php$/';
9
10$ite = new RecursiveDirectoryIterator($dir);
11foreach (new RecursiveIteratorIterator($ite) as $filename => $cur) {
12        if(preg_match($pattern, $filename)) {
13                updateFile($filename);
14        }
15}
16
17
18function updateFile($filename) {
19        echo $filename;
20
21        $block = file($filename);
22        $useblock = array();
23        $i = 0;
24        foreach($block as $line) {
25                if(preg_match('/^use .*(?: |\\\)([a-zA-Z]+);$/', $line, $res)) {
26                        $useblock[$i] = $res[1];
27                }
28                $i++;
29        }
30        $flipped = array_flip($useblock);
31       
32        if($useblock) {
33                $regexp = '/(?:new ('.implode("|", $useblock).')(?: |\()'.
34                        '|('.implode("|", $useblock).')::[^\W]+'.
35                        '|(?:extends|implements) ('.implode("|", $useblock).')(?: |$)'.
36                        '|(?:catch \(('.implode("|", $useblock).') )'.
37                ')/';
38                preg_match_all($regexp, implode("", $block), $res);
39                if($res) {
40                        $res = array_merge((array)$res[1], (array)$res[2], (array)$res[3], (array)$res[4]);
41                        foreach($res as $className) {
42                                if(!isset($flipped[$className])) {
43                                        continue;
44                                }
45                                $idx = $flipped[$className];
46                                unset($useblock[$idx]);
47                        }
48                }
49                if($useblock) {
50                        foreach($useblock as $idx => $line) {
51                                unset($block[$idx]);
52                        }
53                }
54        }
55
56        if($useblock) {
57                file_put_contents($filename, implode("", $block));
58                echo "\tchanged\n";
59        } else {
60                echo "\tunchanged\n";
61        }
62}
63
64function help() {
65        echo "removes unused use clauses";
66        echo "\n";
67        echo "Usage: " . basename($_SERVER['argv'][0]) . " folder [--help]\n";
68        echo "\n";
69        echo "The options are as follows:\n";
70        echo "  -?, --help\n";
71        echo "    Show this help and exit.\n\n";
72}
Note: See TracBrowser for help on using the browser.