Passed
Push — master ( d34604...ab5002 )
by Alexander
02:20
created

VoteForm::checkModel()   C

Complexity

Conditions 7
Paths 12

Size

Total Lines 24
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 24
rs 6.7272
cc 7
eloc 16
nc 12
nop 0
1
<?php
2
3
namespace hauntd\vote\models;
4
5
use Yii;
6
use yii\base\Model;
7
use hauntd\vote\traits\ModuleTrait;
8
use hauntd\vote\Module;
9
10
/**
11
 * @author Alexander Kononenko <[email protected]>
12
 * @package hauntd\vote\models
13
 */
14
class VoteForm extends Model
15
{
16
    use ModuleTrait;
17
18
    const ACTION_POSITIVE = 'positive';
19
    const ACTION_NEGATIVE = 'negative';
20
    const ACTION_TOGGLE = 'toggle';
21
22
    /**
23
     * @var string entity (e.g. "user.like" or "page.voting")
24
     */
25
    public $entity;
26
27
    /**
28
     * @var integer target model id
29
     */
30
    public $targetId;
31
32
    /**
33
     * @var string +/-?
34
     */
35
    public $action;
36
37
    /**
38
     * @return array
39
     * @throws \yii\base\InvalidConfigException
40
     */
41
    public function rules()
42
    {
43
        return [
44
            [['entity', 'targetId', 'action'], 'required'],
45
            ['targetId', 'integer'],
46
            ['action', 'in', 'range' => [self::ACTION_NEGATIVE, self::ACTION_POSITIVE, self::ACTION_TOGGLE]],
47
            ['entity', 'checkModel'],
48
        ];
49
    }
50
51
    /**
52
     * @return int
53
     */
54
    public function getValue()
55
    {
56
        return $this->action == self::ACTION_NEGATIVE ? Vote::VOTE_NEGATIVE : Vote::VOTE_POSITIVE;
57
    }
58
59
    /**
60
     * @return bool
61
     * @throws \yii\base\InvalidConfigException
62
     */
63
    public function checkModel()
64
    {
65
        $module = $this->getModule();
66
        $settings = $module->getSettingsForEntity($this->entity);
67
        $allowGuests = isset($settings['allowGuests']) ? $settings['allowGuests'] : false;
68
69
        if ($settings == null) {
70
            $this->addError('entity', Yii::t('vote', 'This entity is not supported.'));
71
            return false;
72
        }
73
        if (Yii::$app->user->isGuest) {
74
            if ($settings['type'] == Module::TYPE_TOGGLE || !$allowGuests) {
75
                $this->addError('entity', Yii::t('vote', 'Guests are not allowed for this voting.'));
76
                return false;
77
            }
78
        }
79
        $targetModel = Yii::createObject($settings['modelName']);
80
        if ($targetModel->findOne(['id' => $this->targetId]) == null) {
81
            $this->addError('targetId', Yii::t('vote', 'Target model not found.'));
82
            return false;
83
        }
84
85
        return true;
86
    }
87
}
88