Completed
Push — master ( 5d9942...f2e7a7 )
by Victor
01:48
created

TextFileValidator::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
/**
3
 * Created with PHP 5.6 generator
4
 * User: 
5
 * PHP 5.6 generator created by Victor MECH - April 2016
6
*/
7
8
namespace LazyEight\DiTesto;
9
10
11
use LazyEight\DiTesto\Exceptions\InvalidFileLocationException;
12
use LazyEight\DiTesto\Exceptions\InvalidFileTypeException;
13
use LazyEight\DiTesto\ValueObject\FileLocation;
14
15
class TextFileValidator
16
{
17
    /**
18
     * @var FileLocation
19
     */
20
    protected $location;
21
22
    /**
23
     * @var string
24
     */
25
    private $allowedMimeType = 'text/plain';
26
27
    /**
28
     * @param FileLocation $location
29
     */
30 1
    public function __construct(FileLocation $location)
31
    {
32 1
        $this->location = $location;
33 1
    }
34
	
35
    /**
36
     * @throws InvalidFileLocationException
37
     * @throws InvalidFileTypeException
38
     * @return bool
39
     */
40 3
    public function validate()
41
    {
42 3
        $this->validateFileLocation();
43 2
        $this->validateFileContent();
44 1
        return true;
45
    }
46
47
    /**
48
     * @throws InvalidFileLocationException If file not exists
49
     */
50
    protected function validateFileLocation()
51
    {
52
        if (!file_exists($this->location->getValue())) {
53
            throw new InvalidFileLocationException('File not exists!', 101);
54
        }
55
    }
56
57
    /**
58
     * @throws InvalidFileTypeException
59
     */
60
    protected function validateFileContent()
61
    {
62
        $fileInfo = finfo_open(FILEINFO_MIME_TYPE);
63
        $rawInfo = finfo_file($fileInfo, $this->location->getValue());
64
        if ($rawInfo !== $this->allowedMimeType) {
65
            throw new InvalidFileTypeException($this->getFileContentErrorMessage($rawInfo));
66
        }
67
    }
68
	
69
    /**
70
     * @return FileLocation
71
     */
72
    public function getFileLocation()
73
    {
74
        return clone $this->location;
75
    }
76
77
    /**
78
     * @param $rawInfo object created by finfo_file function
79
     * @return string Error message for when the things going wrong with the mimeType of the file
80
     */
81
    protected function getFileContentErrorMessage($rawInfo)
82
    {
83
        return 'Invalid file type. Found '. $rawInfo . ' when ' .$this->allowedMimeType . ' was expected';
84
    }
85
}
86