ModelArray.php 2.3 KB

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