| 1 |
<?php |
| 2 |
|
| 3 |
use Wikimedia\ObjectCache\APCUBagOStuff; |
| 4 |
use Wikimedia\ObjectCache\BagOStuff; |
| 5 |
use Wikimedia\ObjectCache\EmptyBagOStuff; |
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
class FileContentsHasher { |
| 28 |
private const ALGO = 'md4'; |
| 29 |
|
| 30 |
|
| 31 |
protected $cache; |
| 32 |
|
| 33 |
|
| 34 |
private static $instance; |
| 35 |
|
| 36 |
public function __construct() { |
| 37 |
$this->cache = function_exists( 'apcu_fetch' ) ? new APCUBagOStuff() : new EmptyBagOStuff(); |
| 38 |
} |
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
public static function singleton() { |
| 46 |
if ( !self::$instance ) { |
| 47 |
self::$instance = new self; |
| 48 |
} |
| 49 |
|
| 50 |
return self::$instance; |
| 51 |
} |
| 52 |
|
| 53 |
|
| 54 |
|
| 55 |
|
| 56 |
|
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
private function getFileContentsHashInternal( $filePath ) { |
| 61 |
|
| 62 |
$mtime = @filemtime( $filePath ); |
| 63 |
if ( $mtime === false ) { |
| 64 |
return false; |
| 65 |
} |
| 66 |
|
| 67 |
$cacheKey = $this->cache->makeGlobalKey( __CLASS__, $filePath, $mtime, self::ALGO ); |
| 68 |
return $this->cache->getWithSetCallback( |
| 69 |
$cacheKey, |
| 70 |
$this->cache::TTL_DAY, |
| 71 |
static function () use ( $filePath ) { |
| 72 |
|
| 73 |
$contents = @file_get_contents( $filePath ); |
| 74 |
if ( $contents === false ) { |
| 75 |
|
| 76 |
return false; |
| 77 |
} |
| 78 |
|
| 79 |
return hash( self::ALGO, $contents ); |
| 80 |
} |
| 81 |
); |
| 82 |
} |
| 83 |
|
| 84 |
|
| 85 |
|
| 86 |
|
| 87 |
|
| 88 |
|
| 89 |
|
| 90 |
|
| 91 |
|
| 92 |
public static function getFileContentsHash( $filePaths ) { |
| 93 |
$instance = self::singleton(); |
| 94 |
|
| 95 |
if ( !is_array( $filePaths ) ) { |
| 96 |
$filePaths = (array)$filePaths; |
| 97 |
} |
| 98 |
|
| 99 |
if ( count( $filePaths ) === 1 ) { |
| 100 |
$hash = $instance->getFileContentsHashInternal( $filePaths[0] ); |
| 101 |
return $hash; |
| 102 |
} |
| 103 |
|
| 104 |
sort( $filePaths ); |
| 105 |
$hashes = []; |
| 106 |
foreach ( $filePaths as $filePath ) { |
| 107 |
$hashes[] = $instance->getFileContentsHashInternal( $filePath ) ?: ''; |
| 108 |
} |
| 109 |
|
| 110 |
$hashes = implode( '', $hashes ); |
| 111 |
return $hashes ? hash( self::ALGO, $hashes ) : false; |
| 112 |
} |
| 113 |
} |