ModelArray.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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 = array();
  37. }
  38. }
  39. }
  40. /**
  41. * Sauve le tableau $array dans le fichier $filename
  42. **/
  43. protected function writeFile() {
  44. if (!file_put_contents($this->filename, "<?php\n return " . var_export($this->array, true) . ';', LOCK_EX)) {
  45. throw new Minz_PermissionDeniedException($this->filename);
  46. }
  47. return true;
  48. }
  49. private function getLock() {
  50. $handle = fopen($this->filename, 'r');
  51. if ($handle === false) {
  52. return false;
  53. }
  54. $count = 50;
  55. while (!flock($handle, LOCK_SH) && $count > 0) {
  56. $count--;
  57. usleep(1000);
  58. }
  59. if ($count > 0) {
  60. return $handle;
  61. } else {
  62. fclose($handle);
  63. return false;
  64. }
  65. }
  66. private function releaseLock($handle) {
  67. flock($handle, LOCK_UN);
  68. fclose($handle);
  69. }
  70. }