FileHelperTest.php 11.3 KB
Newer Older
1 2
<?php

Qiang Xue committed
3
use yii\helpers\FileHelper;
4
use yiiunit\TestCase;
5 6

/**
7
 * Unit test for [[yii\helpers\FileHelper]]
8
 * @see FileHelper
9
 * @group helpers
10 11 12
 */
class FileHelperTest extends TestCase
{
13 14 15
	/**
	 * @var string test files path.
	 */
16 17 18 19 20 21
	private $testFilePath = '';

	public function setUp()
	{
		$this->testFilePath = Yii::getAlias('@yiiunit/runtime') . DIRECTORY_SEPARATOR . get_class($this);
		$this->createDir($this->testFilePath);
22 23 24
		if (!file_exists($this->testFilePath)) {
			$this->markTestIncomplete('Unit tests runtime directory should have writable permissions!');
		}
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
	}

	public function tearDown()
	{
		$this->removeDir($this->testFilePath);
	}

	/**
	 * Creates directory.
	 * @param string $dirName directory full name.
	 */
	protected function createDir($dirName)
	{
		if (!file_exists($dirName)) {
			mkdir($dirName, 0777, true);
		}
	}

	/**
	 * Removes directory.
	 * @param string $dirName directory full name.
	 */
	protected function removeDir($dirName)
	{
Qiang Xue committed
49
		if (!empty($dirName) && is_dir($dirName)) {
50 51 52 53 54 55 56 57 58 59 60 61 62
			if ($handle = opendir($dirName)) {
				while (false !== ($entry = readdir($handle))) {
					if ($entry != '.' && $entry != '..') {
						if (is_dir($dirName . DIRECTORY_SEPARATOR . $entry) === true) {
							$this->removeDir($dirName . DIRECTORY_SEPARATOR . $entry);
						} else {
							unlink($dirName . DIRECTORY_SEPARATOR . $entry);
						}
					}
				}
				closedir($handle);
				rmdir($dirName);
			}
63 64 65
		}
	}

66 67 68 69 70 71 72 73 74 75
	/**
	 * Get file permission mode.
	 * @param string $file file name.
	 * @return string permission mode.
	 */
	protected function getMode($file)
	{
		return substr(sprintf('%o', fileperms($file)), -4);
	}

76 77 78 79 80 81
	/**
	 * Creates test files structure,
	 * @param array $items file system objects to be created in format: objectName => objectContent
	 * Arrays specifies directories, other values - files.
	 * @param string $basePath structure base file path.
	 */
82 83
	protected function createFileStructure(array $items, $basePath = '')
	{
84 85 86 87 88 89 90 91 92 93 94 95 96 97
		if (empty($basePath)) {
			$basePath = $this->testFilePath;
		}
		foreach ($items as $name => $content) {
			$itemName = $basePath . DIRECTORY_SEPARATOR . $name;
			if (is_array($content)) {
				mkdir($itemName, 0777, true);
				$this->createFileStructure($content, $itemName);
			} else {
				file_put_contents($itemName, $content);
			}
		}
	}

98 99 100 101 102 103
	/**
	 * Asserts that file has specific permission mode.
	 * @param integer $expectedMode expected file permission mode.
	 * @param string $fileName file name.
	 * @param string $message error message
	 */
Alexander Makarov committed
104
	protected function assertFileMode($expectedMode, $fileName, $message = '')
105 106 107 108 109
	{
		$expectedMode = sprintf('%o', $expectedMode);
		$this->assertEquals($expectedMode, $this->getMode($fileName), $message);
	}

110 111
	// Tests :

112 113
	public function testCopyDirectory()
	{
114
		$srcDirName = 'test_src_dir';
Alexander Makarov committed
115
		$files = [
116 117
			'file1.txt' => 'file 1 content',
			'file2.txt' => 'file 2 content',
Alexander Makarov committed
118 119
		];
		$this->createFileStructure([
120
			$srcDirName => $files
Alexander Makarov committed
121
		]);
122 123 124

		$basePath = $this->testFilePath;
		$srcDirName = $basePath . DIRECTORY_SEPARATOR . $srcDirName;
125 126 127 128
		$dstDirName = $basePath . DIRECTORY_SEPARATOR . 'test_dst_dir';

		FileHelper::copyDirectory($srcDirName, $dstDirName);

129
		$this->assertFileExists($dstDirName, 'Destination directory does not exist!');
130 131
		foreach ($files as $name => $content) {
			$fileName = $dstDirName . DIRECTORY_SEPARATOR . $name;
132
			$this->assertFileExists($fileName);
133 134 135
			$this->assertEquals($content, file_get_contents($fileName), 'Incorrect file content!');
		}
	}
136

137 138 139 140 141 142 143 144 145 146 147 148
	/**
	 * @depends testCopyDirectory
	 */
	public function testCopyDirectoryPermissions()
	{
		if (substr(PHP_OS, 0, 3) == 'WIN') {
			$this->markTestSkipped("Can't reliably test it on Windows because fileperms() always return 0777.");
		}

		$srcDirName = 'test_src_dir';
		$subDirName = 'test_sub_dir';
		$fileName = 'test_file.txt';
Alexander Makarov committed
149 150 151
		$this->createFileStructure([
			$srcDirName => [
				$subDirName => [],
152
				$fileName => 'test file content',
Alexander Makarov committed
153 154
			],
		]);
155 156 157 158 159 160 161

		$basePath = $this->testFilePath;
		$srcDirName = $basePath . DIRECTORY_SEPARATOR . $srcDirName;
		$dstDirName = $basePath . DIRECTORY_SEPARATOR . 'test_dst_dir';

		$dirMode = 0755;
		$fileMode = 0755;
Alexander Makarov committed
162
		$options = [
163 164
			'dirMode' => $dirMode,
			'fileMode' => $fileMode,
Alexander Makarov committed
165
		];
166 167 168 169 170 171 172
		FileHelper::copyDirectory($srcDirName, $dstDirName, $options);

		$this->assertFileMode($dirMode, $dstDirName, 'Destination directory has wrong mode!');
		$this->assertFileMode($dirMode, $dstDirName . DIRECTORY_SEPARATOR . $subDirName, 'Copied sub directory has wrong mode!');
		$this->assertFileMode($fileMode, $dstDirName . DIRECTORY_SEPARATOR . $fileName, 'Copied file has wrong mode!');
	}

173
	public function testRemoveDirectory()
174
	{
175
		$dirName = 'test_dir_for_remove';
Alexander Makarov committed
176 177
		$this->createFileStructure([
			$dirName => [
178 179
				'file1.txt' => 'file 1 content',
				'file2.txt' => 'file 2 content',
Alexander Makarov committed
180
				'test_sub_dir' => [
181 182
					'sub_dir_file_1.txt' => 'sub dir file 1 content',
					'sub_dir_file_2.txt' => 'sub dir file 2 content',
Alexander Makarov committed
183 184 185
				],
			],
		]);
186

187
		$basePath = $this->testFilePath;
188
		$dirName = $basePath . DIRECTORY_SEPARATOR . $dirName;
189 190 191

		FileHelper::removeDirectory($dirName);

192
		$this->assertFileNotExists($dirName, 'Unable to remove directory!');
193 194 195

		// should be silent about non-existing directories
		FileHelper::removeDirectory($basePath . DIRECTORY_SEPARATOR . 'nonExisting');
196
	}
197 198 199

