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. * $filename est le nom du fichier
  12. */
  13. protected $filename;
  14. /**
  15. * Ouvre le fichier indiqué, charge le tableau dans $array et le $filename
  16. * @param $filename le nom du fichier à ouvrir contenant un tableau
  17. * Remarque : $array sera obligatoirement un tableau
  18. */
  19. public function __construct ($filename) {
  20. $this->filename = $filename;
  21. }
  22. protected function loadArray() {
  23. if (!file_exists($this->filename)) {
  24. throw new Minz_FileNotExistException($this->filename, Minz_Exception::WARNING);
  25. } elseif (($handle = $this->getLock()) === false) {
  26. throw new Minz_PermissionDeniedException($this->filename);
  27. } else {
  28. $data = include($this->filename);
  29. $this->releaseLock($handle);
  30. if ($data === false) {
  31. throw new Minz_PermissionDeniedException($this->filename);
  32. } elseif (!is_array($data)) {
  33. $data = array();
  34. }
  35. return $data;
  36. }
  37. }
  38. /**
  39. * Sauve le tableau $array dans le fichier $filename
  40. **/
  41. protected function writeArray($array) {
  42. if (file_put_contents($this->filename, "<?php\n return " . var_export($array, true) . ';', LOCK_EX) === false) {
  43. throw new Minz_PermissionDeniedException($this->filename);
  44. }
  45. if (function_exists('opcache_invalidate')) {
  46. opcache_invalidate($this->filename); //Clear PHP cache for include
  47. }
  48. return true;
  49. }
  50. private function getLock() {
  51. $handle = fopen($this->filename, 'r');
  52. if ($handle === false) {
  53. return false;
  54. }
  55. $count = 50;
  56. while (!flock($handle, LOCK_SH) && $count > 0) {
  57. $count--;
  58. usleep(1000);
  59. }
  60. if ($count > 0) {
  61. return $handle;
  62. } else {
  63. fclose($handle);
  64. return false;
  65. }
  66. }
  67. private function releaseLock($handle) {
  68. flock($handle, LOCK_UN);
  69. fclose($handle);
  70. }
  71. }