/
ServiceFactory.php
305 lines (258 loc) · 9.96 KB
/
ServiceFactory.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
<?php
namespace App\Service;
use App\Http\ErrorResponseGenerator;
use App\Http\MessageSchemaMiddleware;
use App\Infrastructure\Logger\PsrErrorLogger;
use App\Infrastructure\ServiceBus\CommandBus;
use App\Infrastructure\ServiceBus\EventBus;
use App\Infrastructure\ServiceBus\QueryBus;
use App\Infrastructure\ServiceBus\UiExchange;
use App\Infrastructure\System\HealthCheckResolver;
use Codeliner\ArrayReader\ArrayReader;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use Prooph\Common\Event\ProophActionEventEmitter;
use Prooph\Common\Messaging\NoOpMessageConverter;
use Prooph\EventMachine\Container\ContainerChain;
use Prooph\EventMachine\Container\EventMachineContainer;
use Prooph\EventMachine\Container\ServiceRegistry;
use Prooph\EventMachine\EventMachine;
use Prooph\EventMachine\Http\MessageBox;
use Prooph\EventMachine\Messaging\Message;
use Prooph\EventMachine\Persistence\DocumentStore;
use Prooph\EventMachine\Postgres\PostgresDocumentStore;
use Prooph\EventMachine\Projecting\AggregateProjector;
use Prooph\EventStore\EventStore;
use Prooph\EventStore\Pdo\PersistenceStrategy;
use Prooph\EventStore\Pdo\PostgresEventStore;
use Prooph\EventStore\Pdo\Projection\PostgresProjectionManager;
use Prooph\EventStore\Projection\ProjectionManager;
use Prooph\EventStore\TransactionalActionEventEmitterEventStore;
use Prooph\ServiceBus\Exception\MessageDispatchException;
use Prooph\ServiceBus\Message\HumusAmqp\AmqpMessageProducer;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Log\LoggerInterface;
use Zend\Diactoros\Response;
use Zend\ProblemDetails\ProblemDetailsMiddleware;
use Zend\ProblemDetails\ProblemDetailsResponseFactory;
final class ServiceFactory
{
use ServiceRegistry;
/**
* @var ArrayReader
*/
private $config;
/**
* @var ContainerInterface
*/
private $container;
public function __construct(array $appConfig)
{
$this->config = new ArrayReader($appConfig);
}
public function setContainer(ContainerInterface $container): void
{
$this->container = $container;
}
//HTTP endpoints
public function httpMessageBox(): MessageBox
{
return $this->makeSingleton(MessageBox::class, function () {
return $this->eventMachine()->httpMessageBox();
});
}
public function eventMachineHttpMessageSchema(): MessageSchemaMiddleware
{
return $this->makeSingleton(MessageSchemaMiddleware::class, function () {
return new MessageSchemaMiddleware($this->eventMachine());
});
}
public function pdoConnection(): \PDO
{
return $this->makeSingleton(\PDO::class, function () {
$this->assertMandatoryConfigExists('pdo.dsn');
$this->assertMandatoryConfigExists('pdo.user');
$this->assertMandatoryConfigExists('pdo.pwd');
return new \PDO(
$this->config->stringValue('pdo.dsn'),
$this->config->stringValue('pdo.user'),
$this->config->stringValue('pdo.pwd')
);
});
}
protected function eventStorePersistenceStrategy(): PersistenceStrategy
{
return $this->makeSingleton(PersistenceStrategy::class, function () {
return new PersistenceStrategy\PostgresSingleStreamStrategy();
});
}
public function eventStore(): EventStore
{
return $this->makeSingleton(EventStore::class, function () {
$eventStore = new PostgresEventStore(
$this->eventMachine()->messageFactory(),
$this->pdoConnection(),
$this->eventStorePersistenceStrategy()
);
return new TransactionalActionEventEmitterEventStore(
$eventStore,
new ProophActionEventEmitter(TransactionalActionEventEmitterEventStore::ALL_EVENTS)
);
});
}
public function documentStore(): DocumentStore
{
return $this->makeSingleton(DocumentStore::class, function () {
return new PostgresDocumentStore(
$this->pdoConnection(),
null,
'CHAR(36) NOT NULL' //Use alternative docId schema, to allow uuids as well as md5 hashes
);
});
}
public function projectionManager(): ProjectionManager
{
return $this->makeSingleton(ProjectionManager::class, function () {
return new PostgresProjectionManager(
$this->eventStore(),
$this->pdoConnection()
);
});
}
public function aggregateProjector(): AggregateProjector
{
return $this->makeSingleton(AggregateProjector::class, function () {
return new AggregateProjector(
$this->documentStore(),
$this->eventMachine()
);
});
}
public function commandBus(): CommandBus
{
return $this->makeSingleton(CommandBus::class, function () {
$commandBus = new CommandBus();
$errorHandler = new \App\Infrastructure\ServiceBus\ErrorHandler();
$errorHandler->attachToMessageBus($commandBus);
return $commandBus;
});
}
public function eventBus(): EventBus
{
return $this->makeSingleton(EventBus::class, function () {
$eventBus = new EventBus();
$errorHandler = new \App\Infrastructure\ServiceBus\ErrorHandler();
$errorHandler->attachToMessageBus($eventBus);
return $eventBus;
});
}
public function queryBus(): QueryBus
{
return $this->makeSingleton(QueryBus::class, function () {
$queryBus = new QueryBus();
$errorHandler = new \App\Infrastructure\ServiceBus\ErrorHandler();
$errorHandler->attachToMessageBus($queryBus);
return $queryBus;
});
}
public function uiExchange(): UiExchange
{
return $this->makeSingleton(UiExchange::class, function () {
$this->assertMandatoryConfigExists('rabbit.connection');
$connection = new \Humus\Amqp\Driver\AmqpExtension\Connection(
$this->config->arrayValue('rabbit.connection')
);
$connection->connect();
$channel = $connection->newChannel();
$exchange = $channel->newExchange();
$exchange->setName($this->config->stringValue('rabbit.ui_exchange', 'ui-exchange'));
$exchange->setType('fanout');
$humusProducer = new \Humus\Amqp\JsonProducer($exchange);
$messageProducer = new \Prooph\ServiceBus\Message\HumusAmqp\AmqpMessageProducer(
$humusProducer,
new NoOpMessageConverter()
);
return new class($messageProducer) implements UiExchange {
private $producer;
public function __construct(AmqpMessageProducer $messageProducer)
{
$this->producer = $messageProducer;
}
public function __invoke(Message $event): void
{
$this->producer->__invoke($event);
}
};
});
}
public function problemDetailsMiddleware(): ProblemDetailsMiddleware
{
return $this->makeSingleton(ProblemDetailsMiddleware::class, function() {
$isDevEnvironment = $this->config->stringValue('environment', 'prod') === 'dev';
$problemDetailsResponseFactory = new class(
function() {
return new Response();
},
$isDevEnvironment
) extends ProblemDetailsResponseFactory {
public function createResponseFromThrowable(
ServerRequestInterface $request,
\Throwable $e
) : ResponseInterface {
if($e instanceof MessageDispatchException) {
$e = $e->getPrevious();
}
return parent::createResponseFromThrowable($request, $e);
}
};
$errorHandler = new ProblemDetailsMiddleware($problemDetailsResponseFactory);
$errorHandler->attachListener(new PsrErrorLogger($this->logger()));
return $errorHandler;
});
}
public function logger(): LoggerInterface
{
return $this->makeSingleton(LoggerInterface::class, function () {
$streamHandler = new StreamHandler('php://stderr');
return new Logger('EventMachine', [$streamHandler]);
});
}
public function healthCheckResolver(): HealthCheckResolver
{
return $this->makeSingleton(HealthCheckResolver::class, function () {
return new HealthCheckResolver();
});
}
public function eventMachine(): EventMachine
{
$this->assertContainerIsset();
return $this->makeSingleton(EventMachine::class, function () {
//@TODO add config param to enable caching
$eventMachine = new EventMachine();
//Load descriptions here or add them to config/autoload/global.php
foreach ($this->config->arrayValue('event_machine.descriptions') as $desc) {
$eventMachine->load($desc);
}
$containerChain = new ContainerChain(
$this->container,
new EventMachineContainer($eventMachine)
);
$eventMachine->initialize($containerChain);
return $eventMachine;
});
}
private function assertContainerIsset(): void
{
if(null === $this->container) {
throw new \RuntimeException("Main container is not set. Use " . __CLASS__ . "::setContainer() to set it.");
}
}
private function assertMandatoryConfigExists(string $path): void
{
if(null === $this->config->mixedValue($path)) {
throw new \RuntimeException("Missing application config for $path");
}
}
}