CheckoutStream.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. {
  22. use StreamDecoratorTrait;
  23. private $expectedLength;
  24. private $readedCount = 0;
  25. public function __construct(StreamInterface $stream, $expectedLength)
  26. {
  27. $this->stream = $stream;
  28. $this->expectedLength = $expectedLength;
  29. }
  30. public function getContents()
  31. {
  32. $contents = $this->stream->getContents();
  33. $length = strlen($contents);
  34. if ($this->expectedLength !== null && floatval($length) !== $this->expectedLength) {
  35. $this->throwObsException($this->expectedLength, $length);
  36. }
  37. return $contents;
  38. }
  39. public function read($length)
  40. {
  41. $string = $this->stream->read($length);
  42. if ($this->expectedLength !== null) {
  43. $this->readedCount += strlen($string);
  44. if ($this->stream->eof() && floatval($this->readedCount) !== $this->expectedLength) {
  45. $this->throwObsException($this->expectedLength, $this->readedCount);
  46. }
  47. }
  48. return $string;
  49. }
  50. public function throwObsException($expectedLength, $reaLength)
  51. {
  52. $obsException = new ObsException('premature end of Content-Length delimiter message body (expected:' . $expectedLength . '; received:' . $reaLength . ')');
  53. $obsException->setExceptionType('server');
  54. throw $obsException;
  55. }
  56. }