blob: 83836c359bc35e0ff66f668797ad2e578b5d152f (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
<?php
/*
* Copyright (C) 2013-2016 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Hydrator;
use Mailgun\Exception\HydrationException;
use Mailgun\Model\ApiResponse;
use Psr\Http\Message\ResponseInterface;
/**
* Serialize an HTTP response to domain object.
*
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
*/
final class ModelHydrator implements Hydrator
{
/**
* @param ResponseInterface $response
* @param string $class
*
* @return ResponseInterface
*/
public function hydrate(ResponseInterface $response, $class)
{
$body = $response->getBody()->__toString();
$contentType = $response->getHeaderLine('Content-Type');
if (strpos($contentType, 'application/json') !== 0 && strpos($contentType, 'application/octet-stream') !== 0) {
throw new HydrationException('The ModelHydrator cannot hydrate response with Content-Type: '.$contentType);
}
$data = json_decode($body, true);
if (JSON_ERROR_NONE !== json_last_error()) {
throw new HydrationException(sprintf('Error (%d) when trying to json_decode response', json_last_error()));
}
if (is_subclass_of($class, ApiResponse::class)) {
$object = call_user_func($class.'::create', $data);
} else {
$object = new $class($data);
}
return $object;
}
}
|