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