@@ -76,7 +76,7 @@ private function all(): array
7676 return [];
7777 }
7878
79- $ cache = include $ this ->file ();
79+ $ cache = @ include $ this ->file ();
8080
8181 if (! is_array ($ cache )) {
8282 return [];
@@ -95,14 +95,28 @@ private function persist(string $key, array $values): void
9595
9696 $ cache [$ key ] = $ values ;
9797
98- // ensure folder exists
99- if (! is_dir (dirname ($ this ->file ()))) {
100- mkdir (dirname ($ this ->file ()), 0755 , true );
98+ $ dirPath = dirname ($ this ->file ());
99+ if (! is_dir ($ dirPath )) {
100+ if (! @mkdir ($ dirPath , 0777 , true )) {
101+ return ;
102+ }
103+ @chmod ($ dirPath , 0777 );
101104 }
102105
103- $ this ->withinLock (
104- fn () => file_put_contents ($ this ->file (), '<?php return ' .var_export ($ cache , true ).'; ' )
105- );
106+ $ this ->withinLock (function () use ($ cache ) {
107+ $ content = '<?php return ' .var_export ($ cache , true ).'; ' ;
108+ $ filePath = $ this ->file ();
109+ $ tempFile = $ filePath .'.tmp ' ;
110+
111+ if (@file_put_contents ($ tempFile , $ content , LOCK_EX ) !== false ) {
112+ @chmod ($ tempFile , 0666 );
113+ if (@rename ($ tempFile , $ filePath )) {
114+ @chmod ($ filePath , 0666 );
115+ } else {
116+ @unlink ($ tempFile );
117+ }
118+ }
119+ });
106120 }
107121
108122 /**
@@ -114,22 +128,29 @@ private function withinLock(callable $callback): mixed
114128 return $ callback ();
115129 }
116130
117- $ lock = fopen ($ this ->file (), 'c+ ' );
131+ $ lock = @ fopen ($ this ->file (), 'c+ ' );
118132
119133 if ($ lock === false ) {
120134 return $ callback ();
121135 }
122136
123- // wait for the lock
124- while (! flock ($ lock , LOCK_EX | LOCK_NB )) {
125- usleep (1 );
137+ $ attempts = 0 ;
138+ while (! @flock ($ lock , LOCK_EX | LOCK_NB ) && $ attempts < 100 ) {
139+ usleep (1000 );
140+ $ attempts ++;
141+ }
142+
143+ if ($ attempts >= 100 ) {
144+ @fclose ($ lock );
145+
146+ return $ callback ();
126147 }
127148
128149 try {
129150 return $ callback ();
130151 } finally {
131- flock ($ lock , LOCK_UN );
132- fclose ($ lock );
152+ @ flock ($ lock , LOCK_UN );
153+ @ fclose ($ lock );
133154 }
134155 }
135156}
0 commit comments