CheckoutStream.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. /**
  3. * Copyright 2019 Huawei Technologies Co.,Ltd.
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not use
  5. * this file except in compliance with the License. You may obtain a copy of the
  6. * License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software distributed
  11. * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  12. * CONDITIONS OF ANY KIND, either express or implied. See the License for the
  13. * specific language governing permissions and limitations under the License.
  14. *
  15. */
  16. namespace Obs\Internal\Common;
  17. use Psr\Http\Message\StreamInterface;
  18. use GuzzleHttp\Psr7\StreamDecoratorTrait;
  19. use Obs\ObsException;
  20. class CheckoutStream implements StreamInterface {
  21. use StreamDecoratorTrait;
  22. private $expectedLength;
  23. private $readedCount = 0;
  24. public function __construct(StreamInterface $stream, $expectedLength) {
  25. $this->stream = $stream;
  26. $this->expectedLength = $expectedLength;
  27. }
  28. public function getContents() {
  29. $contents = $this->stream->getContents();
  30. $length = strlen($contents);
  31. if ($this->expectedLength !== null && floatval($length) !== $this->expectedLength) {
  32. $this -> throwObsException($this->expectedLength, $length);
  33. }
  34. return $contents;
  35. }
  36. public function read($length) {
  37. $string = $this->stream->read($length);
  38. if ($this->expectedLength !== null) {
  39. $this->readedCount += strlen($string);
  40. if ($this->stream->eof()) {
  41. if (floatval($this->readedCount) !== $this->expectedLength) {
  42. $this -> throwObsException($this->expectedLength, $this->readedCount);
  43. }
  44. }
  45. }
  46. return $string;
  47. }
  48. public function throwObsException($expectedLength, $reaLength) {
  49. $obsException = new ObsException('premature end of Content-Length delimiter message body (expected:' . $expectedLength . '; received:' . $reaLength . ')');
  50. $obsException->setExceptionType('server');
  51. throw $obsException;
  52. }
  53. }