forked from onmotion/yii2-survey
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Survey.php
109 lines (89 loc) · 2.88 KB
/
Survey.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
<?php
/**
* Created by PhpStorm.
* User: kozhevnikov
* Date: 26/10/2017
* Time: 10:09
*/
namespace onmotion\survey;
use onmotion\survey\models\SurveyStat;
use yii\db\Exception;
use yii\db\Expression;
use yii\web\ForbiddenHttpException;
use yii\web\NotFoundHttpException;
class Survey extends \yii\base\Widget
{
public $surveyId = null;
public function init()
{
// set up i8n
if (empty(\Yii::$app->i18n->translations['survey'])) {
\Yii::$app->i18n->translations['survey'] = [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '@surveyRoot/messages',
];
}
\Yii::setAlias('@surveyRoot', __DIR__);
parent::init();
}
public function getViewPath()
{
return \Yii::getAlias('@surveyRoot/views');
}
public function beforeRun()
{
// $assignedModel = SurveyStat::getAssignedUserStat(\Yii::$app->user->getId(), $this->surveyId);
// if (empty($assignedModel)) {
// throw new ForbiddenHttpException();
// }
return parent::beforeRun();
}
public function run()
{
$view = $this->getView();
SurveyWidgetAsset::register($view);
$survey = $this->findModel($this->surveyId);
if (!$survey || !$survey->isAccessibleByCurrentUser) {
return $this->renderUnavailable();
}
$status = $survey->getStatus();
if ($status !== 'active') {
return $this->renderClosed();
}
$assignedModel = SurveyStat::getAssignedUserStat(\Yii::$app->user->getId(), $this->surveyId);
if (empty($assignedModel)) {
SurveyStat::assignUser(\Yii::$app->user->getId(), $this->surveyId);
$assignedModel = SurveyStat::getAssignedUserStat(\Yii::$app->user->getId(), $this->surveyId);
} else {
// if ($assignedModel->survey_stat_is_done){
// return $this->renderClosed();
// }
}
if ($assignedModel->survey_stat_started_at === null) {
$assignedModel->survey_stat_started_at = new Expression('NOW()');
$assignedModel->save(false);
}
return $this->renderSurvey($this->surveyId, $assignedModel);
}
private function renderClosed()
{
echo $this->render('widget/default/closed');
}
private function renderUnavailable()
{
echo $this->render('widget/default/unavailable');
}
private function renderSurvey($id, $stat)
{
$survey = $this->findModel($id);
echo $this->render('widget/default/index', ['survey' => $survey, 'stat' => $stat]);
}
protected function findModel($id)
{
if (($model = \onmotion\survey\models\Survey::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}