|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Enqueue\Client\Extension; |
| 4 | + |
| 5 | +use Enqueue\Client\EmptyExtensionTrait; |
| 6 | +use Enqueue\Client\ExtensionInterface; |
| 7 | +use Enqueue\Client\Message; |
| 8 | +use Enqueue\Client\PreSend; |
| 9 | +use Enqueue\Util\JSON; |
| 10 | + |
| 11 | +class PrepareBodyExtension implements ExtensionInterface |
| 12 | +{ |
| 13 | + use EmptyExtensionTrait; |
| 14 | + |
| 15 | + public function onPreSendEvent(PreSend $context): void |
| 16 | + { |
| 17 | + $this->prepareBody($context->getMessage()); |
| 18 | + } |
| 19 | + |
| 20 | + public function onPreSendCommand(PreSend $context): void |
| 21 | + { |
| 22 | + $this->prepareBody($context->getMessage()); |
| 23 | + } |
| 24 | + |
| 25 | + private function prepareBody(Message $message): void |
| 26 | + { |
| 27 | + $body = $message->getBody(); |
| 28 | + $contentType = $message->getContentType(); |
| 29 | + |
| 30 | + if (is_scalar($body) || null === $body) { |
| 31 | + $contentType = $contentType ?: 'text/plain'; |
| 32 | + $body = (string) $body; |
| 33 | + } elseif (is_array($body)) { |
| 34 | + // only array of scalars is allowed. |
| 35 | + array_walk_recursive($body, function ($value) { |
| 36 | + if (!is_scalar($value) && null !== $value) { |
| 37 | + throw new \LogicException(sprintf( |
| 38 | + 'The message\'s body must be an array of scalars. Found not scalar in the array: %s', |
| 39 | + is_object($value) ? get_class($value) : gettype($value) |
| 40 | + )); |
| 41 | + } |
| 42 | + }); |
| 43 | + |
| 44 | + $contentType = $contentType ?: 'application/json'; |
| 45 | + $body = JSON::encode($body); |
| 46 | + } elseif ($body instanceof \JsonSerializable) { |
| 47 | + $contentType = $contentType ?: 'application/json'; |
| 48 | + $body = JSON::encode($body); |
| 49 | + } else { |
| 50 | + throw new \InvalidArgumentException(sprintf( |
| 51 | + 'The message\'s body must be either null, scalar, array or object (implements \JsonSerializable). Got: %s', |
| 52 | + is_object($body) ? get_class($body) : gettype($body) |
| 53 | + )); |
| 54 | + } |
| 55 | + |
| 56 | + $message->setContentType($contentType); |
| 57 | + $message->setBody($body); |
| 58 | + } |
| 59 | +} |
0 commit comments