Advertisement
Guest User

Untitled

a guest
Apr 20th, 2019
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.06 KB | None | 0 0
  1. <?php
  2.  
  3. class TransformingStream {
  4.  
  5. protected $input;
  6. protected $output;
  7.  
  8. // Chunk size...
  9. protected $chunkSize = 4096;
  10.  
  11. // Find/replace operations
  12. protected $search = [];
  13. protected $replace = [];
  14.  
  15. /** @var callable|null */
  16. protected $progress;
  17.  
  18. /**
  19. * TransformingStream constructor.
  20. *
  21. * @param resource $input
  22. * @param resource $output
  23. */
  24. public function __construct($input, $output)
  25. {
  26. $this->input = $input;
  27. $this->output = $output;
  28. }
  29.  
  30. /**
  31. * @return int
  32. */
  33. public function getChunkSize(): int
  34. {
  35. return $this->chunkSize;
  36. }
  37.  
  38. /**
  39. * @param int $chunkSize
  40. * @return \TransformingStream
  41. */
  42. public function setChunkSize(int $chunkSize): self
  43. {
  44. $this->chunkSize = $chunkSize;
  45.  
  46. return $this;
  47. }
  48.  
  49. /**
  50. * @param callable $progress The onProgress callback
  51. */
  52. public function setProgress(callable $progress)
  53. {
  54. $this->progress = $progress;
  55. }
  56.  
  57. public function transform(string $pattern, string $replace): self
  58. {
  59. $this->search[] = $pattern;
  60. $this->replace[] = $replace;
  61.  
  62. return $this;
  63. }
  64.  
  65. public function process()
  66. {
  67. // Early read to fill to twice the buffer size, if possible
  68. $buffer = fread($this->input, $this->chunkSize);
  69. $chunk = 1;
  70. $cb = $this->progress;
  71.  
  72. do {
  73. $buffer .= fread($this->input, $this->chunkSize);
  74.  
  75. // Apply transforms to the whole buffer to fix any operations skipped by
  76. // boundaries of the buffer chunks.
  77. $buffer = preg_replace($this->search, $this->replace, $buffer);
  78.  
  79. // pull off the output chunk...
  80. fwrite($this->output, substr($buffer, 0, $this->chunkSize));
  81. $buffer = substr($buffer, $this->chunkSize);
  82.  
  83. if ($cb) {
  84. $cb($chunk);
  85. }
  86.  
  87. $chunk++;
  88. } while (!feof($this->input));
  89.  
  90. if ($buffer) {
  91. fwrite($this->output, $buffer);
  92. }
  93. }
  94.  
  95. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement