shoman4eg /
moy-nalog
| 1 | <?php |
||
| 2 | declare(strict_types=1); |
||
| 3 | |||
| 4 | namespace Shoman4eg\Nalog\Util; |
||
| 5 | |||
| 6 | use Psr\Http\Message\ResponseInterface; |
||
| 7 | use Shoman4eg\Nalog\Exception\HydrationException; |
||
| 8 | use Shoman4eg\Nalog\Model\CreatableFromArray; |
||
| 9 | |||
| 10 | /** |
||
| 11 | * @author Artem Dubinin <[email protected]> |
||
| 12 | */ |
||
| 13 | final class ModelHydrator |
||
| 14 | { |
||
| 15 | /** |
||
| 16 | * @template T |
||
| 17 | * |
||
| 18 | * @param class-string<CreatableFromArray>|class-string<T> $class |
||
|
0 ignored issues
–
show
Documentation
Bug
introduced
by
Loading history...
|
|||
| 19 | * |
||
| 20 | * @return mixed|T |
||
| 21 | */ |
||
| 22 | public function hydrate(ResponseInterface $response, string $class) |
||
| 23 | { |
||
| 24 | $body = $response->getBody()->__toString(); |
||
| 25 | if (\mb_strpos($response->getHeaderLine('Content-Type'), 'application/json') !== 0) { |
||
| 26 | throw new HydrationException(sprintf('The ModelHydrator cannot hydrate response with Content-Type: %s', $response->getHeaderLine('Content-Type'))); |
||
| 27 | } |
||
| 28 | |||
| 29 | try { |
||
| 30 | $data = JSON::decode($body); |
||
| 31 | } catch (\JsonException $e) { |
||
| 32 | throw new HydrationException(\sprintf('Error (%d) when trying to json_decode response', $e->getCode())); |
||
| 33 | } |
||
| 34 | |||
| 35 | if (\is_subclass_of($class, CreatableFromArray::class)) { |
||
| 36 | $object = \call_user_func($class.'::createFromArray', $data); |
||
| 37 | } else { |
||
| 38 | $object = new $class($data); |
||
| 39 | } |
||
| 40 | |||
| 41 | return $object; |
||
| 42 | } |
||
| 43 | } |
||
| 44 |