1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
|
<?php
namespace Wikimedia\Tests\ParamValidator\Util;
use PHPUnit\Framework\TestCase;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
abstract class UploadedFileTestBase extends TestCase {
/** @var string|null */
protected static $tmpdir;
public static function setUpBeforeClass(): void {
parent::setUpBeforeClass();
// Create a temporary directory for this test's files.
self::$tmpdir = null;
$base = sys_get_temp_dir() . DIRECTORY_SEPARATOR .
'phpunit-ParamValidator-UploadedFileTest-' . time() . '-' . getmypid() . '-';
for ( $i = 0; $i < 10000; $i++ ) {
$dir = $base . sprintf( '%04d', $i );
if ( @mkdir( $dir, 0700, false ) === true ) {
self::$tmpdir = $dir;
break;
}
}
if ( self::$tmpdir === null ) {
self::fail( "Could not create temporary directory '{$base}XXXX'" );
}
}
public static function tearDownAfterClass(): void {
// Clean up temporary directory.
if ( self::$tmpdir !== null ) {
$iter = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator( self::$tmpdir, RecursiveDirectoryIterator::SKIP_DOTS ),
RecursiveIteratorIterator::CHILD_FIRST
);
foreach ( $iter as $file ) {
if ( $file->isDir() ) {
rmdir( $file->getRealPath() );
} else {
unlink( $file->getRealPath() );
}
}
rmdir( self::$tmpdir );
self::$tmpdir = null;
}
parent::tearDownAfterClass();
}
protected static function assertTmpdir() {
if ( self::$tmpdir === null || !is_dir( self::$tmpdir ) ) {
self::fail( 'No temporary directory for ' . static::class );
}
}
/**
* @param string $prefix For tempnam()
* @param string $content Contents of the file
* @return string Filename
*/
protected function makeTemp( $prefix, $content = 'foobar' ) {
self::assertTmpdir();
$filename = tempnam( self::$tmpdir, $prefix );
if ( $filename === false ) {
self::fail( 'Failed to create temporary file' );
}
self::assertSame(
strlen( $content ),
file_put_contents( $filename, $content ),
'Writing test temporary file'
);
return $filename;
}
}
|