1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace cyberinferno\Cabal\Helpers\FileSystem; |
4
|
|
|
|
5
|
|
|
use cyberinferno\Cabal\Helpers\Exceptions\FileBadFormatException; |
6
|
|
|
use cyberinferno\Cabal\Helpers\Exceptions\FileNotFoundException; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* Class File |
10
|
|
|
* |
11
|
|
|
* Base class for all file system classes. Has basic file loading and validating methods |
12
|
|
|
* |
13
|
|
|
* @package cyberinferno\Cabal\Helpers\FileSystem |
14
|
|
|
* @author Karthik P |
15
|
|
|
*/ |
16
|
|
|
abstract class File |
17
|
|
|
{ |
18
|
|
|
protected $_filePath; |
19
|
|
|
protected $_fileContents; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* File constructor. |
23
|
|
|
* @param string $filePath |
24
|
|
|
* @throws FileBadFormatException |
25
|
|
|
* @throws FileNotFoundException |
26
|
|
|
*/ |
27
|
|
|
public function __construct($filePath) |
28
|
|
|
{ |
29
|
|
|
$this->_filePath = $filePath; |
30
|
|
|
$this->validateFileExists(); |
31
|
|
|
$this->validateFormat(); |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* Checks whether the specified file exists |
36
|
|
|
* |
37
|
|
|
* @throws FileNotFoundException |
38
|
|
|
*/ |
39
|
|
|
protected function validateFileExists() |
40
|
|
|
{ |
41
|
|
|
if (file_exists($this->_filePath) === false) { |
42
|
|
|
throw new FileNotFoundException(); |
43
|
|
|
} |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* Checks whether the specified file isn't empty |
48
|
|
|
* |
49
|
|
|
* @throws FileBadFormatException |
50
|
|
|
*/ |
51
|
|
|
protected function validateFormat() |
52
|
|
|
{ |
53
|
|
|
if (filesize($this->_filePath) == 0 || $this->getFileContents() === null) { |
54
|
|
|
throw new FileBadFormatException(); |
55
|
|
|
} |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* Loads the file contents if not already loaded and returns the same |
60
|
|
|
* |
61
|
|
|
* @return null|string |
62
|
|
|
*/ |
63
|
|
|
public function getFileContents() |
64
|
|
|
{ |
65
|
|
|
if (isset($this->_fileContents) === false) { |
66
|
|
|
$this->_fileContents = file_get_contents($this->_filePath); |
67
|
|
|
} |
68
|
|
|
return $this->_fileContents; |
69
|
|
|
} |
70
|
|
|
} |