CollectionDirection.php 1.1 KB

123456789101112131415161718192021222324252627282930313233
  1. <?php
  2. declare(strict_types=1);
  3. namespace Yansongda\Artful\Direction;
  4. use Psr\Http\Message\ResponseInterface;
  5. use Yansongda\Artful\Contract\DirectionInterface;
  6. use Yansongda\Artful\Contract\PackerInterface;
  7. use Yansongda\Artful\Exception\Exception;
  8. use Yansongda\Artful\Exception\InvalidResponseException;
  9. use Yansongda\Supports\Collection;
  10. class CollectionDirection implements DirectionInterface
  11. {
  12. /**
  13. * @throws InvalidResponseException
  14. */
  15. public function guide(PackerInterface $packer, ?ResponseInterface $response, array $params = []): Collection
  16. {
  17. if (is_null($response)) {
  18. throw new InvalidResponseException(Exception::RESPONSE_EMPTY, '响应异常: 响应为空,不能进行 direction');
  19. }
  20. $body = (string) $response->getBody();
  21. if (!is_null($result = $packer->unpack($body, $params))) {
  22. return new Collection($result);
  23. }
  24. throw new InvalidResponseException(Exception::RESPONSE_UNPACK_ERROR, '响应异常: 解包错误', ['body' => $body, 'response' => $response]);
  25. }
  26. }