Completed
Pull Request — master (#2017)
by Basil
02:27
created

RegistryTrait::set()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 15
rs 9.7666
c 0
b 0
f 0
cc 2
nc 2
nop 2
1
<?php
2
3
namespace luya\traits;
4
5
/**
6
 * Registry Trait.
7
 *
8
 * The RegistryTrait helps to handle set(), get(), has() and remove() operations for a key value based storage.
9
 * 
10
 * Can be attached to ActiveRecords with a `name` and `value` property where name is an unique identifier.
11
 *
12
 * @author Basil Suter <[email protected]>
13
 * @since 1.0.0
14
 */
15
trait RegistryTrait
16
{
17
    /**
18
     * Determines what attribute field in the corresponding model table should be used to find the identifier key.
19
     *
20
     * @return string The name attribute field defaults to `name`.
21
     */
22
    public static function getNameAttribute()
23
    {
24
        return 'name';
25
    }
26
    
27
    /**
28
     * Determines what attribute field in the corresponding model table should be used to store the identifier key and retrieve its data.
29
     *
30
     * @return string The value attribute field defaults to `value`.
31
     */
32
    public static function getValueAttribute()
33
    {
34
        return 'value';
35
    }
36
37
    private static $_data;
38
39
    /**
40
     * Loads all config data into an array.
41
     *
42
     * @return array
43
     */
44
    protected static function getData()
45
    {
46
        if (self::$_data === null) {
47
            self::$_data = self::find()
48
                ->select([self::getNameAttribute(), self::getValueAttribute()])
49
                ->indexBy(self::getNameAttribute())
50
                ->column();
51
        }
52
53
        return self::$_data;
54
    }
55
    
56
    /**
57
     * Check whether a config value exists or not.
58
     * 
59
     * If a value exists but is empty, has will return false.
60
     *
61
     * @param string $name The key to lookup. If not found false is returned.
62
     * @return boolean Whether the key exists or not.
63
     */
64
    public static function has($name)
65
    {
66
        return array_key_exists($name, self::getData());
67
    }
68
    
69
    /**
70
     * Get the value of a config value.
71
     * 
72
     * Returns the value from the registry for the given $name, if not found the defaultValue is returned.  
73
     *
74
     * @param string $name The key to lookup. 
75
     * @param mixed $defaultValue The default value to return if the key does not exist.
76
     * @return mixed
77
     */
78
    public static function get($name, $defaultValue = null)
79
    {
80
        if (self::has($name)) {
81
            return self::getData()[$name];
82
        }
83
    
84
        return $defaultValue;
85
    }
86
    
87
    /**
88
     * Store or Update an existing/new config value.
89
     * 
90
     * If the config value is not found, a new record will be created.
91
     *
92
     * @param string $name They config key
93
     * @param string $value They config value. When working with array data, encode the data first with Json::encode.
94
     * @return boolean Whether saving was successfull or not.
95
     */
96
    public static function set($name, $value)
97
    {
98
        $model = self::find()->where([self::getNameAttribute() => $name])->one();
99
    
100
        if ($model) {
101
            return (bool) $model->updateAttributes([
102
                self::getValueAttribute() => $value,
103
            ]);
104
        }
105
    
106
        $model = new self();
107
        $model->value = $value;
0 ignored issues
show
Bug introduced by
The property value does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
108
        $model->name = $name;
0 ignored issues
show
Bug introduced by
The property name does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
109
        return $model->save();
0 ignored issues
show
Bug introduced by
It seems like save() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
110
    }
111
112
    /**
113
     * Remove an existing config value.
114
     * 
115
     * If the value is not found in the config, false is returned.
116
     *
117
     * @param string $name The key to remove.
118
     * @return bool If element was found and deleting was successfull true is returned, otherwise false.
119
     */
120
    public static function remove($name)
121
    {
122
        $model = self::find()->where([self::getNameAttribute() => $name])->one();
123
    
124
        if ($model) {
125
            return (bool) $model->delete();
126
        }
127
    
128
        return false;
129
    }
130
}
131