SynchronousAutoIndexBehavior::events()   B
last analyzed

Complexity

Conditions 4
Paths 1

Size

Total Lines 26
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 4

Importance

Changes 2
Bugs 0 Features 0
Metric Value
dl 0
loc 26
ccs 18
cts 18
cp 1
rs 8.5806
c 2
b 0
f 0
cc 4
eloc 14
nc 1
nop 0
crap 4
1
<?php
2
3
namespace leinonen\Yii2Algolia\ActiveRecord;
4
5
use Yii;
6
use yii\base\Event;
7
use yii\base\Behavior;
8
use yii\db\ActiveRecord;
9
use leinonen\Yii2Algolia\AlgoliaManager;
10
11
class SynchronousAutoIndexBehavior extends Behavior
12
{
13
    /**
14
     * If the model should be removed from index after delete.
15
     *
16
     * @var bool
17
     */
18
    public $afterDelete = true;
19
20
    /**
21
     * If the model should be added to index after insert.
22
     *
23
     * @var bool
24
     */
25
    public $afterInsert = true;
26
27
    /**
28
     * If the model should be updated also to index after update.
29
     *
30
     * @var bool
31
     */
32
    public $afterUpdate = true;
33
34
    /**
35
     * {@inheritdoc}
36
     */
37 6
    public function events()
38
    {
39
        return [
40
            ActiveRecord::EVENT_AFTER_INSERT => function (Event $event) {
41 2
                if ($this->afterInsert) {
42
                    /** @var $manager AlgoliaManager */
43 1
                    $manager = Yii::$container->get(AlgoliaManager::class);
44 1
                    $manager->pushToIndices($event->sender);
45 1
                }
46 6
            },
47
            ActiveRecord::EVENT_AFTER_DELETE => function (Event $event) {
48 2
                if ($this->afterDelete) {
49
                    /** @var $manager AlgoliaManager */
50 1
                    $manager = Yii::$container->get(AlgoliaManager::class);
51 1
                    $manager->removeFromIndices($event->sender);
52 1
                }
53 6
            },
54 6
            ActiveRecord::EVENT_AFTER_UPDATE => function (Event $event) {
55 2
                if ($this->afterUpdate) {
56
                    /** @var $manager AlgoliaManager */
57 1
                    $manager = Yii::$container->get(AlgoliaManager::class);
58 1
                    $manager->updateInIndices($event->sender);
59 1
                }
60 6
            },
61 6
        ];
62
    }
63
}
64