summaryrefslogtreecommitdiff
path: root/www/wiki/extensions/SemanticMediaWiki/tests/phpunit/Utils/File/DummyFileCreator.php
blob: 102c44d64f49db8f4519dba747a103140ae2c1f7 (plain)
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
<?php

namespace SMW\Tests\Utils\File;

use RuntimeException;

/**
 * @license GNU GPL v2+
 * @since 2.1
 *
 * @author mwjames
 */
class DummyFileCreator {

	/**
	 * @var string
	 */
	private $desiredDestName;

	/**
	 * @var string
	 */
	private $file = '';

	/**
	 * @var integer
	 */
	private $size = 100;

	/**
	 * @since 2.1
	 *
	 * @param string $desiredDestName
	 *
	 * @return string
	 */
	public function createEmptyFile( $desiredDestName ) {
		$this->file = $this->createFile( $desiredDestName );
	}

	/**
	 * @since 2.1
	 *
	 * @param string $desiredDestName
	 * @param string $contentCopyPath
	 *
	 * @return string
	 */
	public function createFileWithCopyFrom( $desiredDestName, $contentCopyPath ) {
		$this->file = $this->createFile( $desiredDestName, file_get_contents( $this->getFile( $contentCopyPath ) ) );
	}

	/**
	 * @since 2.1
	 *
	 * @return string
	 */
	public function getPath() {
		return $this->file;
	}

	/**
	 * @since 2.1
	 */
	public function delete() {
		unlink( $this->file );
	}

	private function createFile( $desiredDestName, $content = '' ) {

		$filename = $this->getLocationForTemporaryFile( $desiredDestName );

		$fh = fopen( $filename, 'w' );

		if ( $content === '' ) {
			ftruncate( $fh, $this->size );
		} else {
			fwrite( $fh, $content );
		}

		fclose( $fh );

		return $this->getFile( $filename );
	}

	private function getLocationForTemporaryFile( $desiredDestName ) {
		return sys_get_temp_dir() . '/' . $desiredDestName;
	}

	private function getFile( $path ) {

		$path = str_replace( [ '\\', '/' ], DIRECTORY_SEPARATOR, $path );

		if ( is_readable( $path ) ) {
			return $path;
		}

		throw new RuntimeException( "Expected an accessible {$path}" );
	}

}