Skip to content

Instantly share code, notes, and snippets.

@techouse
Last active January 18, 2017 08:54
Show Gist options
  • Save techouse/4e8df5cf0f057facd697cbbd3dc80c4b to your computer and use it in GitHub Desktop.
Save techouse/4e8df5cf0f057facd697cbbd3dc80c4b to your computer and use it in GitHub Desktop.
Detect deprecated PHP functions based on a list of functions in CSV format, like this one https://da.gd/CupI (save it as depcheck.csv in the same folder as this Perl sript)
#!/usr/bin/env perl
use warnings;
use strict;
use utf8;
use IO::File;
use IO::Handle;
use File::Find::Rule;
use File::Spec;
use Text::CSV_XS;
use Cwd qw(abs_path);
use File::Basename qw(dirname);
# the work dir
my $dir = $ARGV[0];
die "You have to specify a directory to scan!\n" unless defined $dir;
die "Specified directory does not exist!\n" unless -d $dir;
# the deprecations CSV list
my $dep_csv = (defined $ARGV[1]) ? $ARGV[1] : dirname(abs_path($0)) . '/depcheck.csv';
die "Deprecated functions CSV file does not exist!\n" unless -e $dep_csv;
# the file extension
my $extension = 'php';
# the CSV object
my $csv = Text::CSV_XS->new({
eol => $/,
sep_char => ','
});
# the deprecations
my $dep_fh = IO::File->new($dep_csv, 'r') or die "Could not open $dep_csv : $!\n";
binmode $dep_fh, ':unix:utf8';
$csv->column_names($csv->getline($dep_fh));
my $deprecated = $csv->getline_hr_all($dep_fh);
undef $dep_fh;
if (@$deprecated) {
# convert it to a hash for later use
my %deprecated_hash = map { $_->{function} => $_ } @$deprecated;
# the functions regex pattern
my $functions_pattern = join '|', map quotemeta, map { $_->{function} } @$deprecated;
# the files list
my @files = File::Find::Rule->file
->name("*.$extension")
->in($dir);
if (@files) {
# the counter
my $deprecated_functions_counter = 0;
# create a log file
my $log_fh = IO::File->new(dirname(abs_path($0)) . '/deprecated_log.csv', 'w');
binmode $log_fh, ':unix:utf8';
$csv->print($log_fh, [qw/file line function replace/]);
# loop through the files
foreach my $file_name (@files) {
my $file_fh = IO::File->new($file_name, 'r') or die "Could not open $file_name : $!\n";
# find the matches
while (my $line = <$file_fh>) {
if (my @matches = ($line =~ m/(^|\s)($functions_pattern)\s?\(/g)) {
foreach (@matches) {
next unless exists $deprecated_hash{$_};
# count it
$deprecated_functions_counter++;
# print to STDOUT
printf "Found '%s' in file '%s' on line number %d.\n", $_, File::Spec->rel2abs($file_name), $file_fh->input_line_number;
# print to a log file
$csv->print($log_fh, [
File::Spec->rel2abs($file_name),
$file_fh->input_line_number,
$_,
$deprecated_hash{$_}{replace}
]);
}
}
}
undef $file_name;
undef $file_fh;
}
undef $log_fh;
my $summary = sprintf "TOTAL DEPRECATIONS FOUND: %d", $deprecated_functions_counter;
printf "\n\n%s\n%s\n%s\n\n", '-' x length $summary, $summary, '-' x length $summary;
}
}
exit;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment