Completed
Push — master ( 8db1ca...06e479 )
by Dmitry
02:53
created

Temporal::toggleOverrideIdle()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 19
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 19
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 13
nc 2
nop 5
1
<?php
2
3
namespace Tarantool\Mapper\Plugin;
4
5
use Carbon\Carbon;
6
use Exception;
7
use Tarantool\Mapper\Mapper;
8
use Tarantool\Mapper\Entity;
9
use Tarantool\Mapper\Plugin;
10
use Tarantool\Mapper\Plugin\Temporal\Aggregator;
11
use Tarantool\Mapper\Plugin\Temporal\Schema;
12
13
class Temporal extends Plugin
14
{
15
    private $actor;
16
    private $timestamps = [];
17
    private $aggregator;
18
19
    public function __construct(Mapper $mapper)
20
    {
21
        $this->mapper = $mapper;
22
        $this->schema = new Schema($mapper);
0 ignored issues
show
Bug introduced by
The property schema does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
23
        $this->aggregator = new Aggregator($this);
24
    }
25
26 View Code Duplication
    public function getReference($entity, $id, $target, $date)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
27
    {
28
        $entity = $this->entityNameToId($entity);
29
        $target = $this->entityNameToId($target);
30
        $date = $this->getTimestamp($date);
31
32
        $rows = $this->mapper->getClient()->getSpace('_temporal_reference_state')
33
            ->select([$entity, $id, $target, $date], 0, 1, 0, 4) // [key, index, limit, offset, iterator = LE]
34
            ->getData();
35
36
        if (count($rows)) {
37
            $row = $rows[0];
38
            if ([$entity, $id, $target] == [$row[0], $row[1], $row[2]]) {
39
                $state = $this->mapper->findOne('_temporal_reference_state', [
40
                    'entity' => $entity,
41
                    'id' => $id,
42
                    'target' => $target,
43
                    'begin' => $row[3]
44
                ]);
45
                if (!$state->end || $state->end >= $date) {
46
                    return $state->targetId;
47
                }
48
            }
49
        }
50
    }
51
52
    public function getReferenceLog($entity, $id, $target)
53
    {
54
        $log = [];
55
        $params = [
56
            'entity' => $this->entityNameToId($entity),
57
            'id' => $id,
58
            'target' => $this->entityNameToId($target),
59
        ];
60
        foreach ($this->mapper->find('_temporal_reference', $params) as $reference) {
61
            $log[] = $reference;
62
        }
63
        return $log;
64
    }
65
66 View Code Duplication
    public function getReferences($target, $targetId, $source, $date)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
67
    {
68
        $target = $this->entityNameToId($target);
69
        $source = $this->entityNameToId($source);
70
        $date = $this->getTimestamp($date);
71
72
        $rows = $this->mapper->getClient()->getSpace('_temporal_reference_aggregate')
73
            ->select([$target, $targetId, $source, $date], 0, 1, 0, 4) // [key, index, limit, offset, iterator = LE]
74
            ->getData();
75
76
        if (count($rows)) {
77
            $row = $rows[0];
78
            if ([$target, $targetId, $source] == [$row[0], $row[1], $row[2]]) {
79
                $state = $this->mapper->findOne('_temporal_reference_aggregate', [
80
                    'entity' => $target,
81
                    'id'     => $targetId,
82
                    'source' => $source,
83
                    'begin'  => $row[3]
84
                ]);
85
86
                if (!$state->end || $state->end > $date) {
87
                    return $state->data;
88
                }
89
            }
90
        }
91
        return [];
92
    }
93
94
    public function reference(array $reference)
95
    {
96
        $reference = $this->parseConfig($reference);
97
98 View Code Duplication
        foreach ($reference as $k => $v) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
99
            if (!in_array($k, ['entity', 'id', 'begin', 'end', 'data'])) {
100
                $reference['entity'] = $k;
101
                $reference['id'] = $v;
102
                unset($reference[$k]);
103
            }
104
        }
105
106
        if (!array_key_exists('entity', $reference)) {
107
            throw new Exception("no entity defined");
108
        }
109
110
        if (count($reference['data']) != 1) {
111
            throw new Exception("Invalid reference configuration");
112
        }
113
114
        $targetName = array_keys($reference['data'])[0];
115
        $reference['target'] = $this->entityNameToId($targetName);
116
        $reference['targetId'] = array_values($reference['data'])[0];
117
118
119
        // set entity id
120
        $entityName = $reference['entity'];
121
        $reference['entity'] = $this->entityNameToId($entityName);
122
        $reference['actor'] = $this->actor;
123
        $reference['timestamp'] = Carbon::now()->timestamp;
124
125
        $this->schema->init('reference');
126
        $this->mapper->create('_temporal_reference', $reference);
127
128
        $this->aggregator->updateReferenceState($entityName, $reference['id'], $targetName);
129
    }
