CountReadStream.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php declare(strict_types=1);
  2. /**
  3. * @copyright Copyright (c) 2018 Robin Appelman <robin@icewind.nl>
  4. *
  5. * @license GNU AGPL version 3 or any later version
  6. *
  7. * This program is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU Affero General Public License as
  9. * published by the Free Software Foundation, either version 3 of the
  10. * License, or (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU Affero General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Affero General Public License
  18. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. *
  20. */
  21. namespace OC\Files\Stream;
  22. use Icewind\Streams\Wrapper;
  23. class CountReadStream extends Wrapper {
  24. /** @var int */
  25. private $count;
  26. /** @var callback */
  27. private $callback;
  28. public static function wrap($source, $callback) {
  29. $context = stream_context_create(array(
  30. 'count' => array(
  31. 'source' => $source,
  32. 'callback' => $callback,
  33. )
  34. ));
  35. return Wrapper::wrapSource($source, $context, 'count', self::class);
  36. }
  37. public function dir_opendir($path, $options) {
  38. return false;
  39. }
  40. public function stream_open($path, $mode, $options, &$opened_path) {
  41. $context = $this->loadContext('count');
  42. $this->callback = $context['callback'];
  43. return true;
  44. }
  45. public function stream_read($count) {
  46. $result = parent::stream_read($count);
  47. $this->count += strlen($result);
  48. return $result;
  49. }
  50. public function stream_close() {
  51. $result = parent::stream_close();
  52. call_user_func($this->callback, $this->count);
  53. return $result;
  54. }
  55. }