1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace TreeHouse\Queue\Message\Composer; |
4
|
|
|
|
5
|
|
|
use Doctrine\Common\Persistence\ManagerRegistry; |
6
|
|
|
use TreeHouse\Queue\Message\Serializer\SerializerInterface; |
7
|
|
|
|
8
|
|
|
class DoctrineMessageComposer extends DefaultMessageComposer |
9
|
|
|
{ |
10
|
|
|
/** |
11
|
|
|
* @var ManagerRegistry |
12
|
|
|
*/ |
13
|
|
|
protected $doctrine; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* @var string |
17
|
|
|
*/ |
18
|
|
|
protected $className; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* @param ManagerRegistry $doctrine |
22
|
|
|
* @param SerializerInterface $serializer |
23
|
|
|
* @param string $className |
24
|
|
|
*/ |
25
|
5 |
|
public function __construct(ManagerRegistry $doctrine, SerializerInterface $serializer, $className) |
26
|
|
|
{ |
27
|
5 |
|
$this->doctrine = $doctrine; |
28
|
5 |
|
$this->className = $className; |
29
|
|
|
|
30
|
5 |
|
parent::__construct($serializer); |
31
|
5 |
|
} |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* @param mixed $payload |
35
|
|
|
* |
36
|
|
|
* @throws \RuntimeException |
37
|
|
|
* |
38
|
|
|
* @return string |
39
|
|
|
*/ |
40
|
4 |
|
protected function serialize($payload) |
41
|
|
|
{ |
42
|
|
|
// convert identifier to Doctrine object |
43
|
4 |
|
if (is_array($payload) || is_scalar($payload)) { |
44
|
|
|
// just use the id when no keys are given (Doctrine expects an array like [id: 1234] |
45
|
2 |
|
if (is_array($payload) && is_numeric(key($payload))) { |
46
|
1 |
|
$payload = current($payload); |
47
|
|
|
} |
48
|
|
|
|
49
|
2 |
|
$payload = $this->doctrine->getRepository($this->className)->find($payload); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
// anything else is just wrong at this point |
53
|
4 |
|
if (!is_object($payload) || !($payload instanceof $this->className)) { |
54
|
3 |
|
throw new \RuntimeException( |
55
|
3 |
|
sprintf('Expecting object of type %s, but got %s', $this->className, var_export($payload, true)) |
56
|
|
|
); |
57
|
|
|
} |
58
|
|
|
|
59
|
1 |
|
return parent::serialize($payload); |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|