BaseFileHelper.php 22 KB
Newer Older
Qiang Xue committed
1 2 3 4 5 6 7 8 9
<?php
/**
 * Filesystem helper class file.
 *
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

10
namespace yii\helpers;
Qiang Xue committed
11

Qiang Xue committed
12
use Yii;
13
use yii\base\InvalidParamException;
Qiang Xue committed
14 15

/**
16
 * BaseFileHelper provides concrete implementation for [[FileHelper]].
17
 *
18
 * Do not use BaseFileHelper. Use [[FileHelper]] instead.
Qiang Xue committed
19 20 21 22 23
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @author Alex Makarov <sam@rmcreative.ru>
 * @since 2.0
 */
24
class BaseFileHelper
Qiang Xue committed
25
{
26 27 28 29
	const PATTERN_NODIR = 1;
	const PATTERN_ENDSWITH = 4;
	const PATTERN_MUSTBEDIR = 8;
	const PATTERN_NEGATIVE = 16;
30

Qiang Xue committed
31 32 33 34 35 36 37 38 39 40 41
	/**
	 * Normalizes a file/directory path.
	 * After normalization, the directory separators in the path will be `DIRECTORY_SEPARATOR`,
	 * and any trailing directory separators will be removed. For example, '/home\demo/' on Linux
	 * will be normalized as '/home/demo'.
	 * @param string $path the file/directory path to be normalized
	 * @param string $ds the directory separator to be used in the normalized result. Defaults to `DIRECTORY_SEPARATOR`.
	 * @return string the normalized file/directory path
	 */
	public static function normalizePath($path, $ds = DIRECTORY_SEPARATOR)
	{
Alexander Makarov committed
42
		return rtrim(strtr($path, ['/' => $ds, '\\' => $ds]), $ds);
Qiang Xue committed
43 44 45 46 47 48 49
	}

	/**
	 * Returns the localized version of a specified file.
	 *
	 * The searching is based on the specified language code. In particular,
	 * a file with the same name will be looked for under the subdirectory
Qiang Xue committed
50
	 * whose name is the same as the language code. For example, given the file "path/to/view.php"
51 52
	 * and language code "zh-CN", the localized file will be looked for as
	 * "path/to/zh-CN/view.php". If the file is not found, it will try a fallback with just a language code that is
Alexander Makarov committed
53
	 * "zh" i.e. "path/to/zh/view.php". If it is not found as well the original file will be returned.
Qiang Xue committed
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
	 *
	 * If the target and the source language codes are the same,
	 * the original file will be returned.
	 *
	 * @param string $file the original file
	 * @param string $language the target language that the file should be localized to.
	 * If not set, the value of [[\yii\base\Application::language]] will be used.
	 * @param string $sourceLanguage the language that the original file is in.
	 * If not set, the value of [[\yii\base\Application::sourceLanguage]] will be used.
	 * @return string the matching localized file, or the original file if the localized version is not found.
	 * If the target and the source language codes are the same, the original file will be returned.
	 */
	public static function localize($file, $language = null, $sourceLanguage = null)
	{
		if ($language === null) {
Qiang Xue committed
69
			$language = Yii::$app->language;
Qiang Xue committed
70 71
		}
		if ($sourceLanguage === null) {
Qiang Xue committed
72
			$sourceLanguage = Yii::$app->sourceLanguage;
Qiang Xue committed
73 74 75 76
		}
		if ($language === $sourceLanguage) {
			return $file;
		}
77
		$desiredFile = dirname($file) . DIRECTORY_SEPARATOR . $language . DIRECTORY_SEPARATOR . basename($file);
Alexander Makarov committed
78 79 80 81 82 83 84 85 86 87
		if (is_file($desiredFile)) {
			return $desiredFile;
		} else {
			$language = substr($language, 0, 2);
			if ($language === $sourceLanguage) {
				return $file;
			}
			$desiredFile = dirname($file) . DIRECTORY_SEPARATOR . $language . DIRECTORY_SEPARATOR . basename($file);
			return is_file($desiredFile) ? $desiredFile : $file;
		}
Qiang Xue committed
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
	}

	/**
	 * Determines the MIME type of the specified file.
	 * This method will first try to determine the MIME type based on
	 * [finfo_open](http://php.net/manual/en/function.finfo-open.php). If this doesn't work, it will
	 * fall back to [[getMimeTypeByExtension()]].
	 * @param string $file the file name.
	 * @param string $magicFile name of the optional magic database file, usually something like `/path/to/magic.mime`.
	 * This will be passed as the second parameter to [finfo_open](http://php.net/manual/en/function.finfo-open.php).
	 * @param boolean $checkExtension whether to use the file extension to determine the MIME type in case
	 * `finfo_open()` cannot determine it.
	 * @return string the MIME type (e.g. `text/plain`). Null is returned if the MIME type cannot be determined.
	 */
	public static function getMimeType($file, $magicFile = null, $checkExtension = true)
	{
		if (function_exists('finfo_open')) {
			$info = finfo_open(FILEINFO_MIME_TYPE, $magicFile);
106 107
			if ($info) {
				$result = finfo_file($info, $file);
Qiang Xue committed
108
				finfo_close($info);
109 110 111
				if ($result !== false) {
					return $result;
				}
Qiang Xue committed
112 113 114
			}
		}

115
		return $checkExtension ? static::getMimeTypeByExtension($file) : null;
Qiang Xue committed
116 117 118 119 120 121 122 123 124 125 126 127
	}

	/**
	 * Determines the MIME type based on the extension name of the specified file.
	 * This method will use a local map between extension names and MIME types.
	 * @param string $file the file name.
	 * @param string $magicFile the path of the file that contains all available MIME type information.
	 * If this is not set, the default file aliased by `@yii/util/mimeTypes.php` will be used.
	 * @return string the MIME type. Null is returned if the MIME type cannot be determined.
	 */
	public static function getMimeTypeByExtension($file, $magicFile = null)
	{
Alexander Makarov committed
128
		static $mimeTypes = [];
Qiang Xue committed
129
		if ($magicFile === null) {
Qiang Xue committed
130 131 132 133
			$magicFile = __DIR__ . '/mimeTypes.php';
		}
		if (!isset($mimeTypes[$magicFile])) {
			$mimeTypes[$magicFile] = require($magicFile);
Qiang Xue committed
134 135 136
		}
		if (($ext = pathinfo($file, PATHINFO_EXTENSION)) !== '') {
			$ext = strtolower($ext);
Qiang Xue committed
137 138
			if (isset($mimeTypes[$magicFile][$ext])) {
				return $mimeTypes[$magicFile][$ext];
Qiang Xue committed
139 140 141 142 143
			}
		}
		return null;
	}

144 145 146 147 148 149
	/**
	 * Copies a whole directory as another one.
	 * The files and sub-directories will also be copied over.
	 * @param string $src the source directory
	 * @param string $dst the destination directory
	 * @param array $options options for directory copy. Valid options are:
150
	 * @throws \yii\base\InvalidParamException if unable to open directory
151
	 *
152
	 * - dirMode: integer, the permission to be set for newly copied directories. Defaults to 0775.
153
	 * - fileMode:  integer, the permission to be set for newly copied files. Defaults to the current environment setting.
154 155 156 157 158 159 160 161
	 * - filter: callback, a PHP callback that is called for each directory or file.
	 *   The signature of the callback should be: `function ($path)`, where `$path` refers the full path to be filtered.
	 *   The callback can return one of the following values:
	 *
	 *   * true: the directory or file will be copied (the "only" and "except" options will be ignored)
	 *   * false: the directory or file will NOT be copied (the "only" and "except" options will be ignored)
	 *   * null: the "only" and "except" options will determine whether the directory or file should be copied
	 *
162 163 164 165 166 167
	 * - only: array, list of patterns that the file paths should match if they want to be copied.
	 *   A path matches a pattern if it contains the pattern string at its end.
	 *   For example, '.php' matches all file paths ending with '.php'.
	 *   Note, the '/' characters in a pattern matches both '/' and '\' in the paths.
	 *   If a file path matches a pattern in both "only" and "except", it will NOT be copied.
	 * - except: array, list of patterns that the files or directories should match if they want to be excluded from being copied.
168 169 170 171
	 *   A path matches a pattern if it contains the pattern string at its end.
	 *   Patterns ending with '/' apply to directory paths only, and patterns not ending with '/'
	 *   apply to file paths only. For example, '/a/b' matches all file paths ending with '/a/b';
	 *   and '.svn/' matches directory paths ending with '.svn'. Note, the '/' characters in a pattern matches
172
	 *   both '/' and '\' in the paths.
Qiang Xue committed
173
	 * - recursive: boolean, whether the files under the subdirectories should also be copied. Defaults to true.
174
	 * - beforeCopy: callback, a PHP callback that is called before copying each sub-directory or file.
Qiang Xue committed
175
	 *   If the callback returns false, the copy operation for the sub-directory or file will be cancelled.
176 177
	 *   The signature of the callback should be: `function ($from, $to)`, where `$from` is the sub-directory or
	 *   file to be copied from, while `$to` is the copy target.
Qiang Xue committed
178
	 * - afterCopy: callback, a PHP callback that is called after each sub-directory or file is successfully copied.
179
	 *   The signature of the callback should be: `function ($from, $to)`, where `$from` is the sub-directory or
Qiang Xue committed
180
	 *   file copied from, while `$to` is the copy target.
181
	 */
Alexander Makarov committed
182
	public static function copyDirectory($src, $dst, $options = [])
183 184
	{
		if (!is_dir($dst)) {
185
			static::createDirectory($dst, isset($options['dirMode']) ? $options['dirMode'] : 0775, true);
186 187 188
		}

		$handle = opendir($src);
189 190 191
		if ($handle === false) {
			throw new InvalidParamException('Unable to open directory: ' . $src);
		}
192 193 194 195
		while (($file = readdir($handle)) !== false) {
			if ($file === '.' || $file === '..') {
				continue;
			}
196 197
			$from = $src . DIRECTORY_SEPARATOR . $file;
			$to = $dst . DIRECTORY_SEPARATOR . $file;
Qiang Xue committed
198
			if (static::filterPath($from, $options)) {
Qiang Xue committed
199
				if (isset($options['beforeCopy']) && !call_user_func($options['beforeCopy'], $from, $to)) {
Qiang Xue committed
200
					continue;
201
				}
202 203
				if (is_file($from)) {
					copy($from, $to);
204
					if (isset($options['fileMode'])) {
Qiang Xue committed
205
						@chmod($to, $options['fileMode']);
206 207
					}
				} else {
208 209 210 211
					static::copyDirectory($from, $to, $options);
				}
				if (isset($options['afterCopy'])) {
					call_user_func($options['afterCopy'], $from, $to);
212 213 214 215 216
				}
			}
		}
		closedir($handle);
	}
217 218

	/**
Qiang Xue committed
219 220
	 * Removes a directory (and all its content) recursively.
	 * @param string $dir the directory to be deleted recursively.
221
	 */
222
	public static function removeDirectory($dir)
223
	{
Qiang Xue committed
224 225 226 227 228
		if (!is_dir($dir) || !($handle = opendir($dir))) {
			return;
		}
		while (($file = readdir($handle)) !== false) {
			if ($file === '.' || $file === '..') {
229 230
				continue;
			}
Qiang Xue committed
231 232 233
			$path = $dir . DIRECTORY_SEPARATOR . $file;
			if (is_file($path)) {
				unlink($path);
234
			} else {
Qiang Xue committed
235
				static::removeDirectory($path);
236 237
			}
		}
Qiang Xue committed
238 239
		closedir($handle);
		rmdir($dir);
240
	}
241 242 243 244 245

	/**
	 * Returns the files found under the specified directory and subdirectories.
	 * @param string $dir the directory under which the files will be looked for.
	 * @param array $options options for file searching. Valid options are:
Qiang Xue committed
246
	 *
247
	 * - filter: callback, a PHP callback that is called for each directory or file.
Qiang Xue committed
248
	 *   The signature of the callback should be: `function ($path)`, where `$path` refers the full path to be filtered.
249 250 251 252 253 254
	 *   The callback can return one of the following values:
	 *
	 *   * true: the directory or file will be returned (the "only" and "except" options will be ignored)
	 *   * false: the directory or file will NOT be returned (the "only" and "except" options will be ignored)
	 *   * null: the "only" and "except" options will determine whether the directory or file should be returned
	 *
255
	 * - except: array, list of patterns excluding from the results matching file or directory paths.
256 257
	 *   Patterns ending with '/' apply to directory paths only, and patterns not ending with '/'
	 *   apply to file paths only. For example, '/a/b' matches all file paths ending with '/a/b';
258 259 260 261 262 263 264 265 266 267 268 269
	 *   and '.svn/' matches directory paths ending with '.svn'.
	 *   If the pattern does not contain a slash /, it is treated as a shell glob pattern and checked for a match against the pathname relative to $dir.
	 *   Otherwise, the pattern is treated as a shell glob suitable for consumption by fnmatch(3) with the FNM_PATHNAME flag: wildcards in the pattern will not match a / in the pathname.
	 *   For example, "views/*.php" matches "views/index.php" but not "views/controller/index.php".
	 *   A leading slash matches the beginning of the pathname. For example, "/*.php" matches "index.php" but not "views/start/index.php".
	 *   An optional prefix "!" which negates the pattern; any matching file excluded by a previous pattern will become included again.
	 *   If a negated pattern matches, this will override lower precedence patterns sources. Put a backslash ("\") in front of the first "!"
	 *   for patterns that begin with a literal "!", for example, "\!important!.txt".
	 *   Note, the '/' characters in a pattern matches both '/' and '\' in the paths.
	 * - only: array, list of patterns that the file paths should match if they are to be returned. Directory paths are not checked against them.
	 *   Same pattern matching rules as in the "except" option are used.
	 *   If a file path matches a pattern in both "only" and "except", it will NOT be returned.
270
	 * - recursive: boolean, whether the files under the subdirectories should also be looked for. Defaults to true.
271
	 * @return array files found under the directory. The file list is sorted.
272
	 * @throws InvalidParamException if the dir is invalid.
273
	 */
Alexander Makarov committed
274
	public static function findFiles($dir, $options = [])
275
	{
276 277 278
		if (!is_dir($dir)) {
			throw new InvalidParamException('The dir argument must be a directory.');
		}
279
		$dir = rtrim($dir, DIRECTORY_SEPARATOR);
280 281 282 283
		if (!isset($options['basePath'])) {
			$options['basePath'] = realpath($dir);
			// this should also be done only once
			if (isset($options['except'])) {
AlexGx committed
284
				foreach ($options['except'] as $key => $value) {
285
					if (is_string($value)) {
286
						$options['except'][$key] = static::parseExcludePattern($value);
287
					}
288
				}
289 290
			}
			if (isset($options['only'])) {
AlexGx committed
291
				foreach ($options['only'] as $key => $value) {
292
					if (is_string($value)) {
293
						$options['only'][$key] = static::parseExcludePattern($value);
294
					}
295
				}
296 297
			}
		}
Alexander Makarov committed
298
		$list = [];
299
		$handle = opendir($dir);
300 301 302
		if ($handle === false) {
			throw new InvalidParamException('Unable to open directory: ' . $dir);
		}
303 304 305 306 307
		while (($file = readdir($handle)) !== false) {
			if ($file === '.' || $file === '..') {
				continue;
			}
			$path = $dir . DIRECTORY_SEPARATOR . $file;
Qiang Xue committed
308
			if (static::filterPath($path, $options)) {
Qiang Xue committed
309
				if (is_file($path)) {
310
					$list[] = $path;
Qiang Xue committed
311 312
				} elseif (!isset($options['recursive']) || $options['recursive']) {
					$list = array_merge($list, static::findFiles($path, $options));
313 314 315 316 317 318 319 320
				}
			}
		}
		closedir($handle);
		return $list;
	}

	/**
Qiang Xue committed
321 322 323 324 325
	 * Checks if the given file path satisfies the filtering options.
	 * @param string $path the path of the file or directory to be checked
	 * @param array $options the filtering options. See [[findFiles()]] for explanations of
	 * the supported options.
	 * @return boolean whether the file or directory satisfies the filtering options.
326
	 */
Qiang Xue committed
327
	public static function filterPath($path, $options)
328
	{
329 330 331 332 333
		if (isset($options['filter'])) {
			$result = call_user_func($options['filter'], $path);
			if (is_bool($result)) {
				return $result;
			}
334
		}
335 336 337 338 339

		if (empty($options['except']) && empty($options['only'])) {
			return true;
		}

Qiang Xue committed
340
		$path = str_replace('\\', '/', $path);
341

Qiang Xue committed
342
		if (!empty($options['except'])) {
343
			if (($except = self::lastExcludeMatchingFromList($options['basePath'], $path, $options['except'])) !== null) {
344
				return $except['flags'] & self::PATTERN_NEGATIVE;
Qiang Xue committed
345 346
			}
		}
347

348
		if (!is_dir($path) && !empty($options['only'])) {
349
			if (($except = self::lastExcludeMatchingFromList($options['basePath'], $path, $options['only'])) !== null) {
350
				// don't check PATTERN_NEGATIVE since those entries are not prefixed with !
351
				return true;
352
			}
353
			return false;
354
		}
Qiang Xue committed
355
		return true;
356
	}
357 358

	/**
359
	 * Creates a new directory.
Qiang Xue committed
360 361 362 363
	 *
	 * This method is similar to the PHP `mkdir()` function except that
	 * it uses `chmod()` to set the permission of the created directory
	 * in order to avoid the impact of the `umask` setting.
364
	 *
365 366
	 * @param string $path path of the directory to be created.
	 * @param integer $mode the permission to be set for the created directory.
Qiang Xue committed
367 368
	 * @param boolean $recursive whether to create parent directories if they do not exist.
	 * @return boolean whether the directory is created successfully
369
	 */
370
	public static function createDirectory($path, $mode = 0775, $recursive = true)
371
	{
Qiang Xue committed
372 373 374 375 376
		if (is_dir($path)) {
			return true;
		}
		$parentDir = dirname($path);
		if ($recursive && !is_dir($parentDir)) {
377
			static::createDirectory($parentDir, $mode, true);
378 379 380 381 382
		}
		$result = mkdir($path, $mode);
		chmod($path, $mode);
		return $result;
	}
383

384 385 386 387 388 389 390 391 392 393 394 395
	/**
	 * Performs a simple comparison of file or directory names.
	 *
	 * Based on match_basename() from dir.c of git 1.8.5.3 sources.
	 *
	 * @param string $baseName file or directory name to compare with the pattern
	 * @param string $pattern the pattern that $baseName will be compared against
	 * @param integer|boolean $firstWildcard location of first wildcard character in the $pattern
	 * @param integer $flags pattern flags
	 * @return boolean wheter the name matches against pattern
	 */
	private static function matchBasename($baseName, $pattern, $firstWildcard, $flags)
396
	{
397
		if ($firstWildcard === false) {
398 399 400
			if ($pattern === $baseName) {
				return true;
			}
AlexGx committed
401
		} elseif ($flags & self::PATTERN_ENDSWITH) {
402 403 404 405 406 407 408 409 410
			/* "*literal" matching against "fooliteral" */
			$n = StringHelper::byteLength($pattern);
			if (StringHelper::byteSubstr($pattern, 1, $n) === StringHelper::byteSubstr($baseName, -$n, $n)) {
				return true;
			}
		}
		return fnmatch($pattern, $baseName, 0);
	}

411 412 413 414 415 416 417 418 419 420 421 422 423
	/**
	 * Compares a path part against a pattern with optional wildcards.
	 *
	 * Based on match_pathname() from dir.c of git 1.8.5.3 sources.
	 *
	 * @param string $path full path to compare
	 * @param string $basePath base of path that will not be compared
	 * @param string $pattern the pattern that path part will be compared against
	 * @param integer|boolean $firstWildcard location of first wildcard character in the $pattern
	 * @param integer $flags pattern flags
	 * @return boolean wheter the path part matches against pattern
	 */
	private static function matchPathname($path, $basePath, $pattern, $firstWildcard, $flags)
424 425 426 427
	{
		// match with FNM_PATHNAME; the pattern has base implicitly in front of it.
		if (isset($pattern[0]) && $pattern[0] == '/') {
			$pattern = StringHelper::byteSubstr($pattern, 1, StringHelper::byteLength($pattern));
428 429
			if ($firstWildcard !== false && $firstWildcard !== 0) {
				$firstWildcard--;
430 431 432 433 434 435
			}
		}

		$namelen = StringHelper::byteLength($path) - (empty($basePath) ? 0 : StringHelper::byteLength($basePath) + 1);
		$name = StringHelper::byteSubstr($path, -$namelen, $namelen);

436 437 438
		if ($firstWildcard !== 0) {
			if ($firstWildcard === false) {
				$firstWildcard = StringHelper::byteLength($pattern);
439 440
			}
			// if the non-wildcard part is longer than the remaining pathname, surely it cannot match.
441
			if ($firstWildcard > $namelen) {
442 443 444
				return false;
			}

445
			if (strncmp($pattern, $name, $firstWildcard)) {
446 447
				return false;
			}
448 449
			$pattern = StringHelper::byteSubstr($pattern, $firstWildcard, StringHelper::byteLength($pattern));
			$name = StringHelper::byteSubstr($name, $firstWildcard, $namelen);
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471

			// If the whole pattern did not have a wildcard, then our prefix match is all we need; we do not need to call fnmatch at all.
			if (empty($pattern) && empty($name)) {
				return true;
			}
		}

		return fnmatch($pattern, $name, FNM_PATHNAME);
	}

	/**
	 * Scan the given exclude list in reverse to see whether pathname
	 * should be ignored.  The first match (i.e. the last on the list), if
	 * any, determines the fate.  Returns the element which
	 * matched, or null for undecided.
	 *
	 * Based on last_exclude_matching_from_list() from dir.c of git 1.8.5.3 sources.
	 *
	 * @param string $basePath
	 * @param string $path
	 * @param array $excludes list of patterns to match $path against
	 * @return string null or one of $excludes item as an array with keys: 'pattern', 'flags'
472
	 * @throws InvalidParamException if any of the exclude patterns is not a string or an array with keys: pattern, flags, firstWildcard.
473
	 */
474
	private static function lastExcludeMatchingFromList($basePath, $path, $excludes)
475
	{
AlexGx committed
476
		foreach (array_reverse($excludes) as $exclude) {
477 478 479
			if (is_string($exclude)) {
				$exclude = self::parseExcludePattern($exclude);
			}
480 481 482
			if (!isset($exclude['pattern']) || !isset($exclude['flags']) || !isset($exclude['firstWildcard'])) {
				throw new InvalidParamException('If exclude/include pattern is an array it must contain the pattern, flags and firstWildcard keys.');
			}
483
			if ($exclude['flags'] & self::PATTERN_MUSTBEDIR && !is_dir($path)) {
484 485 486
				continue;
			}

487
			if ($exclude['flags'] & self::PATTERN_NODIR) {
488
				if (self::matchBasename(basename($path), $exclude['pattern'], $exclude['firstWildcard'], $exclude['flags'])) {
489 490 491 492 493
					return $exclude;
				}
				continue;
			}

494
			if (self::matchPathname($path, $basePath, $exclude['pattern'], $exclude['firstWildcard'], $exclude['flags'])) {
495 496 497 498 499 500
				return $exclude;
			}
		}
		return null;
	}

501 502 503 504 505 506 507
	/**
	 * Processes the pattern, stripping special characters like / and ! from the beginning and settings flags instead.
	 * @param string $pattern
	 * @return array with keys: (string)pattern, (int)flags, (int|boolean)firstWildcard
	 * @throws InvalidParamException if the pattern is not a string.
	 */
	private static function parseExcludePattern($pattern)
508 509
	{
		if (!is_string($pattern)) {
510
			throw new InvalidParamException('Exclude/include pattern must be a string.');
511
		}
AlexGx committed
512
		$result = [
513 514
			'pattern' => $pattern,
			'flags' => 0,
515
			'firstWildcard' => false,
AlexGx committed
516
		];
517
		if (!isset($pattern[0])) {
518
			return $result;
519
		}
520 521

		if ($pattern[0] == '!') {
522
			$result['flags'] |= self::PATTERN_NEGATIVE;
523 524 525 526 527 528
			$pattern = StringHelper::byteSubstr($pattern, 1, StringHelper::byteLength($pattern));
		}
		$len = StringHelper::byteLength($pattern);
		if ($len && StringHelper::byteSubstr($pattern, -1, 1) == '/') {
			$pattern = StringHelper::byteSubstr($pattern, 0, -1);
			$len--;
529
			$result['flags'] |= self::PATTERN_MUSTBEDIR;
530
		}
531
		if (strpos($pattern, '/') === false) {
532
			$result['flags'] |= self::PATTERN_NODIR;
533
		}
534
		$result['firstWildcard'] = self::firstWildcardInPattern($pattern);
535
		if ($pattern[0] == '*' && self::firstWildcardInPattern(StringHelper::byteSubstr($pattern, 1, StringHelper::byteLength($pattern))) === false) {
536
			$result['flags'] |= self::PATTERN_ENDSWITH;
537
		}
538 539 540 541
		$result['pattern'] = $pattern;
		return $result;
	}

542 543 544 545 546 547
	/**
	 * Searches for the first wildcard character in the pattern.
	 * @param string $pattern the pattern to search in
	 * @return integer|boolean position of first wildcard character or false if not found
	 */
	private static function firstWildcardInPattern($pattern)
548
	{
AlexGx committed
549
		$wildcards = ['*', '?', '[', '\\'];
550
		$wildcardSearch = function ($r, $c) use ($pattern) {
551 552 553 554 555
			$p = strpos($pattern, $c);
			return $r===false ? $p : ($p===false ? $r : min($r, $p));
		};
		return array_reduce($wildcards, $wildcardSearch, false);
	}
Zander Baldwin committed
556
}