MediaWiki master
FileContentsHasher.php
Go to the documentation of this file.
1<?php
2
10
15 private const ALGO = 'md4';
16
18 protected $cache;
19
21 private static $instance;
22
23 public function __construct() {
24 $this->cache = function_exists( 'apcu_fetch' ) ? new APCUBagOStuff() : new EmptyBagOStuff();
25 }
26
32 public static function singleton() {
33 if ( !self::$instance ) {
34 self::$instance = new self;
35 }
36
37 return self::$instance;
38 }
39
47 private function getFileContentsHashInternal( $filePath ) {
48 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
49 $mtime = @filemtime( $filePath );
50 if ( $mtime === false ) {
51 return false;
52 }
53
54 $cacheKey = $this->cache->makeGlobalKey( __CLASS__, $filePath, $mtime, self::ALGO );
55 return $this->cache->getWithSetCallback(
56 $cacheKey,
57 $this->cache::TTL_DAY,
58 static function () use ( $filePath ) {
59 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
60 $contents = @file_get_contents( $filePath );
61 if ( $contents === false ) {
62 // Don't cache false
63 return false;
64 }
65
66 return hash( self::ALGO, $contents );
67 }
68 );
69 }
70
79 public static function getFileContentsHash( $filePaths ) {
80 $instance = self::singleton();
81
82 if ( !is_array( $filePaths ) ) {
83 $filePaths = (array)$filePaths;
84 }
85
86 if ( count( $filePaths ) === 1 ) {
87 $hash = $instance->getFileContentsHashInternal( $filePaths[0] );
88 return $hash;
89 }
90
91 sort( $filePaths );
92 $hashes = [];
93 foreach ( $filePaths as $filePath ) {
94 $hashes[] = $instance->getFileContentsHashInternal( $filePath ) ?: '';
95 }
96
97 $hashes = implode( '', $hashes );
98 return $hashes ? hash( self::ALGO, $hashes ) : false;
99 }
100}
Generate hash digests of file contents to help with cache invalidation.
static singleton()
Get the singleton instance of this class.
static getFileContentsHash( $filePaths)
Get a hash of the combined contents of one or more files, either by retrieving a previously-computed ...
Store data in the local server memory via APCu (php-apcu)
Abstract class for any ephemeral data store.
Definition BagOStuff.php:73
No-op implementation that stores nothing.