MediaWiki master
FileContentsHasher.php
Go to the documentation of this file.
1<?php
2
6
28 private const ALGO = 'md4';
29
31 protected $cache;
32
34 private static $instance;
35
36 public function __construct() {
37 $this->cache = function_exists( 'apcu_fetch' ) ? new APCUBagOStuff() : new EmptyBagOStuff();
38 }
39
45 public static function singleton() {
46 if ( !self::$instance ) {
47 self::$instance = new self;
48 }
49
50 return self::$instance;
51 }
52
60 private function getFileContentsHashInternal( $filePath ) {
61 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
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 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
73 $contents = @file_get_contents( $filePath );
74 if ( $contents === false ) {
75 // Don't cache false
76 return false;
77 }
78
79 return hash( self::ALGO, $contents );
80 }
81 );
82 }
83
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}
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:89
No-op implementation that stores nothing.