file_writer.class.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. /**
  3. * Write data to file. Default to UTF8 encoding.
  4. *
  5. * @copyright (c) 2012 University of Geneva
  6. * @license GNU General Public License - http://www.gnu.org/copyleft/gpl.html
  7. * @author Laurent Opprecht <laurent@opprecht.info>
  8. */
  9. class FileWriter
  10. {
  11. /**
  12. *
  13. * @param string $path
  14. * @param Converter $converter
  15. * @return FileWriter
  16. */
  17. static function create($path, $converter = null)
  18. {
  19. return new self($path, $converter);
  20. }
  21. const EOL = "\n";
  22. protected $path = '';
  23. protected $handle = null;
  24. protected $converter = null;
  25. /**
  26. *
  27. * @param string $path
  28. * @param Encoding $encoding
  29. */
  30. function __construct($path, $converter = null)
  31. {
  32. $this->path = $path;
  33. $this->converter = $converter ? $converter : Encoding::utf8()->encoder();
  34. }
  35. /**
  36. *
  37. * @return Converter
  38. */
  39. function get_converter()
  40. {
  41. return $this->converter;
  42. }
  43. protected function handle()
  44. {
  45. if (is_null($this->handle)) {
  46. $this->handle = fopen($this->path, 'a+');
  47. }
  48. return $this->handle;
  49. }
  50. function write($text)
  51. {
  52. fwrite($this->handle(), $this->convert($text));
  53. }
  54. function writeln($text)
  55. {
  56. fwrite($this->handle(), $this->convert($text) . self::EOL);
  57. }
  58. function close()
  59. {
  60. if (is_resource($this->handle)) {
  61. fclose($this->handle);
  62. }
  63. $this->handle = null;
  64. }
  65. protected function convert($text)
  66. {
  67. return $this->converter->convert($text);
  68. }
  69. }