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

TextFileValidator   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 71
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 33.33%

Importance

Changes 5
Bugs 1 Features 0
Metric Value
wmc 8
c 5
b 1
f 0
lcom 1
cbo 3
dl 0
loc 71
ccs 7
cts 21
cp 0.3333
rs 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
A validateFileLocation() 0 6 2
A validateFileContent() 0 8 2
A getFileLocation() 0 4 1
A getFileContentErrorMessage() 0 4 1
A __construct() 0 4 1
A validate() 0 6 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