FileNameValidationTrait::validateFileNamePath()   A
last analyzed

Complexity

Conditions 6
Paths 4

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 6
c 1
b 0
f 0
dl 0
loc 13
ccs 7
cts 7
cp 1
rs 9.2222
cc 6
nc 4
nop 1
crap 6
1
<?php
2
3
/**
4
 * Trait implementation of file name and path validation methods.
5
 */
6
7
namespace CryptoManana\Core\Traits\CommonValidations;
8
9
use CryptoManana\Core\StringBuilder as StringBuilder;
10
11
/**
12
 * Trait FileNameValidationTrait - Reusable implementation of file name and path validations.
13
 *
14
 * @package CryptoManana\Core\Traits\CommonValidations
15
 */
16
trait FileNameValidationTrait
17
{
18
    /**
19
     * Internal method for location and filename validation.
20
     *
21
     * @param string $filename The filename and location.
22
     *
23
     * @throws \Exception Validation errors.
24
     */
25 118
    protected function validateFileNamePath($filename)
26
    {
27 118
        $filename = StringBuilder::stringReplace("\0", '', $filename); // (ASCII 0 (0x00))
28 118
        $filename = realpath($filename); // Path traversal escape and absolute path fetching
29
30
        // Clear path cache
31 118
        if (!empty($filename)) {
32 50
            clearstatcache(true, $filename);
33
        }
34
35
        // Check if path is valid and the file is readable
36 118
        if ($filename === false || !file_exists($filename) || !is_readable($filename) || !is_file($filename)) {
37 68
            throw new \RuntimeException('File is not found or can not be accessed.');
38
        }
39
    }
40
}
41