Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reduce code duplication

As I'm not familiar with PHP I wonde how do I reduce code duplication here? Both methods are doing exactly the same thing here... except the part where the string is extracted (filemtime and basename) and joined.

private function modified_hash( $files ) {
    $joined = "";

    foreach ( $files as $file ) {
        $joined .= filemtime( $file );
    }

    return $this->checksum( $joined );
}

private function filename_hash( $files ) {
    $joined = "";

    foreach ( $files as $file ) {
        $joined .= basename( $file );
    }

    return $this->checksum( $joined );
}
like image 510
Johnsen Parker Avatar asked Mar 18 '26 05:03

Johnsen Parker


1 Answers

Instead of two functions, declare a unified function with an argument for a crucial callback/function name $func_name:

/**
 * Gets joined files hash
 * 
 * @param $files an array of file paths
 * @param $func_name callback name
 * @return mixed
 */
private function getFilesHash($files, callable $func_name) {
    $joined = "";

    foreach ($files as $file) {
        $joined .= call_user_func($func_name, $file);
    }

    return $this->checksum($joined);
}

Usage:

$fileHash = getFilesHash($files, 'basename');

Used functions: call_user_func

like image 179
RomanPerekhrest Avatar answered Mar 19 '26 18:03

RomanPerekhrest