PathAssertionsTrait::ensureFileReadable()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 5
dl 0
loc 7
ccs 5
cts 5
cp 1
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 2
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
/**
6
 * @see       https://github.com/soluble-io/soluble-mediatools for the canonical repository
7
 *
8
 * @copyright Copyright (c) 2018-2020 Sébastien Vanvelthem. (https://github.com/belgattitude)
9
 * @license   https://github.com/soluble-io/soluble-mediatools/blob/master/LICENSE.md MIT
10
 */
11
12
namespace Soluble\MediaTools\Common\Assert;
13
14
use Soluble\MediaTools\Common\Exception\FileEmptyException;
15
use Soluble\MediaTools\Common\Exception\FileNotFoundException;
16
use Soluble\MediaTools\Common\Exception\FileNotReadableException;
17
18
trait PathAssertionsTrait
19
{
20
    /**
21
     * @param bool $ensureFileNotEmpty check also filesize to be greater than 0
22
     *
23
     * @throws FileNotFoundException
24
     * @throws FileEmptyException    if $ensureFileNotEmpty is true
25
     */
26 47
    private function ensureFileExists(string $file, bool $ensureFileNotEmpty = false): void
27
    {
28 47
        if (!file_exists($file)) {
29 11
            throw new FileNotFoundException(sprintf('File "%s" does not exists', $file));
30
        }
31 36
        if (!is_file($file)) {
32 1
            throw new FileNotFoundException(sprintf(
33 1
                'File "%s" is not a regular file (%s)',
34
                $file,
35 1
                is_dir($file) ? 'directory' : 'unknow type'
36
            ));
37
        }
38
39 35
        if ($ensureFileNotEmpty && filesize($file) === 0) {
40 1
            throw new FileEmptyException(sprintf('File "%s" is empty', $file));
41
        }
42 34
    }
43
44
    /**
45
     * @param bool $ensureFileNotEmpty check also filesize to be greater than 0
46
     *
47
     * @throws FileNotReadableException
48
     * @throws FileNotFoundException
49
     * @throws FileEmptyException       if $ensureFileNotEmpty is true
50
     */
51 44
    private function ensureFileReadable(string $file, bool $ensureFileNotEmpty = false): void
52
    {
53 44
        $this->ensureFileExists($file, $ensureFileNotEmpty);
54 33
        if (!is_readable($file)) {
55 1
            throw new FileNotReadableException(sprintf(
56 1
                'File "%s" is not readable',
57
                $file
58
            ));
59
        }
60 32
    }
61
}
62