	public function testFindFiles()
	{
200
		$dirName = 'test_dir';
Alexander Makarov committed
201 202
		$this->createFileStructure([
			$dirName => [
203 204
				'file_1.txt' => 'file 1 content',
				'file_2.txt' => 'file 2 content',
Alexander Makarov committed
205
				'test_sub_dir' => [
206 207
					'file_1_1.txt' => 'sub dir file 1 content',
					'file_1_2.txt' => 'sub dir file 2 content',
Alexander Makarov committed
208 209 210
				],
			],
		]);
211
		$basePath = $this->testFilePath;
212
		$dirName = $basePath . DIRECTORY_SEPARATOR . $dirName;
Alexander Makarov committed
213
		$expectedFiles = [
214 215 216 217
			$dirName . DIRECTORY_SEPARATOR . 'file_1.txt',
			$dirName . DIRECTORY_SEPARATOR . 'file_2.txt',
			$dirName . DIRECTORY_SEPARATOR . 'test_sub_dir' . DIRECTORY_SEPARATOR . 'file_1_1.txt',
			$dirName . DIRECTORY_SEPARATOR . 'test_sub_dir' . DIRECTORY_SEPARATOR . 'file_1_2.txt',
Alexander Makarov committed
218
		];
219 220 221

		$foundFiles = FileHelper::findFiles($dirName);
		sort($expectedFiles);
Qiang Xue committed
222
		sort($foundFiles);
223 224
		$this->assertEquals($expectedFiles, $foundFiles);
	}
225

226 227 228 229 230 231 232
	/**
	 * @depends testFindFiles
	 */
	public function testFindFileFilter()
	{
		$dirName = 'test_dir';
		$passedFileName = 'passed.txt';
Alexander Makarov committed
233 234
		$this->createFileStructure([
			$dirName => [
235 236
				$passedFileName => 'passed file content',
				'declined.txt' => 'declined file content',
Alexander Makarov committed
237 238
			],
		]);
239 240 241
		$basePath = $this->testFilePath;
		$dirName = $basePath . DIRECTORY_SEPARATOR . $dirName;

Alexander Makarov committed
242
		$options = [
Alexander Makarov committed
243
			'filter' => function ($path) use ($passedFileName) {
Qiang Xue committed
244
				return $passedFileName == basename($path);
245
			}
Alexander Makarov committed
246
		];
247
		$foundFiles = FileHelper::findFiles($dirName, $options);
Alexander Makarov committed
248
		$this->assertEquals([$dirName . DIRECTORY_SEPARATOR . $passedFileName], $foundFiles);
249 250
	}

251 252 253 254 255
	/**
	 * @depends testFindFiles
	 */
	public function testFindFilesExclude()
	{
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
		$basePath = $this->testFilePath . DIRECTORY_SEPARATOR;
		$dirs = array('', 'one', 'one'.DIRECTORY_SEPARATOR.'two', 'three');
		$files = array_fill_keys(array_map(function($n){return "a.$n";}, range(1,8)), 'file contents');

		$tree = $files;
		$root = $files;
		$flat = array();
		foreach($dirs as $dir) {
			foreach($files as $fileName=>$contents) {
				$flat[] = rtrim($basePath.$dir,DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR.$fileName;
			}
			if ($dir === '') continue;
			$parts = explode(DIRECTORY_SEPARATOR, $dir);
			$last = array_pop($parts);
			$parent = array_pop($parts);
			$tree[$last] = $files;
			if ($parent !== null) {
				$tree[$parent][$last] = &$tree[$last];
			} else {
				$root[$last] = &$tree[$last];
			}
		}
		$this->createFileStructure($root);
279

280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
		// range
		$foundFiles = FileHelper::findFiles($basePath, ['except' => ['a.[2-8]']]);
		sort($foundFiles);
		$expect = array_values(array_filter($flat, function($p){return substr($p, -3)==='a.1';}));
		$this->assertEquals($expect, $foundFiles);

		// suffix
		$foundFiles = FileHelper::findFiles($basePath, ['except' => ['*.1']]);
		sort($foundFiles);
		$expect = array_values(array_filter($flat, function($p){return substr($p, -3)!=='a.1';}));
		$this->assertEquals($expect, $foundFiles);

		// dir
		$foundFiles = FileHelper::findFiles($basePath, ['except' => ['/one']]);
		sort($foundFiles);
		$expect = array_values(array_filter($flat, function($p){return strpos($p, DIRECTORY_SEPARATOR.'one')===false;}));
		$this->assertEquals($expect, $foundFiles);

		// dir contents
		$foundFiles = FileHelper::findFiles($basePath, ['except' => ['?*/a.1']]);
		sort($foundFiles);
		$expect = array_values(array_filter($flat, function($p){
			return substr($p, -11, 10)==='one'.DIRECTORY_SEPARATOR.'two'.DIRECTORY_SEPARATOR.'a.' || (
				substr($p, -8)!==DIRECTORY_SEPARATOR.'one'.DIRECTORY_SEPARATOR.'a.1' &&
				substr($p, -10)!==DIRECTORY_SEPARATOR.'three'.DIRECTORY_SEPARATOR.'a.1'
			);
		}));
		$this->assertEquals($expect, $foundFiles);
308
	}
309

310
	public function testCreateDirectory()
Alexander Makarov committed
311
	{
312 313
		$basePath = $this->testFilePath;
		$dirName = $basePath . DIRECTORY_SEPARATOR . 'test_dir_level_1' . DIRECTORY_SEPARATOR . 'test_dir_level_2';
314
		$this->assertTrue(FileHelper::createDirectory($dirName), 'FileHelper::createDirectory should return true if directory was created!');
315
		$this->assertFileExists($dirName, 'Unable to create directory recursively!');
316
		$this->assertTrue(FileHelper::createDirectory($dirName), 'FileHelper::createDirectory should return true for already existing directories!');
317
	}
318 319 320 321

	public function testGetMimeTypeByExtension()
	{
		$magicFile = $this->testFilePath . DIRECTORY_SEPARATOR . 'mime_type.php';
Alexander Makarov committed
322
		$mimeTypeMap = [
323 324
			'txa' => 'application/json',
			'txb' => 'another/mime',
Alexander Makarov committed
325
		];
326 327 328 329 330 331 332 333 334
		$magicFileContent = '<?php return ' . var_export($mimeTypeMap, true) . ';';
		file_put_contents($magicFile, $magicFileContent);

		foreach ($mimeTypeMap as $extension => $mimeType) {
			$fileName = 'test.' . $extension;
			$this->assertNull(FileHelper::getMimeTypeByExtension($fileName));
			$this->assertEquals($mimeType, FileHelper::getMimeTypeByExtension($fileName, $magicFile));
		}
	}
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350

	public function testGetMimeType()
	{
		$file = $this->testFilePath . DIRECTORY_SEPARATOR . 'mime_type_test.txt';
		file_put_contents($file, 'some text');
		$this->assertEquals('text/plain', FileHelper::getMimeType($file));

		$file = $this->testFilePath . DIRECTORY_SEPARATOR . 'mime_type_test.json';
		file_put_contents($file, '{"a": "b"}');
		$this->assertEquals('text/plain', FileHelper::getMimeType($file));
	}

	public function testNormalizePath()
	{
		$this->assertEquals(DIRECTORY_SEPARATOR.'home'.DIRECTORY_SEPARATOR.'demo', FileHelper::normalizePath('/home\demo/'));
	}
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375

	public function testLocalizedDirectory()
	{
		$this->createFileStructure([
			'views' => [
				'faq.php' => 'English FAQ',
				'de-DE' => [
					'faq.php' => 'German FAQ',
				],
			],
		]);
		$viewFile = $this->testFilePath . DIRECTORY_SEPARATOR . 'views' . DIRECTORY_SEPARATOR . 'faq.php';
		$sourceLanguage = 'en-US';

		// Source language and target language are same. The view path should be unchanged.
		$currentLanguage = $sourceLanguage;
		$this->assertSame($viewFile, FileHelper::localize($viewFile, $currentLanguage, $sourceLanguage));

		// Source language and target language are different. The view path should be changed.
		$currentLanguage = 'de-DE';
		$this->assertSame(
			$this->testFilePath . DIRECTORY_SEPARATOR . 'views' . DIRECTORY_SEPARATOR . $currentLanguage . DIRECTORY_SEPARATOR . 'faq.php',
			FileHelper::localize($viewFile, $currentLanguage, $sourceLanguage)
		);
	}
Qiang Xue committed
376
}