|
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
|
|
|
|