summaryrefslogtreecommitdiff
path: root/lib/Minz/ModelArray.php
diff options
context:
space:
mode:
authorGravatar Marien Fressinaud <dev@marienfressinaud.fr> 2014-01-29 21:26:19 +0100
committerGravatar Marien Fressinaud <dev@marienfressinaud.fr> 2014-01-29 21:26:19 +0100
commit165eb57459a152b3cc6aa3fd15ca990c3d908829 (patch)
tree640ddacbc6eabc985646dd65b0578f369ea92321 /lib/Minz/ModelArray.php
parent75096e6a39fe5d34d3951991f296f616e62a9fd8 (diff)
parentc053825ff8f9792e692c101585481129b006937b (diff)
Sortie de la version 0.70.7.0
Diffstat (limited to 'lib/Minz/ModelArray.php')
-rw-r--r--lib/Minz/ModelArray.php81
1 files changed, 81 insertions, 0 deletions
diff --git a/lib/Minz/ModelArray.php b/lib/Minz/ModelArray.php
new file mode 100644
index 000000000..ff23dbc83
--- /dev/null
+++ b/lib/Minz/ModelArray.php
@@ -0,0 +1,81 @@
+<?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 {
+ /**
+ * $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;
+ }
+
+ protected function loadArray() {
+ 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 {
+ $data = include($this->filename);
+ $this->releaseLock($handle);
+
+ if ($data === false) {
+ throw new Minz_PermissionDeniedException($this->filename);
+ } elseif (!is_array($data)) {
+ $data = array();
+ }
+ return $data;
+ }
+ }
+
+ /**
+ * Sauve le tableau $array dans le fichier $filename
+ **/
+ protected function writeArray($array) {
+ if (file_put_contents($this->filename, "<?php\n return " . var_export($array, true) . ';', LOCK_EX) === false) {
+ throw new Minz_PermissionDeniedException($this->filename);
+ }
+ if (function_exists('opcache_invalidate')) {
+ opcache_invalidate($this->filename); //Clear PHP 5.5+ cache for include
+ }
+ return true;
+ }
+
+ 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);
+ }
+}