Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
16 / 16 |
|
100.00% |
3 / 3 |
CRAP | |
100.00% |
1 / 1 |
| EncoderHashmap | |
100.00% |
16 / 16 |
|
100.00% |
3 / 3 |
9 | |
100.00% |
1 / 1 |
| offsetGet | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| create | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| getAcceptedContentTypeForRequest | |
100.00% |
14 / 14 |
|
100.00% |
1 / 1 |
7 | |||
| 1 | <?php |
| 2 | namespace Apie\Serializer; |
| 3 | |
| 4 | use Apie\Core\Lists\ItemHashmap; |
| 5 | use Apie\Serializer\Encoders\JsonEncoder; |
| 6 | use Apie\Serializer\Exceptions\NotAcceptedException; |
| 7 | use Apie\Serializer\Interfaces\EncoderInterface; |
| 8 | use LogicException; |
| 9 | use Psr\Http\Message\RequestInterface; |
| 10 | use Symfony\Component\HttpFoundation\AcceptHeader; |
| 11 | |
| 12 | final class EncoderHashmap extends ItemHashmap |
| 13 | { |
| 14 | protected bool $mutable = false; |
| 15 | |
| 16 | public function offsetGet(mixed $offset): EncoderInterface |
| 17 | { |
| 18 | return parent::offsetGet($offset); |
| 19 | } |
| 20 | |
| 21 | public static function create(): self |
| 22 | { |
| 23 | return new self(['application/json' => new JsonEncoder()]); |
| 24 | } |
| 25 | |
| 26 | public function getAcceptedContentTypeForRequest(RequestInterface $request): string |
| 27 | { |
| 28 | if (empty($this->internalArray)) { |
| 29 | throw new LogicException('I am an encoder hashmap with no encoders?'); |
| 30 | } |
| 31 | |
| 32 | if (!$request->hasHeader('Accept')) { |
| 33 | reset($this->internalArray); |
| 34 | return key($this->internalArray); |
| 35 | } |
| 36 | $acceptString = $request->getHeaderLine('Accept'); |
| 37 | $acceptHeaders = AcceptHeader::fromString($acceptString); |
| 38 | foreach ($this as $mimeType => $_encoder) { |
| 39 | if ($item = $acceptHeaders->get($mimeType)) { |
| 40 | return $mimeType; |
| 41 | } |
| 42 | } |
| 43 | if (strtolower($request->getMethod()) === 'delete') { |
| 44 | reset($this->internalArray); |
| 45 | return key($this->internalArray) ? : 'application/json'; |
| 46 | } |
| 47 | throw new NotAcceptedException($acceptString); |
| 48 | } |
| 49 | } |