Completed
Push — master ( a2c400...8a7993 )
by Nikola
09:09
created

Filename   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 8
c 1
b 0
f 0
lcom 0
cbo 0
dl 0
loc 53
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 1 1
A sanitize() 0 8 2
A temporaryFile() 0 10 2
A temporaryFilename() 0 10 3
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
    public static function sanitize($filename)
26
    {
27
        if (function_exists('mb_ereg_replace')) {
28
            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
    public static function temporaryFile($filename)
41
    {
42
        $temporaryFile = self::temporaryFilename($filename);
43
44
        if (touch($temporaryFile) === false) {
45
            throw new \RuntimeException(sprintf('Unable to create temporary file %s.', $filename));
46
        }
47
48
        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
    public static function temporaryFilename($filename)
58
    {
59
        $tmp = tempnam(sys_get_temp_dir(), '');
60
61
        if (unlink($tmp) === false || mkdir($tmp) === false) {
62
            throw new \RuntimeException(sprintf('Unable to create temporary file %s.', $filename));
63
        }
64
65
        return $tmp . DIRECTORY_SEPARATOR . self::sanitize($filename);
66
    }
67
}
68