Widget::run()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 11
rs 9.9
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
namespace maxmirazh33\file;
4
5
use yii\base\InvalidConfigException;
6
use yii\widgets\InputWidget;
7
use Yii;
8
9
/**
10
 * Class for uploadable file widget
11
 *
12
 * Usage:
13
 * ```
14
 * ...
15
 * echo $form->field($model, 'file')->widget('maxmirazh33\file\Widget');
16
 * ...
17
 * ```
18
 */
19
class Widget extends InputWidget
20
{
21
    /**
22
     * @inheritdoc
23
     */
24
    public function init()
25
    {
26
        if (!$this->hasModel() && $this->name === null) {
27
            throw new InvalidConfigException("'model' and 'attribute' properties must be specified.");
28
        }
29
        parent::init();
30
31
        $this->registerTranslations();
32
    }
33
34
    /**
35
     * Register widget translations.
36
     */
37
    public function registerTranslations()
38
    {
39
        if (!isset(Yii::$app->i18n->translations['maxmirazh33/file']) && !isset(Yii::$app->i18n->translations['maxmirazh33/*'])) {
40
            Yii::$app->i18n->translations['maxmirazh33/file'] = [
41
                'class' => 'yii\i18n\PhpMessageSource',
42
                'basePath' => '@maxmirazh33/file/messages',
43
                'fileMap' => [
44
                    'maxmirazh33/file' => 'file.php'
45
                ],
46
                'forceTranslation' => true
47
            ];
48
        }
49
    }
50
51
    /**
52
     * @inheritdoc
53
     */
54
    public function run()
55
    {
56
        return $this->render(
57
            'view',
58
            [
59
                'selector' => $this->getSelector(),
60
                'model' => $this->model,
61
                'attribute' => $this->attribute,
62
            ]
63
        );
64
    }
65
66
    /**
67
     * @return string Widget selector
68
     * @throws \ReflectionException
69
     */
70
    public function getSelector()
71
    {
72
        $object = new \ReflectionClass($this->model);
73
        return mb_strtolower($object->getShortName()) . '-' . $this->attribute;
74
    }
75
}
76