ArrayHydrator.php 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. <?php
  2. declare(strict_types=1);
  3. /*
  4. * Copyright (C) 2013 Mailgun
  5. *
  6. * This software may be modified and distributed under the terms
  7. * of the MIT license. See the LICENSE file for details.
  8. */
  9. namespace Mailgun\Hydrator;
  10. use Mailgun\Exception\HydrationException;
  11. use Psr\Http\Message\ResponseInterface;
  12. /**
  13. * Serialize an HTTP response to array.
  14. *
  15. * @author Tobias Nyholm <tobias.nyholm@gmail.com>
  16. */
  17. final class ArrayHydrator implements Hydrator
  18. {
  19. /**
  20. * @param class-string $class
  21. * @return array
  22. * @throws \JsonException
  23. */
  24. public function hydrate(ResponseInterface $response, string $class)
  25. {
  26. $body = $response->getBody()->__toString();
  27. if (0 !== strpos($response->getHeaderLine('Content-Type'), 'application/json')) {
  28. throw new HydrationException('The ArrayHydrator cannot hydrate response with Content-Type:'.$response->getHeaderLine('Content-Type'));
  29. }
  30. try {
  31. $content = json_decode($body, true, 512, JSON_THROW_ON_ERROR);
  32. } catch (\JsonException $exception) {
  33. throw new HydrationException(sprintf('Error (%d) when trying to json_decode response: %s', $exception->getCode(), $exception->getMessage()));
  34. }
  35. return $content;
  36. }
  37. }