4
0

ModelArray.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. }
  26. elseif (($handle = $this->getLock()) === false) {
  27. throw new Minz_PermissionDeniedException($this->filename);
  28. } else {
  29. $data = include($this->filename);
  30. $this->releaseLock($handle);
  31. if ($data === false) {
  32. throw new Minz_PermissionDeniedException($this->filename);
  33. } elseif (!is_array($data)) {
  34. $data = array();
  35. }
  36. return $data;
  37. }
  38. }
  39. /**
  40. * Sauve le tableau $array dans le fichier $filename
  41. **/
  42. protected function writeArray($array) {
  43. if (file_put_contents($this->filename, "<?php\n return " . var_export($array, true) . ';', LOCK_EX) === false) {
  44. throw new Minz_PermissionDeniedException($this->filename);
  45. }
  46. if (function_exists('opcache_invalidate')) {
  47. opcache_invalidate($this->filename); //Clear PHP 5.5+ cache for include
  48. }
  49. return true;
  50. }
  51. private function getLock() {
  52. $handle = fopen($this->filename, 'r');
  53. if ($handle === false) {
  54. return false;
  55. }
  56. $count = 50;
  57. while (!flock($handle, LOCK_SH) && $count > 0) {
  58. $count--;
  59. usleep(1000);
  60. }
  61. if ($count > 0) {
  62. return $handle;
  63. } else {
  64. fclose($handle);
  65. return false;
  66. }
  67. }
  68. private function releaseLock($handle) {
  69. flock($handle, LOCK_UN);
  70. fclose($handle);
  71. }
  72. }