130
131
    public function getLinksLog($entity, $entityId, $filter = [])
132
    {
133
        $this->schema->init('link');
134
135
        $entity = $this->entityNameToId($entity);
136
137
        $nodes = $this->mapper->find('_temporal_link', [
138
            'entity' => $entity,
139
            'entityId' => $entityId,
140
        ]);
141
142
        $links = [];
143
144
        foreach ($nodes as $node) {
145
            foreach ($this->aggregator->getLeafs($node) as $leaf) {
146
                $entityName = $this->entityIdToName($leaf->entity);
147
                $link = [
148
                    $entityName => $leaf->entityId,
149
                    'id'        => $leaf->id,
150
                    'begin'     => $leaf->begin,
151
                    'end'       => $leaf->end,
152
                    'timestamp' => $leaf->timestamp,
153
                    'actor'     => $leaf->actor,
154
                    'idle'      => property_exists($leaf, 'idle') ? $leaf->idle : 0,
155
                ];
156
157
                $current = $leaf;
158
                while ($current->parent) {
159
                    $current = $this->mapper->findOne('_temporal_link', $current->parent);
160
                    $entityName = $this->entityIdToName($current->entity);
161
                    $link[$entityName] = $current->entityId;
162
                }
163
164
                if (count($filter)) {
165
                    foreach ($filter as $required) {
166
                        if (!array_key_exists($required, $link)) {
167
                            continue 2;
168
                        }
169
                    }
170
                }
171
                $links[] = $link;
172
            }
173
        }
174
175
        return $links;
176
    }
177
178
    public function getLinks($entity, $id, $date)
179
    {
180
        $this->schema->init('link');
181
182
        $links = $this->getData($entity, $id, $date, '_temporal_link_aggregate');
183
        foreach ($links as $i => $source) {
184
            $link = array_key_exists(1, $source) ? ['data' => $source[1]] : [];
185
            foreach ($source[0] as $spaceId => $entityId) {
186
                $spaceName = $this->mapper->findOne('_temporal_entity', $spaceId)->name;
0 ignored issues
show
Documentation introduced by
$spaceId is of type integer|string, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
187
                $link[$spaceName] = $entityId;
188
            }
189
            $links[$i] = $link;
190
        }
191
        return $links;
192
    }
193
194
    public function getState($entity, $id, $date)
195
    {
196
        $this->schema->init('override');
197
198
        return $this->getData($entity, $id, $date, '_temporal_override_aggregate');
199
    }
200
201
    private function getData($entity, $id, $date, $space)
202
    {
203
        $entity = $this->entityNameToId($entity);
204
        $date = $this->getTimestamp($date);
205
206
        $rows = $this->mapper->getClient()->getSpace($space)
207
            ->select([$entity, $id, $date], 0, 1, 0, 4) // [key, index, limit, offset, iterator = LE]
208
            ->getData();
209
210
        if (count($rows) && $rows[0][0] == $entity && $rows[0][1] == $id) {
211
            $state = $this->mapper->findOne($space, [
212
                'entity' => $entity,
213
                'id' => $id,
214
                'begin' => $rows[0][2]
215
            ]);
216
            if (!$state->end || $state->end >= $date) {
217
                return $state->data;
218
            }
219
        }
220
221
        return [];
222
    }
223
224
    public function getOverrides($entityName, $id)
225
    {
226
        return $this->mapper->find('_temporal_override', [
227
            'entity' => $this->entityNameToId($entityName),
228
            'id' => $id,
229
        ]);
230
    }
231
232
    public function override(array $override)
233
    {
234
        $override = $this->parseConfig($override);
235
236 View Code Duplication
        foreach ($override as $k => $v) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
237
            if (!in_array($k, ['entity', 'id', 'begin', 'end', 'data'])) {
238
                $override['entity'] = $k;
239
                $override['id'] = $v;
240
                unset($override[$k]);
241
            }
242
        }
243
244
        if (!array_key_exists('entity', $override)) {
245
            throw new Exception("no entity defined");
246
        }
247
248
        // set entity id
249
        $entityName = $override['entity'];
250
        $override['entity'] = $this->entityNameToId($entityName);
251
        $override['actor'] = $this->actor;
252
        $override['timestamp'] = Carbon::now()->timestamp;
253
254
        $this->schema->init('override');
255
        $this->mapper->create('_temporal_override', $override);
256
257
        $this->aggregator->updateOverrideAggregation($entityName, $override['id']);
258
    }
259
260
    public function setLinkIdle($id, $flag)
261
    {
262
        $link = $this->mapper->findOrFail('_temporal_link', $id);
263
264
        $idled = property_exists($link, 'idle') && $link->idle > 0;
265
        if ($idled && !$flag || !$idled && $flag) {
266
            return $this->toggleLinkIdle($link);
267
        }
268
    }
269
270
    public function toggleLinkIdle(Entity $link)
271
    {
272
        if (property_exists($link, 'idle') && $link->idle) {
273
            $link->idle = 0;
0 ignored issues
show
Bug introduced by
The property idle does not seem to exist in Tarantool\Mapper\Entity.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
274
        } else {
275
            $link->idle = time();
276
        }
277
        $link->save();
278
279
        $this->aggregator->updateLinkAggregation($link);
280
    }
281
282
    public function setReferenceIdle($entity, $id, $target, $targetId, $begin, $actor, $timestamp, $flag)
283
    {
284
        $reference = $this->mapper->findOrFail('_temporal_reference', [
285
            'entity' => $this->entityNameToId($entity),
286
            'id' => $id,
287
            'target' => $this->entityNameToId($target),
288
            'targetId' => $targetId,
289
            'begin' => $begin,
290
            'actor' => $actor,
291
            'timestamp' => $timestamp,
292
        ]);
293
        $idled = property_exists($reference, 'idle') && $reference->idle > 0;
294
        if ($idled && !$flag || !$idled && $flag) {
295
            return $this->toggleReferenceIdle($entity, $id, $target, $targetId, $begin, $actor, $timestamp);
296
        }
297
    }
298
299
    public function toggleReferenceIdle($entity, $id, $target, $targetId, $begin, $actor, $timestamp)
300
    {
301
        $reference = $this->mapper->findOrFail('_temporal_reference', [
302
            'entity' => $this->entityNameToId($entity),
303
            'id' => $id,
304
            'target' => $this->entityNameToId($target),
305
            'targetId' => $targetId,
306
            'begin' => $begin,
307
            'actor' => $actor,
308
            'timestamp' => $timestamp,
309
        ]);
310
311
        if (property_exists($reference, 'idle') && $reference->idle) {
312
            $reference->idle = 0;
313
        } else {
314
            $reference->idle = time();
315
        }
316
        $reference->save();
317
318
        $this->aggregator->updateReferenceState($entity, $id, $target);
319
    }
320
321
    public function setOverrideIdle($entity, $id, $begin, $actor, $timestamp, $flag)
322
    {
323
        $override = $this->mapper->findOrFail('_temporal_override', [
324
            'entity' => $this->entityNameToId($entity),
325
            'id' => $id,
326
            'begin' => $begin,
327
            'actor' => $actor,
328
            'timestamp' => $timestamp,
329
        ]);
330
        $idled = property_exists($override, 'idle') && $override->idle > 0;
331
        if ($idled && !$flag || !$idled && $flag) {
332
            return $this->toggleOverrideIdle($entity, $id, $begin, $actor, $timestamp);
333
        }
334
    }
335
336
    public function toggleOverrideIdle($entity, $id, $begin, $actor, $timestamp)
