@@ -624,28 +624,24 @@ public function tempnam($dir, $prefix)
624
624
* @param string $filename The file to be written to
625
625
* @param string $content The data to write into the file
626
626
*
627
- * @throws IOException If the file cannot be written to.
627
+ * @throws IOException If the file cannot be written to
628
628
*/
629
629
public function dumpFile ($ filename , $ content )
630
630
{
631
- $ dir = dirname ($ filename );
632
-
633
- if (!is_dir ($ dir )) {
634
- $ this ->mkdir ($ dir );
635
- } elseif (!is_writable ($ dir )) {
636
- throw new IOException (sprintf ('Unable to write to the "%s" directory. ' , $ dir ), 0 , null , $ dir );
637
- }
638
-
639
- // Will create a temp file with 0600 access rights
640
- // when the filesystem supports chmod.
641
- $ tmpFile = $ this ->tempnam ($ dir , basename ($ filename ));
642
-
643
- if (false === @file_put_contents ($ tmpFile , $ content )) {
644
- throw new IOException (sprintf ('Failed to write file "%s". ' , $ filename ), 0 , null , $ filename );
645
- }
631
+ return $ this ->writeFile ($ filename , $ content );
632
+ }
646
633
647
- @chmod ($ tmpFile , 0666 & ~umask ());
648
- $ this ->rename ($ tmpFile , $ filename , true );
634
+ /**
635
+ * Atomically appends content to an existing file.
636
+ *
637
+ * @param string $filename The file for which to append content
638
+ * @param string|array|resource $content The content to append
639
+ *
640
+ * @throws IOException If the file is not writable
641
+ */
642
+ public function appendToFile ($ filename , $ content )
643
+ {
644
+ return $ this ->writeFile ($ filename , $ content , true );
649
645
}
650
646
651
647
/**
@@ -675,4 +671,28 @@ private function getSchemeAndHierarchy($filename)
675
671
676
672
return 2 === count ($ components ) ? array ($ components [0 ], $ components [1 ]) : array (null , $ components [0 ]);
677
673
}
674
+
675
+ /**
676
+ * Writes to a file.
677
+ *
678
+ * @param string $filename The file to write into
679
+ * @param string|array|resource $content The content to write
680
+ * @param bool $append Whether to append content to the file if it already exists
681
+ *
682
+ * @throws IOException If the file is not writable
683
+ */
684
+ private function writeFile ($ filename , $ content , $ append = false )
685
+ {
686
+ $ dir = dirname ($ filename );
687
+
688
+ if (!is_dir ($ dir )) {
689
+ $ this ->mkdir ($ dir );
690
+ } elseif (!is_writable ($ dir )) {
691
+ throw new IOException (sprintf ('Unable to write to the "%s" directory. ' , $ dir ), 0 , null , $ dir );
692
+ }
693
+
694
+ if (false === @file_put_contents ($ filename , $ content , $ append ? FILE_APPEND | LOCK_EX : LOCK_EX )) {
695
+ throw new IOException (sprintf ('Failed to write file "%s". ' , $ filename ), 0 , null , $ filename );
696
+ }
697
+ }
678
698
}
0 commit comments