-
Notifications
You must be signed in to change notification settings - Fork 439
/
Copy pathPrepareBodyExtension.php
65 lines (56 loc) · 2.27 KB
/
PrepareBodyExtension.php
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<?php
namespace Enqueue\Client\Extension;
use ArrayObject;
use Enqueue\Client\Message;
use Enqueue\Client\PreSend;
use Enqueue\Client\PreSendCommandExtensionInterface;
use Enqueue\Client\PreSendEventExtensionInterface;
use Enqueue\Util\JSON;
class PrepareBodyExtension implements PreSendEventExtensionInterface, PreSendCommandExtensionInterface
{
public function onPreSendEvent(PreSend $context): void
{
$this->prepareBody($context->getMessage());
}
public function onPreSendCommand(PreSend $context): void
{
$this->prepareBody($context->getMessage());
}
private function prepareBody(Message $message): void
{
$body = $message->getBody();
$contentType = $message->getContentType();
if (is_scalar($body) || null === $body) {
$contentType = $contentType ?: 'text/plain';
$body = (string) $body;
} elseif (is_array($body) || $body instanceof ArrayObject) {
// convert ArrayObjects to arrays
array_walk_recursive($body, function (&$value) {
if ($value instanceof ArrayObject) {
$value = (array) $value;
}
});
// only array of scalars is allowed.
array_walk_recursive($body, function ($value) {
if (!is_scalar($value) && null !== $value) {
throw new \LogicException(sprintf(
'The message\'s body must be an array of scalars. Found not scalar in the array: %s',
is_object($value) ? get_class($value) : gettype($value)
));
}
});
$contentType = $contentType ?: 'application/json';
$body = JSON::encode($body);
} elseif ($body instanceof \JsonSerializable) {
$contentType = $contentType ?: 'application/json';
$body = JSON::encode($body);
} else {
throw new \InvalidArgumentException(sprintf(
'The message\'s body must be either null, scalar, array or object (implements \JsonSerializable). Got: %s',
is_object($body) ? get_class($body) : gettype($body)
));
}
$message->setContentType($contentType);
$message->setBody($body);
}
}