@@ -1055,49 +1055,45 @@ public function saveJson($mode = '', $options = JSON_PRETTY_PRINT)
10551055 ////////////////////////////////////////////////////////////////////////////////////////////////////////////
10561056 ////////////////////////////////////////////////////////////////////////////////////////////////////////////
10571057
1058- protected static function read_file ($ filename )
1058+ protected static function protected_file_operation ($ filename, $ filemode , $ operation )
10591059 {
1060- $ fp = fopen ($ filename , " r " );
1061- $ success = false ;
1060+ $ fp = fopen ($ filename , $ filemode );
1061+ $ lock_success = false ;
10621062 $ result = "" ;
10631063
10641064 $ attempts = 15 ;
10651065 while ($ attempts -- > 0 ) {
1066- if (flock ($ fp , LOCK_SH )) { // acquire an exclusive shared lock
1067- $ result = fread ($ fp , filesize ( $ filename) );
1066+ if (flock ($ fp , $ filemode == " r " ? LOCK_SH : LOCK_EX )) { // acquire lock
1067+ $ result = $ operation ($ fp , $ filename );
10681068 flock ($ fp , LOCK_UN ); // release the lock
1069- $ success = true ;
1069+ $ lock_success = true ;
10701070 break ;
1071- }
1071+ }
10721072 }
10731073
10741074 fclose ($ fp );
1075- if (!$ success ) echo "Couldn't get the lock: $ filename " ;
1075+ if (!$ lock_success ) echo "Couldn't get the lock: $ filename " ;
10761076 return $ result ;
10771077 }
10781078
1079+ protected static function read_file ($ filename )
1080+ {
1081+ return xml_file::protected_file_operation ($ filename , "r " , function ($ fp ) use ($ filename ) {
1082+ return fread ($ fp , filesize ($ filename ));
1083+ });
1084+ }
1085+
10791086 protected static function write_file ($ filename , $ contents )
10801087 {
10811088 // We use same format for read and write, and read doesn't accept LOCK_SH
10821089 // file_put_contents($filename, $contents, LOCK_EX);
10831090
1084- $ fp = fopen ($ filename , "w " );
1085- $ success = false ;
1086-
1087- $ attempts = 15 ;
1088- while ($ attempts -- > 0 ) {
1089- if (flock ($ fp , LOCK_EX )) { // acquire an exclusive lock
1090- ftruncate ($ fp , 0 ); // truncate (erase/overwrite) file
1091- fwrite ($ fp , $ contents );
1092- fflush ($ fp ); // flush output before releasing the lock
1093- flock ($ fp , LOCK_UN ); // release the lock
1094- $ success = true ;
1095- break ;
1096- }
1097- }
1098-
1099- fclose ($ fp );
1100- if (!$ success ) echo "Couldn't get the lock: $ filename " ;
1091+ return xml_file::protected_file_operation ($ filename , "w " , function ($ fp ) use ($ contents ) {
1092+ ftruncate ($ fp , 0 ); // truncate (erase/overwrite) file
1093+ fwrite ($ fp , $ contents );
1094+ fflush ($ fp ); // flush output before releasing the lock
1095+ return "" ; // Supply return value. Not used on write.
1096+ });
11011097 }
11021098
11031099 ////////////////////////////////////////////////////////////////////////////////////////////////////////////
0 commit comments