Completed
Push — master ( b30e53...9fbf6c )
by Victor
01:55
created

AbstractTextFileValidator::validateFileLocation()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 1 Features 1
Metric Value
c 1
b 1
f 1
dl 0
loc 6
ccs 0
cts 4
cp 0
rs 9.4285
cc 2
eloc 3
nc 2
nop 0
crap 6
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: victor
5
 * Date: 10/04/16
6
 * Time: 23:42
7
 */
8
9
namespace LazyEight\DiTesto\Validator;
10
11
12
use LazyEight\DiTesto\Exceptions\InvalidFileLocationException;
13
use LazyEight\DiTesto\Exceptions\InvalidFileTypeException;
14
use LazyEight\DiTesto\ValueObject\FileLocation;
15
16
abstract class AbstractTextFileValidator
17
{
18
    /**
19
     * @var string
20
     */
21
    private $allowedMimeType = 'text/plain';
22
23
    /**
24
     * @return bool
25
     */
26
    abstract public function validate();
27
28
    /**
29
     * @throws InvalidFileLocationException If file not exists
30
     */
31
    protected function validateFileLocation()
32
    {
33
        if (!file_exists($this->getFileLocation()->getValue())) {
34
            throw new InvalidFileLocationException('File not exists!', 101);
35
        }
36
    }
37
38
    /**
39
     * @throws InvalidFileTypeException
40
     */
41
    protected function validateFileContent()
42
    {
43
        $fileInfo = finfo_open(FILEINFO_MIME_TYPE);
44
        $rawInfo = finfo_file($fileInfo, $this->getFileLocation()->getValue());
45
        if ($rawInfo !== $this->allowedMimeType) {
46
            throw new InvalidFileTypeException($this->getFileContentErrorMessage($rawInfo), 102);
47
        }
48
    }
49
50
    /**
51
     * @return FileLocation
52
     */
53
    abstract protected function getFileLocation();
54
55
    /**
56
     * @param $rawInfo object created by finfo_file function
57
     * @return string Error message for when the things going wrong with the mimeType of the file
58
     */
59
    protected function getFileContentErrorMessage($rawInfo)
60
    {
61
        return 'Invalid file type. Found '. $rawInfo . ' when ' .$this->allowedMimeType . ' was expected';
62
    }
63
}