Passed
Push — master ( e178e9...0a6cdc )
by Rutger
13:08
created

DateTimeBehavior::beforeSave()   A

Complexity

Conditions 5
Paths 3

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 5.0729

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 7
c 1
b 0
f 0
dl 0
loc 12
ccs 6
cts 7
cp 0.8571
rs 9.6111
cc 5
nc 3
nop 0
crap 5.0729
1
<?php
2
3
namespace rhertogh\Yii2Oauth2Server\models\behaviors;
4
5
use DateTimeImmutable;
6
use yii\base\Behavior;
7
use yii\db\ActiveRecord;
8
use yii\db\BaseActiveRecord;
9
use yii\db\Schema;
10
11
/**
12
 * @property BaseActiveRecord $owner
13
 */
14
class DateTimeBehavior extends Behavior
15
{
16
    /**
17
     * The DateTime format to convert to before inserting the DateTime object into the database.
18
     * @var string
19
     */
20
    public $dateTimeFormat = 'Y-m-d H:i:s';
21
22
    /**
23
     * @inheritDoc
24
     */
25 89
    public function events()
26
    {
27
        return [
28 89
            ActiveRecord::EVENT_BEFORE_INSERT => 'beforeSave',
29
            ActiveRecord::EVENT_BEFORE_UPDATE => 'beforeSave',
30
            ActiveRecord::EVENT_AFTER_INSERT => 'afterFind',
31
            ActiveRecord::EVENT_AFTER_UPDATE => 'afterFind',
32
            ActiveRecord::EVENT_AFTER_FIND => 'afterFind',
33
        ];
34
    }
35
36
    /**
37
     * Convert DateTime objects to string before writing the database.
38
     * @throws \yii\base\InvalidConfigException
39
     * @since 1.0.0
40
     */
41 1
    public function beforeSave()
42
    {
43
        /** @var ActiveRecord $activeRecord */
44 1
        $activeRecord = $this->owner;
45
46 1
        foreach ($activeRecord->getTableSchema()->columns as $column) {
47 1
            $value = $this->owner[$column->name];
48
            if (
49 1
                $column->type === Schema::TYPE_DATETIME
50 1
                && ($value instanceof \DateTime || $value instanceof DateTimeImmutable)
51
            ) {
52
                $this->owner[$column->name] = $value->format($this->dateTimeFormat);
53
            }
54
        }
55
    }
56
57
    /**
58
     * Convert strings to DateTime objects after loading them from the database.
59
     * @throws \yii\base\InvalidConfigException
60
     * @since 1.0.0
61
     */
62 14
    public function afterFind()
63
    {
64
        /** @var ActiveRecord $activeRecord */
65 14
        $activeRecord = $this->owner;
66
67 14
        foreach ($activeRecord->getTableSchema()->columns as $column) {
68 14
            $value = $this->owner[$column->name];
69 14
            if ($column->type === Schema::TYPE_DATETIME && !empty($value)) {
70 6
                $dateTime = DateTimeImmutable::createFromFormat($this->dateTimeFormat, $value);
71 6
                $this->owner[$column->name] = $dateTime;
72 6
                $this->owner->setOldAttribute($column->name, $dateTime);
73
            }
74
        }
75
    }
76
}
77