ModelArray.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * MINZ - Copyright 2011 Marien Fressinaud
  5. * Sous licence AGPL3 <http://www.gnu.org/licenses/>
  6. */
  7. /**
  8. * The Minz_ModelArray class is the model to interact with text files containing a PHP array
  9. */
  10. class Minz_ModelArray {
  11. /**
  12. * $filename est le nom du fichier
  13. */
  14. protected string $filename;
  15. /**
  16. * Ouvre le fichier indiqué, charge le tableau dans $array et le $filename
  17. * @param string $filename le nom du fichier à ouvrir contenant un tableau
  18. * Remarque : $array sera obligatoirement un tableau
  19. */
  20. public function __construct(string $filename) {
  21. $this->filename = $filename;
  22. }
  23. /**
  24. * @return array<string,mixed>
  25. * @throws Minz_FileNotExistException
  26. * @throws Minz_PermissionDeniedException
  27. */
  28. protected function loadArray(): array {
  29. if (!file_exists($this->filename)) {
  30. throw new Minz_FileNotExistException($this->filename, Minz_Exception::WARNING);
  31. } elseif (($handle = $this->getLock()) === false) {
  32. throw new Minz_PermissionDeniedException($this->filename);
  33. } else {
  34. $data = include($this->filename);
  35. $this->releaseLock($handle);
  36. if ($data === false) {
  37. throw new Minz_PermissionDeniedException($this->filename);
  38. } elseif (!is_array($data)) {
  39. $data = array();
  40. }
  41. return $data;
  42. }
  43. }
  44. /**
  45. * Sauve le tableau $array dans le fichier $filename
  46. * @param array<string,mixed> $array
  47. * @throws Minz_PermissionDeniedException
  48. */
  49. protected function writeArray(array $array): bool {
  50. if (file_put_contents($this->filename, "<?php\n return " . var_export($array, true) . ';', LOCK_EX) === false) {
  51. throw new Minz_PermissionDeniedException($this->filename);
  52. }
  53. if (function_exists('opcache_invalidate')) {
  54. opcache_invalidate($this->filename); //Clear PHP cache for include
  55. }
  56. return true;
  57. }
  58. /** @return resource|false */
  59. private function getLock() {
  60. $handle = fopen($this->filename, 'r');
  61. if ($handle === false) {
  62. return false;
  63. }
  64. $count = 50;
  65. while (!flock($handle, LOCK_SH) && $count > 0) {
  66. $count--;
  67. usleep(1000);
  68. }
  69. if ($count > 0) {
  70. return $handle;
  71. } else {
  72. fclose($handle);
  73. return false;
  74. }
  75. }
  76. /** @param resource $handle */
  77. private function releaseLock($handle): void {
  78. flock($handle, LOCK_UN);
  79. fclose($handle);
  80. }
  81. }