Passed
Pull Request — master (#14)
by Alexander
02:11
created

BooleanBehavior::map()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 11
ccs 6
cts 6
cp 1
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 6
nc 3
nop 1
crap 3
1
<?php
2
3
namespace Horat1us\Yii\Behaviors;
4
5
use yii\base\Behavior;
6
use yii\base\InvalidConfigException;
7
use yii\db\ActiveRecord;
8
9
/**
10
 * Class BooleanBehavior
11
 * @package Horat1us\Yii\Behaviors
12
 */
13
class BooleanBehavior extends Behavior
14
{
15
    const RETURN_TYPE_INT = 'int';
16
    const RETURN_TYPE_BOOL = 'bool';
17
18
    /** @var  string|string[] */
19
    public $attributes;
20
21
    /** @var  string */
22
    public $returnType;
23
24
    /**
25
     * @return array
26
     */
27 2
    public function events()
28
    {
29
        return [
30 2
            ActiveRecord::EVENT_BEFORE_VALIDATE => 'process',
31
            ActiveRecord::EVENT_BEFORE_INSERT => 'process',
32
            ActiveRecord::EVENT_BEFORE_UPDATE => 'process',
33
        ];
34
    }
35
36
    /**
37
     * @return void
38
     */
39 2
    public function process()
40
    {
41 2
        foreach ((array)$this->attributes as $attribute) {
42 2
            if (is_null($this->owner->{$attribute})) {
43 2
                continue;
44
            }
45
46 2
            $this->owner->{$attribute} = $this->makeReturnValue(
47 2
                $this->map($this->owner->{$attribute})
48
            );
49
        }
50 2
    }
51
52
    /**
53
     * @param string|int|bool $value
54
     * @return bool|mixed
55
     */
56 2
    protected function map($value) {
57 2
        if (is_numeric($value)) {
58 2
            return (bool)$value;
59
        }
60
61 2
        if (is_string($value)) {
62 2
            return $value === 'true';
63
        }
64
65 2
        return $value;
66
    }
67
68
    /**
69
     * @param bool|mixed $value
70
     * @return bool|int|mixed
71
     * @throws InvalidConfigException
72
     */
73 2
    protected function makeReturnValue($value)
74
    {
75 2
        if (!is_bool($value)) {
76 2
            return $value;
77
        }
78
79 2
        if (!in_array($this->returnType, [static::RETURN_TYPE_BOOL, static::RETURN_TYPE_INT,])) {
80
            throw new InvalidConfigException("Invalid return type {$this->returnType}");
81
        }
82 2
        return $this->returnType === static::RETURN_TYPE_BOOL ? $value : (int)$value;
83
    }
84
}