@@ -19,6 +19,9 @@ class Rotation
1919
2020 private bool $ _truncate = false ;
2121
22+ /**
23+ * @param mixed[] $options
24+ */
2225 public function __construct (array $ options = [])
2326 {
2427 $ this ->processor = new RotativeProcessor ();
@@ -199,25 +202,15 @@ private function copyAndTruncate(string $filename): ?string
199202 {
200203 clearstatcache ();
201204
202- $ filenameTarget = tempnam (dirname ($ filename ), 'LOG ' );
203-
204- $ fd = fopen ($ filename , 'r+ ' );
205-
206- if ($ fd === false ) {
207- $ this ->exception (
208- new Exception (sprintf ('the file %s not can open. ' , $ filename ), 20 )
209- );
205+ $ filenameTarget = $ this ->getTempFilename (dirname ($ filename ));
210206
207+ if (!$ filenameTarget ) {
211208 return null ;
212209 }
213210
214- if (!flock ($ fd , LOCK_EX )) {
215- fclose ($ fd );
216-
217- $ this ->exception (
218- new Exception (sprintf ('the file %s not can lock. ' , $ filename ), 21 )
219- );
211+ $ fd = $ this ->openFileWithLock ($ filename );
220212
213+ if (!$ fd ) {
221214 return null ;
222215 }
223216
@@ -259,7 +252,11 @@ private function move(string $filename): ?string
259252 {
260253 clearstatcache ();
261254
262- $ filenameTarget = tempnam (dirname ($ filename ), 'LOG ' );
255+ $ filenameTarget = $ this ->getTempFilename (dirname ($ filename ));
256+
257+ if (!$ filenameTarget ) {
258+ return null ;
259+ }
263260
264261 if (!rename ($ filename , $ filenameTarget )) {
265262 $ this ->exception (
@@ -274,4 +271,47 @@ private function move(string $filename): ?string
274271
275272 return $ filenameTarget ;
276273 }
274+
275+ private function getTempFilename (string $ path ): ?string
276+ {
277+ $ filename = tempnam ($ path , 'LOG ' );
278+
279+ if ($ filename === false ) {
280+ $ this ->exception (
281+ new Exception (sprintf ('the file %s not can create temp file. ' , $ path ), 19 )
282+ );
283+
284+ return null ;
285+ }
286+
287+ return $ filename ;
288+ }
289+
290+ /**
291+ * @return null|resource
292+ */
293+ private function openFileWithLock (string $ filename )
294+ {
295+ $ fd = fopen ($ filename , 'r+ ' );
296+
297+ if ($ fd === false ) {
298+ $ this ->exception (
299+ new Exception (sprintf ('the file %s not can open. ' , $ filename ), 20 )
300+ );
301+
302+ return null ;
303+ }
304+
305+ if (!flock ($ fd , LOCK_EX )) {
306+ fclose ($ fd );
307+
308+ $ this ->exception (
309+ new Exception (sprintf ('the file %s not can lock. ' , $ filename ), 21 )
310+ );
311+
312+ return null ;
313+ }
314+
315+ return $ fd ;
316+ }
277317}
0 commit comments