1 | <?php |
||
15 | class File extends AllKeysList { |
||
16 | |||
17 | protected $filePath; |
||
18 | protected $fileHandler; |
||
19 | |||
20 | /** |
||
21 | * @param string $filePath Writable path for postponed data storage (should not be under DOCUMENT_ROOT) |
||
22 | * @param bool $validatePathNotUnderDocRoot Throw \Exception if $filePath is not under DOCUMENT_ROOT |
||
23 | * @throws \Exception |
||
24 | */ |
||
25 | 5 | public function __construct($filePath, $validatePathNotUnderDocRoot = true) { |
|
26 | 5 | if(!file_exists($filePath)) { |
|
27 | 5 | if(file_put_contents($filePath, '') === false) { |
|
28 | throw new \Exception('Unable to write file ' . $filePath); |
||
29 | } |
||
30 | } |
||
31 | 5 | $this->filePath = realpath($filePath); |
|
32 | |||
33 | 5 | if($validatePathNotUnderDocRoot && $this->isPathUnderDocRoot()) { |
|
34 | 1 | throw new \Exception('Path ' . $this->filePath . ' is under DOCUMENT_ROOT. It\'s insecure!'); |
|
35 | } |
||
36 | 5 | } |
|
37 | |||
38 | 2 | protected function isPathUnderDocRoot() { |
|
41 | |||
42 | 3 | protected function initFileHandler() { |
|
43 | 3 | $this->fileHandler = fopen($this->filePath, 'a+b'); |
|
44 | 3 | if(!$this->fileHandler) { |
|
45 | throw new \Exception('Unable to read/write file ' . $this->filePath); |
||
46 | } |
||
47 | 3 | while(!flock($this->fileHandler, LOCK_EX | LOCK_NB)) { |
|
48 | usleep(10000); |
||
49 | } |
||
50 | 3 | fseek($this->fileHandler, 0); |
|
51 | 3 | } |
|
52 | |||
53 | /** |
||
54 | * @throws \Exception |
||
55 | * @return array |
||
56 | */ |
||
57 | 3 | protected function getKeysData() { |
|
60 | |||
61 | /** |
||
62 | * @param array $keysData |
||
63 | */ |
||
64 | 3 | protected function saveKeysData(array $keysData) { |
|
68 | |||
69 | 4 | protected function closeFileHandler() { |
|
70 | 4 | if($this->fileHandler) { |
|
71 | 3 | flock($this->fileHandler, LOCK_UN); |
|
72 | 3 | fclose($this->fileHandler); |
|
73 | 3 | $this->fileHandler = null; |
|
74 | } |
||
75 | 4 | } |
|
76 | |||
77 | 3 | public function pop($key) { |
|
83 | |||
84 | 3 | public function push($key, $data) { |
|
89 | |||
90 | 1 | public function __destruct() { |
|
93 | } |
||
94 |
Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable: