Passed
Push — master ( 63d167...fb60c6 )
by Rutger
03:11
created

BooleanBehavior   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 59
Duplicated Lines 0 %

Test Coverage

Coverage 89.47%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 10
eloc 22
c 1
b 0
f 0
dl 0
loc 59
ccs 17
cts 19
cp 0.8947
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A boolToInt() 0 8 5
A intToBool() 0 11 4
A events() 0 8 1
1
<?php
2
3
namespace rhertogh\Yii2Oauth2Server\models\behaviors;
4
5
use yii\base\Behavior;
6
use yii\db\ActiveRecord;
7
use yii\db\Schema;
8
9
class BooleanBehavior extends Behavior
10
{
11
    /**
12
     * Nummeric database schema types.
13
     */
14
    public const INTEGER_SCHEMA_TYPES = [
15
        Schema::TYPE_INTEGER,
16
        Schema::TYPE_BIGINT,
17
        Schema::TYPE_SMALLINT,
18
        Schema::TYPE_TINYINT,
19
    ];
20
21
    /**
22
     * @inheritDoc
23
     */
24 121
    public function events()
25
    {
26 121
        return [
27 121
            ActiveRecord::EVENT_BEFORE_INSERT => 'boolToInt',
28 121
            ActiveRecord::EVENT_BEFORE_UPDATE => 'boolToInt',
29 121
            ActiveRecord::EVENT_AFTER_INSERT => 'intToBool',
30 121
            ActiveRecord::EVENT_AFTER_UPDATE => 'intToBool',
31 121
            ActiveRecord::EVENT_AFTER_FIND => 'intToBool',
32 121
        ];
33
    }
34
35
    /**
36
     * Convert boolean values to integers before inserting them into the database.
37
     * @throws \yii\base\InvalidConfigException
38
     * @since 1.0.0
39
     */
40 7
    public function boolToInt()
41
    {
42
        /** @var ActiveRecord $activeRecord */
43 7
        $activeRecord = $this->owner;
44
45 7
        foreach ($activeRecord->getTableSchema()->columns as $column) {
46 7
            if (is_bool($activeRecord->{$column->name}) && in_array($column->type, static::INTEGER_SCHEMA_TYPES)) {
47
                $activeRecord->{$column->name} = $activeRecord->{$column->name} ? 1 : 0;
48
            }
49
        }
50
    }
51
52
    /**
53
     * Convert integer values to booleans after loading them from the database.
54
     * @throws \yii\base\InvalidConfigException
55
     * @since 1.0.0
56
     */
57 35
    public function intToBool()
58
    {
59
        /** @var ActiveRecord $activeRecord */
60 35
        $activeRecord = $this->owner;
61
62 35
        foreach ($activeRecord->getTableSchema()->columns as $column) {
63
            if (
64 35
                is_int($activeRecord->{$column->name})
65 35
                && $column->size === 1
66
            ) {
67
                $activeRecord->{$column->name} = (bool)$activeRecord->{$column->name};
68
            }
69
        }
70
    }
71
}
72