Completed
Push — master ( ff18d3...b1af96 )
by Loban
02:26
created

Model::getSaveAttributeList()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 1
1
<?php
2
/**
3
 * @link https://github.com/LAV45/yii2-settings
4
 * @copyright Copyright (c) 2016 LAV45
5
 * @author Alexey Loban <[email protected]>
6
 * @license http://opensource.org/licenses/BSD-3-Clause
7
 */
8
9
namespace lav45\settings;
10
11
use yii\di\Instance;
12
13
/**
14
 * Class Model represents settings model
15
 * @package lav45\settings
16
 */
17
class Model extends \yii\base\Model
18
{
19
    /**
20
     * @var Settings|string|array
21
     */
22
    public $settings = 'settings';
23
24
    /**
25
     * @inheritdoc
26
     */
27 1
    public function init()
28
    {
29 1
        $this->settings = Instance::ensure($this->settings, Settings::class);
30 1
        $this->setAttributes($this->getData());
31 1
    }
32
33
    /**
34
     * @param bool $runValidation
35
     * @return bool
36
     */
37 1
    public function save($runValidation = true)
38
    {
39 1
        if ($runValidation === false || $this->validate()) {
40 1
            return $this->setData($this->getSaveAttributes());
41
        }
42
        return false;
43
    }
44
45
    /**
46
     * @return array|string|integer
47
     */
48 1
    protected function getSettingsKey()
49
    {
50 1
        return [static::class];
51
    }
52
53
    /**
54
     * List of attributes to save
55
     * @return string[]
56
     * @since 1.2.2
57
     */
58 1
    protected function getSaveAttributeList()
59
    {
60 1
        return $this->safeAttributes();
61
    }
62
63
    /**
64
     * @return array
65
     */
66 1
    protected function getSaveAttributes()
67
    {
68 1
        $data = $this->getAttributes($this->getSaveAttributeList());
69
        return array_filter($data, function ($val) {
70 1
            return $val !== '' || $val !== [] || $val !== null ;
71 1
        });
72
    }
73
74
    /**
75
     * @return array
76
     */
77 1
    protected function getData()
78
    {
79 1
        return $this->settings->get($this->getSettingsKey(), []);
80
    }
81
82
    /**
83
     * @param array $data
84
     * @return bool
85
     */
86 1
    protected function setData($data)
87
    {
88 1
        return $this->settings->set($this->getSettingsKey(), $data);
89
    }
90
91
    /**
92
     * @return bool
93
     */
94 1
    public function flush()
95
    {
96 1
        $this->setAttributes(array_fill_keys($this->safeAttributes(), null));
97 1
        return $this->settings->delete($this->getSettingsKey());
98
    }
99
}
100