Completed
Push — master ( 7f45a1...6afdf1 )
by Andrey
01:18
created

MultilanguageValidateModel::attributeLabels()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 32

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 32
rs 9.408
c 0
b 0
f 0
cc 4
nc 4
nop 0
1
<?php
2
3
namespace Itstructure\AdminModule\models;
4
5
use yii\db\ActiveRecord as BaseActiveRecord;
6
use yii\base\Model;
7
use yii\helpers\ArrayHelper;
8
use Itstructure\AdminModule\interfaces\ModelInterface;
9
10
/**
11
 * Class MultilanguageValidateModel
12
 * General validation model together with multilingual fields.
13
 *
14
 * @property array $dynamicFields Dynamic fields from which the translated fields are formed.
15
 * @property BaseActiveRecord|MultilanguageTrait $mainModel Basic data model.
16
 *
17
 * @package Itstructure\AdminModule\models
18
 *
19
 * @author Andrey Girnik <[email protected]>
20
 */
21
class MultilanguageValidateModel extends Model implements ModelInterface
22
{
23
    /**
24
     * Dynamic fields from which the translated fields are formed.
25
     *
26
     * @var array
27
     */
28
    public $dynamicFields = [];
29
30
    /**
31
     * Basic data model.
32
     *
33
     * @var BaseActiveRecord|MultilanguageTrait
34
     */
35
    private $mainModel;
36
37
    /**
38
     * Validation rules for all fields together with dynamic.
39
     *
40
     * @return array
41
     */
42
    public function rules(): array
43
    {
44
        return ArrayHelper::merge(
45
            $this->getDynamicValidationRules(),
46
            $this->mainModel->rules()
0 ignored issues
show
Bug introduced by
The method rules does only exist in yii\db\ActiveRecord, but not in Itstructure\AdminModule\models\MultilanguageTrait.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
47
        );
48
    }
49
50
    /**
51
     * Scenarios.
52
     *
53
     * @return array
54
     */
55 View Code Duplication
    public function scenarios(): array
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
56
    {
57
        return [
58
            ModelInterface::SCENARIO_CREATE => $this->attributes(),
59
            ModelInterface::SCENARIO_UPDATE => $this->attributes(),
60
            self::SCENARIO_DEFAULT => $this->attributes(),
61
        ];
62
    }
63
64
    /**
65
     * Labels of all fields.
66
     *
67
     * @inheritdoc
68
     */
69
    public function attributeLabels()
70
    {
71
        $dynamicAttributeLabels = [];
72
        $staticAttributeLabels = [];
73
74
        $translateAttributeLabels = call_user_func([
75
            $this->mainModel->getTranslateModelName(),
0 ignored issues
show
Bug introduced by
The method getTranslateModelName does only exist in Itstructure\AdminModule\models\MultilanguageTrait, but not in yii\db\ActiveRecord.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
76
            'attributeLabels',
77
        ]);
78
79
        foreach ($this->dynamicFields as $fieldConditions) {
80
81
            $fieldName = $fieldConditions['name'];
82
83
            if (array_key_exists($fieldName, $translateAttributeLabels)) {
84
85
                $staticAttributeLabels[$fieldName] = $translateAttributeLabels[$fieldName];
86
87
                foreach ($this->getShortLanguageList() as $language) {
88
                    $dynamicAttributeLabels[$fieldName.'_'.$language] = $translateAttributeLabels[$fieldName];
89
                }
90
            }
91
        }
92
93
        return ArrayHelper::merge(
94
            ArrayHelper::merge(
95
                $dynamicAttributeLabels,
96
                $staticAttributeLabels
97
            ),
98
            $this->mainModel->attributeLabels()
0 ignored issues
show
Bug introduced by
The method attributeLabels does only exist in yii\db\ActiveRecord, but not in Itstructure\AdminModule\models\MultilanguageTrait.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
99
        );
100
    }
101
102
    /**
103
     * Specifies the value of the field.
104
     *
105
     * @param string $name - name of field.
106
     * @param mixed  $value - value to be stored in field.
107
     *
108
     * @return void
109
     */
110
    public function __set($name, $value)
111
    {
112
        $setter = 'set' . $name;
113
        if (method_exists($this, $setter)) {
114
            $this->$setter($value);
115
        } else {
116
            $this->{$name} = $value;
117
        }
118
    }
119
120
    /**
121
     * Gets the value of the field.
122
     *
123
     * @param string $name - field name.
124
     *
125
     * @return mixed
126
     */
127
    public function __get($name)
128
    {
129
        $getter = 'get' . $name;
130
        if (method_exists($this, $getter)) {
131
            return $this->$getter();
132
        }
133
134
        if ($this->mainModel->isNewRecord) {
135
            return $this->{$name} ?? '';
136
        } else {
137
            return $this->mainModel->{$name} ?? '';
138
        }
139
    }
140
141
    /**
142
     * Setter for main model.
143
     *
144
     * @param BaseActiveRecord $mainModel
145
     */
146
    public function setMainModel(BaseActiveRecord $mainModel)
147
    {
148
        $this->mainModel = $mainModel;
149
    }
150
151
    /**
152
     * Getter for main model.
153
     *
154
     * @return mixed
155
     */
156
    public function getMainModel()
157
    {
158
        return $this->mainModel;
159
    }
160
161
    /**
162
     * Attributes along with dynamic and from the basic model.
163
     *
164
     * @return array
165
     */
166
    public function attributes(): array
167
    {
168
        if (method_exists($this->mainModel, 'mainModelAttributes')) {
169
            $mainModelAttributes = call_user_func([
170
                $this->mainModel,
171
                'mainModelAttributes'
172
            ]);
173
        } else {
174
            $mainModelAttributes = $this->mainModel->attributes();
0 ignored issues
show
Bug introduced by
The method attributes does only exist in yii\db\ActiveRecord, but not in Itstructure\AdminModule\models\MultilanguageTrait.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
175
        }
176
177
        return ArrayHelper::merge(
178
            $this->getDynamicAttributes(),
179
            $mainModelAttributes
180
        );
181
    }
182
183
    /**
184
     * Saves data in the main model.
185
     *
186
     * @return bool
187
     */
188
    public function save(): bool
189
    {
190
        if ($this->mainModel->isNewRecord) {
191
            $this->setScenario(ModelInterface::SCENARIO_CREATE);
192
        } else {
193
            $this->setScenario(ModelInterface::SCENARIO_UPDATE);
194
        }
195
196
        if (!$this->validate()){
197
            return false;
198
        }
199
200
        // Transferring attribute values from this model to the main.
201
        foreach ($this->attributes() as $attribute) {
202
203
            $this->mainModel->{$attribute} = $this->{$attribute};
204
        }
205
206
        return $this->mainModel->save();
0 ignored issues
show
Bug introduced by
The method save does only exist in yii\db\ActiveRecord, but not in Itstructure\AdminModule\models\MultilanguageTrait.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
207
    }
208
209
    /**
210
     * Returns the id of the current model.
211
     *
212
     * @return int
213
     */
214
    public function getId()
215
    {
216
        return $this->mainModel->id;
217
    }
218
219
    /**
220
     * Returns an array of all multilanguage attributes.
221
     *
222
     * @return array
223
     */
224
    private function getDynamicAttributes(): array
225
    {
226
        $languageList = $this->getShortLanguageList();
227
        $dynamicAttributes = [];
228
        foreach ($languageList as $language) {
229
            foreach ($this->dynamicFields as $fieldConditions) {
230
                $dynamicAttributes[] = $fieldConditions['name'] . '_' . $language;
231
            }
232
        }
233
        return array_values($dynamicAttributes);
234
    }
235
236
    /**
237
     * Creates validation rules for dynamic fields for all languages.
238
     *
239
     * @return array
240
     */
241
    private function getDynamicValidationRules(): array
242
    {
243
        $rules = [];
244
        foreach ($this->getShortLanguageList() as $language) {
245
            foreach ($this->dynamicFields as $fieldConditions) {
246
247
                $fieldName = $fieldConditions['name'];
248
                $fieldRules = isset($fieldConditions['rules']) ? $fieldConditions['rules'] : [];
249
250
                foreach ($fieldRules as $fieldRule) {
251
252
                    if (in_array('required', $fieldRule) && $language != Language::getDefaultLanguage()->shortName) {
253
                        continue;
254
                    }
255
256
                    if (in_array('unique', $fieldRule)) {
257
                        $fieldRule = ArrayHelper::merge(
258
                            $fieldRule,
259
                            [
260
                                'skipOnError'     => true,
261
                                'targetClass'     => $this->mainModel->getTranslateModelName(),
0 ignored issues
show
Bug introduced by
The method getTranslateModelName does only exist in Itstructure\AdminModule\models\MultilanguageTrait, but not in yii\db\ActiveRecord.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
262
                                'targetAttribute' => [$fieldName . '_' . $language => $fieldName],
263
264
                                'filter' => $this->getScenario() == ModelInterface::SCENARIO_UPDATE ?
265
                                    $this->mainModel->getKeyToMainModel().' != '.$this->id : '',
0 ignored issues
show
Documentation introduced by
The property id does not exist on object<Itstructure\Admin...ilanguageValidateModel>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
Bug introduced by
The method getKeyToMainModel does only exist in Itstructure\AdminModule\models\MultilanguageTrait, but not in yii\db\ActiveRecord.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
266
267
                                'message' => isset($fieldRule['message']) ?
268
                                    $fieldRule['message'] : 'Record with such attribute "{attribute}" already exists'
269
                            ]
270
                        );
271
                    }
272
273
                    $rules[] = ArrayHelper::merge(
274
                        [$fieldName . '_' . $language],
275
                        $fieldRule
276
                    );
277
                }
278
            }
279
        }
280
281
        return $rules;
282
    }
283
284
    /**
285
     * Returns the list of available languages in the short name format.
286
     *
287
     * @return array
288
     */
289
    private function getShortLanguageList(): array
290
    {
291
        return Language::getShortLanguageList();
292
    }
293
}
294