@@ -1055,49 +1055,45 @@ public function saveJson($mode = '', $options = JSON_PRETTY_PRINT)
1055
1055
////////////////////////////////////////////////////////////////////////////////////////////////////////////
1056
1056
////////////////////////////////////////////////////////////////////////////////////////////////////////////
1057
1057
1058
- protected static function read_file ($ filename )
1058
+ protected static function protected_file_operation ($ filename, $ filemode , $ operation )
1059
1059
{
1060
- $ fp = fopen ($ filename , " r " );
1061
- $ success = false ;
1060
+ $ fp = fopen ($ filename , $ filemode );
1061
+ $ lock_success = false ;
1062
1062
$ result = "" ;
1063
1063
1064
1064
$ attempts = 15 ;
1065
1065
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 );
1068
1068
flock ($ fp , LOCK_UN ); // release the lock
1069
- $ success = true ;
1069
+ $ lock_success = true ;
1070
1070
break ;
1071
- }
1071
+ }
1072
1072
}
1073
1073
1074
1074
fclose ($ fp );
1075
- if (!$ success ) echo "Couldn't get the lock: $ filename " ;
1075
+ if (!$ lock_success ) echo "Couldn't get the lock: $ filename " ;
1076
1076
return $ result ;
1077
1077
}
1078
1078
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
+
1079
1086
protected static function write_file ($ filename , $ contents )
1080
1087
{
1081
1088
// We use same format for read and write, and read doesn't accept LOCK_SH
1082
1089
// file_put_contents($filename, $contents, LOCK_EX);
1083
1090
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
+ });
1101
1097
}
1102
1098
1103
1099
////////////////////////////////////////////////////////////////////////////////////////////////////////////
0 commit comments