blob: bf2c4cb40d00398686e918f1ba7cf7626fd09be6 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
|
<?php
/**
* MINZ - Copyright 2011 Marien Fressinaud
* Sous licence AGPL3 <http://www.gnu.org/licenses/>
*/
/**
* La classe Model_array représente le modèle interragissant avec les fichiers de type texte gérant des tableaux php
*/
class Minz_ModelArray {
/**
* $array Le tableau php contenu dans le fichier $filename
*/
protected $array = array ();
/**
* $filename est le nom du fichier
*/
protected $filename;
/**
* Ouvre le fichier indiqué, charge le tableau dans $array et le $filename
* @param $filename le nom du fichier à ouvrir contenant un tableau
* Remarque : $array sera obligatoirement un tableau
*/
public function __construct ($filename) {
$this->filename = $filename;
if (!file_exists($this->filename)) {
throw new Minz_FileNotExistException($this->filename, Minz_Exception::WARNING);
}
elseif (($handle = $this->getLock()) === false) {
throw new Minz_PermissionDeniedException($this->filename);
} else {
$this->array = include($this->filename);
$this->releaseLock($handle);
if ($this->array === false) {
throw new Minz_PermissionDeniedException($this->filename);
} elseif (is_array($this->array)) {
$this->array = $this->decodeArray($this->array);
} else {
$this->array = array ();
}
}
}
/**
* Sauve le tableau $array dans le fichier $filename
**/
protected function writeFile() {
if (!file_put_contents($this->filename, "<?php\n return " . var_export($this->array, true) . ';', LOCK_EX)) {
throw new Minz_PermissionDeniedException($this->filename);
}
return true;
}
//TODO: check if still useful, and if yes, use a native function such as array_map
private function decodeArray ($array) {
$new_array = array ();
foreach ($array as $key => $value) {
if (is_array ($value)) {
$new_array[$key] = $this->decodeArray ($value);
} else {
$new_array[$key] = stripslashes ($value);
}
}
return $new_array;
}
private function getLock() {
$handle = fopen($this->filename, 'r');
if ($handle === false) {
return false;
}
$count = 50;
while (!flock($handle, LOCK_SH) && $count > 0) {
$count--;
usleep(1000);
}
if ($count > 0) {
return $handle;
} else {
fclose($handle);
return false;
}
}
private function releaseLock($handle) {
flock($handle, LOCK_UN);
fclose($handle);
}
}
|