ModelAccessor   A
last analyzed

Complexity

Total Complexity 17

Size/Duplication

Total Lines 88
Duplicated Lines 0 %

Test Coverage

Coverage 61.76%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 27
c 1
b 0
f 0
dl 0
loc 88
ccs 21
cts 34
cp 0.6176
rs 10
wmc 17

6 Methods

Rating   Name   Duplication   Size   Complexity  
A create() 0 7 2
A delete() 0 6 3
A get() 0 9 3
A createBasedOnModel() 0 9 3
A set() 0 6 3
A exists() 0 9 3
1
<?php
2
3
namespace Volosyuk\SimpleEloquent;
4
5
use Exception;
6
use stdClass;
7
8
/**
9
 * Perform simple operations with models depends on their type
10
 *
11
 * Class ModelAccessor
12
 * @package Volosyuk\SimpleEloquent
13
 */
14
class ModelAccessor
15
{
16
    /**
17
     * @param $model
18
     * @param $attribute
19
     * @param $value
20
     */
21 16
    public static function set(&$model, $attribute, $value)
22
    {
23 16
        if (is_array($model)) {
24
            $model[$attribute] = $value;
25 16
        } elseif (is_object($model)) {
26 16
            $model->{$attribute} = $value;
27
        }
28 16
    }
29
30
    /**
31
     * @param $model
32
     * @param $attribute
33
     * @return mixed|null
34
     */
35 11
    public static function get($model, $attribute)
36
    {
37 11
        if (is_array($model)) {
38
            return $model[$attribute];
39 11
        } elseif (is_object($model)) {
40 11
            return $model->{$attribute};
41
        }
42
43
        return null;
44
    }
45
46
    /**
47
     * @param $model
48
     * @param $attribute
49
     */
50 6
    public static function delete(&$model, $attribute)
51
    {
52 6
        if (is_array($model)) {
53
            unset($model[$attribute]);
54 6
        } elseif (is_object($model)) {
55 6
            unset($model->{$attribute});
56
        }
57 6
    }
58
59
    /**
60
     * @param $model
61
     * @param $attribute
62
     * @return bool
63
     */
64
    public static function exists($model, $attribute)
65
    {
66
        if (is_array($model)) {
67
            return isset($model[$attribute]);
68
        } elseif (is_object($model)) {
69
            return property_exists($model, $attribute);
70
        }
71
72
        return false;
73
    }
74
75
    /**
76
     * @param $model
77
     * @return array|stdClass
78
     * @throws Exception
79
     */
80 10
    public static function createBasedOnModel($model)
81
    {
82 10
        if (is_array($model)) {
83
            return self::create(true);
84 10
        } elseif (is_object($model)) {
85 10
            return self::create(false);
86
        }
87
88
        throw new Exception('Model type is not valid');
89
    }
90
91
    /**
92
     * @param bool $buildArray
93
     * @return array|stdClass
94
     */
95 10
    private static function create($buildArray = true)
96
    {
97 10
        if ($buildArray) {
98
            return [];
99
        }
100
101 10
        return new stdClass;
102
    }
103
}
104