-
Notifications
You must be signed in to change notification settings - Fork 243
Expand file tree
/
Copy pathCallActivity.php
More file actions
321 lines (278 loc) · 11 KB
/
CallActivity.php
File metadata and controls
321 lines (278 loc) · 11 KB
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
<?php
namespace ProcessMaker\Models;
use Exception;
use ProcessMaker\Managers\DataManager;
use ProcessMaker\Nayra\Bpmn\ActivitySubProcessTrait;
use ProcessMaker\Nayra\Bpmn\Events\ActivityActivatedEvent;
use ProcessMaker\Nayra\Bpmn\Events\ActivityClosedEvent;
use ProcessMaker\Nayra\Bpmn\Events\ActivityCompletedEvent;
use ProcessMaker\Nayra\Contracts\Bpmn\ActivityInterface;
use ProcessMaker\Nayra\Contracts\Bpmn\CallActivityInterface;
use ProcessMaker\Nayra\Contracts\Bpmn\ErrorInterface;
use ProcessMaker\Nayra\Contracts\Bpmn\TokenInterface;
use ProcessMaker\Nayra\Contracts\Engine\ExecutionInstanceInterface;
/**
* Call Activity model
*/
class CallActivity implements CallActivityInterface
{
use ActivitySubProcessTrait {
addToken as addTokenBase;
completeSubprocess as completeSubprocessBase;
catchSubprocessError as catchSubprocessErrorBase;
}
private $subProcessRequestVersion;
/**
* Initialize the Call Activity element.
*/
protected function initActivity()
{
$this->attachEvent(
ActivityInterface::EVENT_ACTIVITY_ACTIVATED,
function (ActivityInterface $callActivity, TokenInterface $token) {
$config = json_decode($callActivity->getProperty('config'), true);
$startId = is_array($config) && isset($config['startEvent']) ? $config['startEvent'] : null;
$instance = $this->callSubprocess($token, $startId);
$this->getRepository()
->getTokenRepository()
->persistCallActivityActivated($token, $instance, $startId);
$this->linkProcesses($token, $instance);
$this->synchronizeInstances($token->getInstance(), $instance);
}
);
}
/**
* Call the subprocess
*
* @return ExecutionInstanceInterface
*/
protected function callSubprocess(TokenInterface $token, $startId)
{
// The entire data model is sent to the target
$dataManager = new DataManager();
$data = $dataManager->getData($token);
// Add info about parent (Note MultiInstance also adds _parent info)
if (!isset($data['_parent'])) {
$data['_parent'] = [];
}
$data['_parent']['process_id'] = $token->getInstance()->process_id;
$data['_parent']['request_id'] = $token->getInstance()->id;
$data['_parent']['node_id'] = $token->element_id;
$configString = $this->getProperty('config');
if ($configString) {
$config = json_decode($configString, true);
$data['_parent']['config'] = $config;
}
$callable = $this->getCalledElement($data);
$dataStore = $callable->getRepository()->createDataStore();
$startEvent = $startId ? $callable->getOwnerDocument()->getElementInstanceById($startId) : null;
$dataStore->setData($data);
$instance = $callable->call($dataStore, $startEvent);
return $instance;
}
/**
* Complete the subprocess
*
* @param TokenInterface $token
* @param ExecutionInstanceInterface $closedInstance
* @param ExecutionInstanceInterface $instance
*
* @return CallActivity
*/
protected function completeSubprocess(TokenInterface $token, ExecutionInstanceInterface $closedInstance, ExecutionInstanceInterface $instance)
{
$store = $closedInstance->getDataStore();
$allData = $store->getData();
$data = $this->resolveUpdatedData($store, $allData);
$parentData = $token->getInstance()->getDataStore()->getData();
$data = $this->mergeNewKeys($data, $allData, $parentData);
$data = $this->mergeChangedKeys($data, $allData, $parentData);
$dataManager = new DataManager();
$dataManager->updateData($token, $data);
$token->getInstance()->getProcess()->getEngine()->runToNextState();
// Complete the sub process call
$this->completeSubprocessBase($token);
$this->synchronizeInstances($instance, $token->getInstance());
return $this;
}
/**
* Decide which data from the subprocess should be merged based on updated keys.
*/
protected function resolveUpdatedData($store, array $allData): array
{
$updatedKeys = method_exists($store, 'getUpdated')
? $store->getUpdated()
: null;
if ($updatedKeys === null) {
return $allData;
}
if ($updatedKeys === []) {
return [];
}
$updatedKeys = array_values((array) $updatedKeys);
return array_intersect_key($allData, array_flip($updatedKeys));
}
/**
* Merge keys that exist only in the subprocess data.
*/
protected function mergeNewKeys(array $data, array $allData, array $parentData): array
{
$newKeys = array_diff(array_keys($allData), array_keys($parentData));
if (empty($newKeys)) {
return $data;
}
return $data + array_intersect_key($allData, array_flip($newKeys));
}
/**
* Merge keys that changed in the subprocess but may not have been tracked.
*/
protected function mergeChangedKeys(array $data, array $allData, array $parentData): array
{
$changedKeys = [];
foreach ($allData as $key => $value) {
if (array_key_exists($key, $parentData) && $parentData[$key] !== $value) {
$changedKeys[] = $key;
}
}
if (empty($changedKeys)) {
return $data;
}
$pendingKeys = array_diff($changedKeys, array_keys($data));
return $data + array_intersect_key($allData, array_flip($pendingKeys));
}
/**
* Catch a subprocess error
*
* @param TokenInterface $token
* @param ErrorInterface|null $error
* @param ExecutionInstanceInterface $instance
*
* @return CallActivity
*/
protected function catchSubprocessError(TokenInterface $token, ErrorInterface $error = null, ExecutionInstanceInterface $instance)
{
$this->catchSubprocessErrorBase($token, $error);
// Log subprocess error message
$message = [];
if ($error) {
$message = [$error->getName()];
}
if ($instance->errors && is_array($instance->errors)) {
foreach ($instance->errors as $err) {
$errorMessage = $err['message'];
if (array_key_exists('body', $err)) {
// add the body but not the stack trace:
$errorMessage = "\n" . explode('Stack trace', $err['body'])[0];
}
$message[] = $errorMessage;
}
}
$token->getInstance()->logError(new Exception(implode("\n", $message)), $this);
$this->synchronizeInstances($instance, $token->getInstance());
return $this;
}
/**
* Array map of custom event classes for the bpmn element.
*
* @return array
*/
protected function getBpmnEventClasses()
{
return [
ActivityInterface::EVENT_ACTIVITY_ACTIVATED => ActivityActivatedEvent::class,
ActivityInterface::EVENT_ACTIVITY_COMPLETED => ActivityCompletedEvent::class,
ActivityInterface::EVENT_ACTIVITY_CLOSED => ActivityClosedEvent::class,
];
}
/**
* Get the called element by the activity.
*
* @return \ProcessMaker\Nayra\Contracts\Bpmn\CallableElementInterface
*/
public function getCalledElement(array $data = [], bool $evaluatePublisher = true)
{
$calledElementRef = $this->getProperty(CallActivityInterface::BPMN_PROPERTY_CALLED_ELEMENT);
$refs = explode('-', $calledElementRef);
if (count($refs) === 1) {
return $this->getOwnerDocument()->getElementInstanceById($calledElementRef);
} elseif (count($refs) === 2) {
// Capability to reuse other processes inside a process
$process = is_numeric($refs[1]) ? Process::findOrFail($refs[1]) : Process::where('package_key', $refs[1])->firstOrFail();
$engine = $this->getProcess()->getEngine();
if ($this->subProcessRequestVersion) {
$definitions = $engine->getDefinition($this->subProcessRequestVersion);
} else {
$this->subProcessRequestVersion = $evaluatePublisher
? $process->getPublishedVersion($data)
: $process->getLatestVersion();
$definitions = $engine->getDefinition($this->subProcessRequestVersion);
}
$response = $definitions->getElementInstanceById($refs[0]);
return $response;
}
}
/**
* Set the called element by the activity.
*
* @param \ProcessMaker\Nayra\Contracts\Bpmn\CallableElementInterface|string $callableElement
*
* @return $this
*/
public function setCalledElement($callableElement)
{
$this->setProperty(CallActivityInterface::BPMN_PROPERTY_CALLED_ELEMENT, $callableElement);
return $this;
}
/**
* Load tokens from array. And Link to the subprocess if exists.
*
* @param ExecutionInstanceInterface $instance
* @param TokenInterface $token
*
* @return $this
*/
public function addToken(ExecutionInstanceInterface $instance, TokenInterface $token)
{
if ($token->getStatus() === ActivityInterface::TOKEN_STATE_ACTIVE && !empty($token->subprocess_request_id)) {
// Set subprocess request (to get the right process version)
$this->subProcessRequestVersion = $token->subProcessRequest->processVersion;
$subprocess = $this->getProcess()->getEngine()->loadProcessRequest($token->subProcessRequest);
$this->linkProcesses($token, $subprocess);
}
return $this->addTokenBase($instance, $token);
}
/**
* Synchronize two process instances
*
* @param ExecutionInstanceInterface $instance
* @param ExecutionInstanceInterface $currentInstance
*/
private function synchronizeInstances(ExecutionInstanceInterface $instance, ExecutionInstanceInterface $currentInstance)
{
$parentProcessId = $instance->getProcess()->getOwnerDocument()->getModel()?->id;
$childProcessId = $currentInstance->getProcess()->getOwnerDocument()->getModel()?->id;
if ($parentProcessId !== $childProcessId) {
$currentInstance->getProcess()->getEngine()->runToNextState();
}
}
/**
* Returns true if callable element is external to the owner definition
*
* @return bool
*/
public function isFromExternalDefinition()
{
$ref = explode('-', $this->getProperty(CallActivityInterface::BPMN_PROPERTY_CALLED_ELEMENT));
return count($ref) === 2 && is_numeric($ref[1]);
}
/**
* Returns true if callable element is a service sub process (like data-connector)
*
* @return bool
*/
public function isServiceSubProcess()
{
$ref = explode('-', $this->getProperty(CallActivityInterface::BPMN_PROPERTY_CALLED_ELEMENT));
return count($ref) === 2 && !is_numeric($ref[1]);
}
}