Test Failed
Pull Request — master (#11)
by Alexander
05:04
created

BooleanBehavior::map()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 11
ccs 0
cts 6
cp 0
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 6
nc 3
nop 1
crap 12
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
    public function events()
28
    {
29
        return [
30
            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
    public function process()
40
    {
41
        foreach ((array)$this->attributes as $attribute) {
42
            $this->owner->{$attribute} = $this->makeReturnValue(
43
                $this->map($this->owner->{$attribute})
44
            );
45
        }
46
    }
47
48
    /**
49
     * @param string|int|bool $value
50
     * @return bool
51
     */
52
    protected function map($value) {
53
        if (is_numeric($value)) {
54
            return (bool)$value;
55
        }
56
57
        if (is_string($value)) {
58
            return $value === 'true';
59
        }
60
61
        return $value;
62
    }
63
64
    /**
65
     * @param bool $value
66
     * @return bool|int
67
     * @throws InvalidConfigException
68
     */
69
    protected function makeReturnValue(bool $value)
70
    {
71
        if (!in_array($this->returnType, [static::RETURN_TYPE_BOOL, static::RETURN_TYPE_INT,])) {
72
            throw new InvalidConfigException("Invalid return type {$this->returnType}");
73
        }
74
        return $this->returnType === static::RETURN_TYPE_BOOL ? $value : (int)$value;
75
    }
76
}