MediaWiki REL1_39
FileContentsHasher.php
Go to the documentation of this file.
1<?php
23 private const ALGO = 'md4';
24
26 protected $cache;
27
29 private static $instance;
30
31 public function __construct() {
32 $this->cache = function_exists( 'apcu_fetch' ) ? new APCUBagOStuff() : new EmptyBagOStuff();
33 }
34
40 public static function singleton() {
41 if ( !self::$instance ) {
42 self::$instance = new self;
43 }
44
45 return self::$instance;
46 }
47
55 private function getFileContentsHashInternal( $filePath ) {
56 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
57 $mtime = @filemtime( $filePath );
58 if ( $mtime === false ) {
59 return false;
60 }
61
62 $cacheKey = $this->cache->makeGlobalKey( __CLASS__, $filePath, $mtime, self::ALGO );
63 return $this->cache->getWithSetCallback(
64 $cacheKey,
65 $this->cache::TTL_DAY,
66 static function () use ( $filePath ) {
67 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
68 $contents = @file_get_contents( $filePath );
69 if ( $contents === false ) {
70 // Don't cache false
71 return false;
72 }
73
74 return hash( self::ALGO, $contents );
75 }
76 );
77 }
78
87 public static function getFileContentsHash( $filePaths ) {
88 $instance = self::singleton();
89
90 if ( !is_array( $filePaths ) ) {
91 $filePaths = (array)$filePaths;
92 }
93
94 if ( count( $filePaths ) === 1 ) {
95 $hash = $instance->getFileContentsHashInternal( $filePaths[0] );
96 return $hash;
97 }
98
99 sort( $filePaths );
100 $hashes = [];
101 foreach ( $filePaths as $filePath ) {
102 $hashes[] = $instance->getFileContentsHashInternal( $filePath ) ?: '';
103 }
104
105 $hashes = implode( '', $hashes );
106 return $hashes ? hash( self::ALGO, $hashes ) : false;
107 }
108}
This is a wrapper for APCu's shared memory functions.
Class representing a cache/ephemeral data store.
Definition BagOStuff.php:85
A BagOStuff object with no objects in it.
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 ...