Johnsen Parker
Johnsen Parker

Reputation: 31

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 );
}

Upvotes: 3

Views: 209

Answers (2)

Zoltán Jére
Zoltán Jére

Reputation: 634

I guess my version is way bigger then Romans, but as an OOP problem I think this is a possible solution too:

<?php

interface HashInterface
{
    public function hash();
}

class ModifiedHash implements HashInterface
{
    public function hash($file)
    {
        return filemtime($file);
    }
}

class FileNameHash implements HashInterface
{
    public function hash($file)
    {
        return basename($file);
    }
}

class SomeClient
{
    private $hashType;

    public function setHashType(HashInterface $hashType)
    {
        $this->hashType = $hashType;
    }

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

        foreach ( $files as $file ) {
            $joined .= $this->hashType->hash( $file );
        }

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

$client = new SomeClient();
$files = ???;

// Want a ModifiedHash?
$client->setHashType(new ModifiedHash());
$data = $client->doHash($files);

// Want a FileNameHash?
$client->setHashType(new FileNameHash());
$data = $client->doHash($files);

Sorry for the confusing class or method names. I hope you got the idea.

Upvotes: 0

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

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

Upvotes: 4

Related Questions