Passed
Push — master ( f43c0a...452f90 )
by Alexander
34s
created

FlexibleTimestampBehavior   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 4
c 1
b 0
f 0
lcom 1
cbo 2
dl 0
loc 51
ccs 0
cts 31
cp 0
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A events() 0 8 1
B map() 0 28 3
1
<?php
2
3
namespace Horat1us\Yii\Behaviors;
4
5
use Carbon\Carbon;
6
use yii\base\Behavior;
7
use yii\db\ActiveRecord;
8
9
/**
10
 * Class FlexibleTimestampBehavior
11
 * @package Horat1us\Yii\Behaviors
12
 */
13
class FlexibleTimestampBehavior extends Behavior
14
{
15
    /** @var  string[] */
16
    public $attributes;
17
18
    public $format = 'Y-m-d';
19
20
    /**
21
     * @return array
22
     */
23
    public function events()
24
    {
25
        return [
26
            ActiveRecord::EVENT_BEFORE_VALIDATE => 'map',
27
            ActiveRecord::EVENT_BEFORE_INSERT => 'map',
28
            ActiveRecord::EVENT_BEFORE_UPDATE => 'map',
29
        ];
30
    }
31
32
    /**
33
     * @return void
34
     */
35
    public function map()
36
    {
37
        foreach ($this->attributes as $attribute) {
38
            $value = $this->owner->{$attribute};
39
40
            $date = null;
41
            preg_replace_callback_array(
42
                [
43
                    '/^\d{4}\-\d{2}\-\d{2}$/' => function ($match) use (&$date) {
44
                        $date = Carbon::createFromFormat('Y-m-d', $match[0]);
45
                    },
46
                    '/^\d{2}\.\d{2}\.\d{4}$/' => function ($match) use (&$date) {
47
                        $date = Carbon::createFromFormat('d.m.Y', $match[0]);
48
                    },
49
                    '/^\d+$/' => function ($match) use (&$date) {
50
                        $date = Carbon::createFromTimestamp($match[0]);
51
                    }
52
                ],
53
                $value
54
            );
55
56
            if (!$date instanceof Carbon) {
57
                continue;
58
            }
59
60
            $this->owner->{$attribute} = $date->format($this->format);
61
        }
62
    }
63
}