Filename::sanitize()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.0625

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 3
cts 4
cp 0.75
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 1
crap 2.0625
1
<?php
2
/*
3
 * This file is part of the Backup package, an RunOpenCode project.
4
 *
5
 * (c) 2015 RunOpenCode
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 *
10
 * This project is fork of "kbond/php-backup", for full credits info, please
11
 * view CREDITS file that was distributed with this source code.
12
 */
13
namespace RunOpenCode\Backup\Utils;
14
15
final class Filename
16
{
17
    private function __construct() { }
18
19
    /**
20
     * Sanitize filename.
21
     *
22
     * @param string $filename Filename to sanitize.
23
     * @return string Sanitized filename
24
     */
25 72
    public static function sanitize($filename)
26
    {
27 72
        if (function_exists('mb_ereg_replace')) {
28 72
            return mb_ereg_replace("([\.]{2,})", '', mb_ereg_replace("([^\w\s\d\-_~\[\]\(\).])", '', $filename));
29
        } else {
30
            return preg_replace("/([\.]{2,})/", '', preg_replace("/([^\w\s\d\-_~\[\]\(\).])/", '', $filename));
31
        }
32
    }
33
34
    /**
35
     * Create unique temporary file with given filename in system's temporary directory.
36
     *
37
     * @param string $filename Filename of temporary file.
38
     * @return string Absolute path to created temporary file.
39
     */
40 4
    public static function temporaryFile($filename)
41
    {
42 4
        $temporaryFile = self::temporaryFilename($filename);
43
44 4
        if (touch($temporaryFile) === false) {
45
            throw new \RuntimeException(sprintf('Unable to create temporary file %s.', $filename));
46
        }
47
48 4
        return $temporaryFile;
49
    }
50
51
    /**
52
     * Create temporary filename with given filename with path in system's temporary directory.
53
     *
54
     * @param string $filename Filename of temporary file.
55
     * @return string Generated absolute path to unique temporary file.
56
     */
57 16
    public static function temporaryFilename($filename)
58
    {
59 16
        $tmp = tempnam(sys_get_temp_dir(), '');
60
61 16
        if (unlink($tmp) === false || mkdir($tmp) === false) {
62
            throw new \RuntimeException(sprintf('Unable to create temporary file %s.', $filename));
63
        }
64
65 16
        return $tmp . DIRECTORY_SEPARATOR . self::sanitize($filename);
66
    }
67
}
68