Passed
Push — master ( 4cc419...24852b )
by Tõnis
02:14
created

models/BaseLanguageSettings.php (1 issue)

Severity
1
<?php
2
3
namespace andmemasin\language\models;
4
5
6
use andmemasin\myabstract\Settings;
7
use yii\base\InvalidConfigException;
8
use yii\base\UserException;
9
use andmemasin\language\interfaces\WithLanguagesInterface;
10
11
/**
12
 * Class BaseLanguageSettings
13
 * @package andmemasin\language\models
14
 * @author Tõnis Ormisson <[email protected]>
15
 */
16
class BaseLanguageSettings extends Settings
17
{
18
    /** @var BaseLanguageSetting[] */
19
    public $settings;
20
21
    /** @var array */
22
    public $settingsData = [];
23
24
    /** @var WithLanguagesInterface */
25
    public $parent;
26
27
28
    /** @var Language */
29
    public $language;
30
31
    /** {@inheritdoc} */
32
    public function init()
33
    {
34
        parent::init();
35
36
        if (!$this->parent) {
37
            throw new InvalidConfigException('Parent Model must be defined while initiating languages-settings');
38
        }
39
40
        if (!$this->parent instanceof WithLanguagesInterface) {
0 ignored issues
show
$this->parent is always a sub-type of andmemasin\language\inte...\WithLanguagesInterface. If $this->parent can have other possible types, add them to models/BaseLanguageSettings.php:24.
Loading history...
41
            throw new InvalidConfigException('Parent Model must implement WithLanguagesInterface');
42
        }
43
    }
44
45
    /** {@inheritdoc} */
46
    public function save($runValidation = true, $attributeNames = NULL){
47
        if(!empty($this->settings)){
48
            foreach ($this->settings as $key=> $setting){
49
                // delete empty
50
                if($setting->value === null || $setting->value === ''){
51
                    if(!$setting->isNewRecord){
52
                        $setting->delete();
53
                    }
54
                } else {
55
                    if (!$setting->save($runValidation, $attributeNames)) {
56
                        throw new UserException(serialize($setting->errors));
57
                    }
58
59
                    $this->settings[$key] = $setting;
60
                    $this->addErrors($setting->errors);
61
                }
62
63
            }
64
        }
65
66
        return empty($this->errors);
67
    }
68
69
}