Merge "Update Vue to 3.5.13"
[mediawiki.git] / includes / libs / filebackend / fsfile / TempFSFileFactory.php
blobb92b0acd6bc260472f0923117c21edab04be8ceb
1 <?php
3 namespace MediaWiki\FileBackend\FSFile;
5 use Wikimedia\AtEase\AtEase;
6 use Wikimedia\FileBackend\FSFile\TempFSFile;
8 /**
9 * @ingroup FileBackend
11 class TempFSFileFactory {
12 /** @var string|null */
13 private $tmpDirectory;
15 /**
16 * @param string|null $tmpDirectory A directory to put the temporary files in, e.g.,
17 * $wgTmpDirectory. If null, we'll try to find one ourselves.
19 public function __construct( $tmpDirectory = null ) {
20 $this->tmpDirectory = $tmpDirectory;
23 /**
24 * Make a new temporary file on the file system.
25 * Temporary files may be purged when the file object falls out of scope.
27 * @param string $prefix
28 * @param string $extension Optional file extension
29 * @return TempFSFile|null
31 public function newTempFSFile( $prefix, $extension = '' ) {
32 $ext = ( $extension != '' ) ? ".{$extension}" : '';
33 $tmpDirectory = $this->tmpDirectory;
34 if ( !is_string( $tmpDirectory ) ) {
35 $tmpDirectory = TempFSFile::getUsableTempDirectory();
38 $attempts = 5;
39 while ( $attempts-- ) {
40 $hex = sprintf( '%06x%06x', mt_rand( 0, 0xffffff ), mt_rand( 0, 0xffffff ) );
41 $path = "$tmpDirectory/$prefix$hex$ext";
42 AtEase::suppressWarnings();
43 $newFileHandle = fopen( $path, 'x' );
44 AtEase::restoreWarnings();
45 if ( $newFileHandle ) {
46 fclose( $newFileHandle );
47 $tmpFile = new TempFSFile( $path );
48 $tmpFile->autocollect();
49 // Safely instantiated, end loop.
50 return $tmpFile;
54 // Give up
55 return null; // @codeCoverageIgnore