337
    {
338
        $override = $this->mapper->findOrFail('_temporal_override', [
339
            'entity' => $this->entityNameToId($entity),
340
            'id' => $id,
341
            'begin' => $begin,
342
            'actor' => $actor,
343
            'timestamp' => $timestamp,
344
        ]);
345
346
        if (property_exists($override, 'idle') && $override->idle) {
347
            $override->idle = 0;
348
        } else {
349
            $override->idle = time();
350
        }
351
        $override->save();
352
353
        $this->aggregator->updateOverrideAggregation($entity, $id);
354
    }
355
356
357
    public function link(array $link)
358
    {
359
        $link = $this->parseConfig($link);
360
361
        $this->schema->init('link');
362
363
        $config = [];
364
        foreach ($link as $entity => $id) {
365
            if (!in_array($entity, ['begin', 'end', 'data'])) {
366
                $config[$entity] = $id;
367
            }
368
        }
369
370
        ksort($config);
371
        $node = null;
372
373
        foreach (array_keys($config) as $i => $entity) {
374
            $id = $config[$entity];
375
            $spaceId = $this->entityNameToId($entity);
376
            $params = [
377
                'entity'   => $spaceId,
378
                'entityId' => $id,
379
                'parent'   => $node ? $node->id : 0,
380
            ];
381
            if (count($config) == $i+1) {
382
                $params['begin'] = $link['begin'];
383
                $params['timestamp'] = 0;
384
            }
385
            $node = $this->mapper->findOrCreate('_temporal_link', $params);
386
        }
387
388
        if (!$node || !$node->parent) {
389
            throw new Exception("Invalid link configuration");
390
        }
391
392
        $node->begin = $link['begin'];
393
        $node->end = $link['end'];
394
        $node->actor = $this->actor;
395
        $node->timestamp = Carbon::now()->timestamp;
396
        if (array_key_exists('data', $link)) {
397
            $node->data = $link['data'];
398
        }
399
400
        $node->save();
401
402
        $this->aggregator->updateLinkAggregation($node);
403
    }
404
405
    public function setActor($actor)
406
    {
407
        $this->actor = $actor;
408
        return $this;
409
    }
410
411
    private function getTimestamp($string)
412
    {
413
        if (!array_key_exists($string, $this->timestamps)) {
414
            if (strlen($string) == 8 && is_numeric($string)) {
415
                $this->timestamps[$string] = Carbon::createFromFormat('Ymd', $string)->setTime(0, 0, 0)->timestamp;
416
            } else {
417
                $this->timestamps[$string] = Carbon::parse($string)->timestamp;
418
            }
419
        }
420
        return $this->timestamps[$string];
421
    }
422
423
    private function parseConfig(array $data)
424
    {
425
        if (!$this->actor) {
426
            throw new Exception("actor is undefined");
427
        }
428
429
        if (array_key_exists('actor', $data)) {
430
            throw new Exception("actor is defined");
431
        }
432
433
        if (array_key_exists('timestamp', $data)) {
434
            throw new Exception("timestamp is defined");
435
        }
436
437
        foreach (['begin', 'end'] as $field) {
438
            if (array_key_exists($field, $data) && strlen($data[$field])) {
439
                if (strlen($data[$field]) == 8 || is_string($data[$field])) {
440
                    $data[$field] = $this->getTimestamp($data[$field]);
441
                }
442
            } else {
443
                $data[$field] = 0;
444
            }
445
        }
446
447
        return $data;
448
    }
449
450
    public function entityNameToId($name)
451
    {
452
        if (!$this->mapper->hasPlugin(Sequence::class)) {
453
            $this->mapper->addPlugin(Sequence::class);
454
        }
455
456
        $this->mapper->getSchema()->once(__CLASS__.'@entity', function (Mapper $mapper) {
0 ignored issues
show
Unused Code introduced by
The parameter $mapper is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
457
            $this->mapper->getSchema()
458
                ->createSpace('_temporal_entity', [
459
                    'id'   => 'unsigned',
460
                    'name' => 'str',
461
                ])
462
                ->addIndex(['id'])
463
                ->addIndex(['name']);
464
        });
465
466
        return $this->mapper->findOrCreate('_temporal_entity', compact('name'))->id;
467
    }
468
469
    public function entityIdToName($id)
470
    {
471
        return $this->mapper->findOne('_temporal_entity', compact('id'))->name;
472
    }
473
}
474