Completed
Push — develop ( 5e03e2...c8a8fd )
by Adrien
28:49
created

File::fileExists()   B

Complexity

Conditions 3
Paths 3

Size

Total Lines 25
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 3.0052

Importance

Changes 0
Metric Value
cc 3
eloc 14
c 0
b 0
f 0
nc 3
nop 1
dl 0
loc 25
ccs 11
cts 12
cp 0.9167
crap 3.0052
rs 8.8571
1
<?php
2
3
namespace PhpOffice\PhpSpreadsheet\Shared;
4
5
/**
6
 * Copyright (c) 2006 - 2016 PhpSpreadsheet
7
 *
8
 * This library is free software; you can redistribute it and/or
9
 * modify it under the terms of the GNU Lesser General Public
10
 * License as published by the Free Software Foundation; either
11
 * version 2.1 of the License, or (at your option) any later version.
12
 *
13
 * This library is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16
 * Lesser General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU Lesser General Public
19
 * License along with this library; if not, write to the Free Software
20
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
21
 *
22
 * @category   PhpSpreadsheet
23
 * @copyright  Copyright (c) 2006 - 2016 PhpSpreadsheet (https://github.com/PHPOffice/PhpSpreadsheet)
24
 * @license    http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt    LGPL
25
 */
26
class File
27
{
28
    /*
29
     * Use Temp or File Upload Temp for temporary files
30
     *
31
     * @protected
32
     * @var    boolean
33
     */
34
35
    protected static $useUploadTempDirectory = false;
36
37
    /**
38
     * Set the flag indicating whether the File Upload Temp directory should be used for temporary files
39
     *
40
     * @param     bool    $useUploadTempDir        Use File Upload Temporary directory (true or false)
41
     */
42 1
    public static function setUseUploadTempDirectory($useUploadTempDir = false)
43
    {
44 1
        self::$useUploadTempDirectory = (boolean) $useUploadTempDir;
45 1
    }
46
47
    /**
48
     * Get the flag indicating whether the File Upload Temp directory should be used for temporary files
49
     *
50
     * @return     bool    Use File Upload Temporary directory (true or false)
51
     */
52 2
    public static function getUseUploadTempDirectory()
53
    {
54 2
        return self::$useUploadTempDirectory;
55
    }
56
57
    /**
58
     * Verify if a file exists
59
     *
60
     * @param     string    $pFilename    Filename
61
     * @return bool
62
     */
63 7
    public static function fileExists($pFilename)
64
    {
65
        // Sick construction, but it seems that
66
        // file_exists returns strange values when
67
        // doing the original file_exists on ZIP archives...
68 7
        if (strtolower(substr($pFilename, 0, 3)) == 'zip') {
69
            // Open ZIP file and verify if the file exists
70 2
            $zipFile = substr($pFilename, 6, strpos($pFilename, '#') - 6);
71 2
            $archiveFile = substr($pFilename, strpos($pFilename, '#') + 1);
72
73 2
            $zipClass = \PhpOffice\PhpSpreadsheet\Settings::getZipClass();
74 2
            $zip = new $zipClass();
75 2
            if ($zip->open($zipFile) === true) {
76 2
                $returnValue = ($zip->getFromName($archiveFile) !== false);
77 2
                $zip->close();
78
79 2
                return $returnValue;
80
            } else {
81
                return false;
82
            }
83
        } else {
84
            // Regular file_exists
85 6
            return file_exists($pFilename);
86
        }
87
    }
88
89
    /**
90
     * Returns canonicalized absolute pathname, also for ZIP archives
91
     *
92
     * @param string $pFilename
93
     * @return string
94
     */
95 10
    public static function realpath($pFilename)
96
    {
97
        // Returnvalue
98 10
        $returnValue = '';
99
100
        // Try using realpath()
0 ignored issues
show
Unused Code Comprehensibility introduced by
38% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
101 10
        if (file_exists($pFilename)) {
102 4
            $returnValue = realpath($pFilename);
103
        }
104
105
        // Found something?
106 10
        if ($returnValue == '' || ($returnValue === null)) {
107 10
            $pathArray = explode('/', $pFilename);
108 10
            while (in_array('..', $pathArray) && $pathArray[0] != '..') {
109 2
                for ($i = 0; $i < count($pathArray); ++$i) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
110 2
                    if ($pathArray[$i] == '..' && $i > 0) {
111 2
                        unset($pathArray[$i]);
112 2
                        unset($pathArray[$i - 1]);
113 2
                        break;
114
                    }
115
                }
116
            }
117 10
            $returnValue = implode('/', $pathArray);
118
        }
119
120
        // Return
121 10
        return $returnValue;
122
    }
123
124
    /**
125
     * Get the systems temporary directory.
126
     *
127
     * @return string
128
     */
129 40
    public static function sysGetTempDir()
130
    {
131 40
        if (self::$useUploadTempDirectory) {
132
            //  use upload-directory when defined to allow running on environments having very restricted
133
            //      open_basedir configs
134
            if (ini_get('upload_tmp_dir') !== false) {
135
                if ($temp = ini_get('upload_tmp_dir')) {
136
                    if (file_exists($temp)) {
137
                        return realpath($temp);
138
                    }
139
                }
140
            }
141
        }
142
143
        // sys_get_temp_dir is only available since PHP 5.2.1
144
        // http://php.net/manual/en/function.sys-get-temp-dir.php#94119
145 40
        if (!function_exists('sys_get_temp_dir')) {
146 View Code Duplication
            if ($temp = getenv('TMP')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
147
                if ((!empty($temp)) && (file_exists($temp))) {
148
                    return realpath($temp);
149
                }
150
            }
151 View Code Duplication
            if ($temp = getenv('TEMP')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
152
                if ((!empty($temp)) && (file_exists($temp))) {
153
                    return realpath($temp);
154
                }
155
            }
156 View Code Duplication
            if ($temp = getenv('TMPDIR')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
157
                if ((!empty($temp)) && (file_exists($temp))) {
158
                    return realpath($temp);
159
                }
160
            }
161
162
            // trick for creating a file in system's temporary dir
163
            // without knowing the path of the system's temporary dir
164
            $temp = tempnam(__FILE__, '');
165
            if (file_exists($temp)) {
166
                unlink($temp);
167
168
                return realpath(dirname($temp));
169
            }
170
171
            return null;
172
        }
173
174
        // use ordinary built-in PHP function
175
        //    There should be no problem with the 5.2.4 Suhosin realpath() bug, because this line should only
176
        //        be called if we're running 5.2.1 or earlier
177 40
        return realpath(sys_get_temp_dir());
178
    }
179
180
    /**
181
     * Assert that given path is an existing file and is readable, otherwise throw exception
182
     * @param string $filename
183
     * @throws \InvalidArgumentException
184
     */
185 27
    public static function assertFile($filename)
186
    {
187 27
        if (!is_file($filename)) {
188 2
            throw new \InvalidArgumentException('File "' . $filename . '" does not exist.');
189
        }
190
191 25
        if (!is_readable($filename)) {
192
            throw new \InvalidArgumentException('Could not open "' . $filename . '" for reading.');
193
        }
194 25
    }
195
}
196