MediaWiki master
FileContentsHasher.php
Go to the documentation of this file.
1<?php
2
3namespace MediaWiki\Utils;
4
12
17 private const ALGO = 'md4';
18
20 protected $cache;
21
23 private static $instance;
24
25 public function __construct() {
26 $this->cache = function_exists( 'apcu_fetch' ) ? new APCUBagOStuff() : new EmptyBagOStuff();
27 }
28
34 public static function singleton() {
35 if ( !self::$instance ) {
36 self::$instance = new self;
37 }
38
39 return self::$instance;
40 }
41
49 private function getFileContentsHashInternal( $filePath ) {
50 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
51 $mtime = @filemtime( $filePath );
52 if ( $mtime === false ) {
53 return false;
54 }
55
56 $cacheKey = $this->cache->makeGlobalKey( __CLASS__, $filePath, $mtime, self::ALGO );
57 return $this->cache->getWithSetCallback(
58 $cacheKey,
59 $this->cache::TTL_DAY,
60 static function () use ( $filePath ) {
61 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
62 $contents = @file_get_contents( $filePath );
63 if ( $contents === false ) {
64 // Don't cache false
65 return false;
66 }
67
68 return hash( self::ALGO, $contents );
69 }
70 );
71 }
72
81 public static function getFileContentsHash( $filePaths ) {
82 $instance = self::singleton();
83
84 if ( !is_array( $filePaths ) ) {
85 $filePaths = (array)$filePaths;
86 }
87
88 if ( count( $filePaths ) === 1 ) {
89 $hash = $instance->getFileContentsHashInternal( $filePaths[0] );
90 return $hash;
91 }
92
93 sort( $filePaths );
94 $hashes = [];
95 foreach ( $filePaths as $filePath ) {
96 $hashes[] = $instance->getFileContentsHashInternal( $filePath ) ?: '';
97 }
98
99 $hashes = implode( '', $hashes );
100 return $hashes ? hash( self::ALGO, $hashes ) : false;
101 }
102}
103
105class_alias( FileContentsHasher::class, 'FileContentsHasher' );
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.
Copyright (C) 2017 Kunal Mehta legoktm@debian.org