1
|
|
|
<?php |
2
|
|
|
namespace App\Http\Controller; |
3
|
|
|
|
4
|
|
|
use App\Model\Article; |
5
|
|
|
use App\Model\ArticleLike; |
6
|
|
|
use App\Model\StatusInterface; |
7
|
|
|
use yii\data\Pagination; |
8
|
|
|
use yii\helpers\ArrayHelper; |
9
|
|
|
use yii\helpers\HtmlPurifier; |
10
|
|
|
use yii\web\NotFoundHttpException; |
11
|
|
|
|
12
|
|
|
class ArticleController extends Controller |
13
|
|
|
{ |
14
|
|
|
public function afterAction($action, $result) |
15
|
|
|
{ |
16
|
|
|
if ($action->id === 'view') { |
17
|
|
|
$this->model->updateCounters([ |
18
|
|
|
'views' => 1 |
19
|
|
|
]); |
20
|
|
|
} |
21
|
|
|
|
22
|
|
|
return parent::afterAction($action, $result); |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
public function actionIndex() |
26
|
|
|
{ |
27
|
|
|
$query = Article::find() |
28
|
|
|
->alias('a') |
29
|
|
|
->joinWith('category') |
30
|
|
|
->where([ |
31
|
|
|
'a.status' => StatusInterface::STATUS_ACTIVE, |
32
|
|
|
'a.is_deleted' => 0, |
33
|
|
|
]) |
34
|
|
|
->andWhere(['<=', 'a.release_time', time()]) |
35
|
|
|
->orderBy(['a.release_time' => SORT_DESC]); |
36
|
|
|
|
37
|
|
|
$count = $query->count(); |
38
|
|
|
$pagination = new Pagination(['totalCount' => $count]); |
39
|
|
|
|
40
|
|
|
$articles = $query->offset($pagination->offset) |
41
|
|
|
->limit($pagination->limit) |
42
|
|
|
->all(); |
43
|
|
|
|
44
|
|
|
$likes = ArticleLike::find() |
45
|
|
|
->select([ |
46
|
|
|
'article_id', |
47
|
|
|
'count' => 'count(*)' |
48
|
|
|
]) |
49
|
|
|
->where(['IN', 'article_id', array_column($articles, 'id')]) |
50
|
|
|
->groupBy(['article_id']) |
51
|
|
|
->asArray() |
52
|
|
|
->all(); |
53
|
|
|
$likesCount = ArrayHelper::map($likes, 'article_id', 'count'); |
54
|
|
|
|
55
|
|
|
return $this->render('index', [ |
56
|
|
|
'articles' => $articles, |
57
|
|
|
'likesCount' => $likesCount, |
58
|
|
|
'pagination' => $pagination, |
59
|
|
|
]); |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
public function actionView($id) |
63
|
|
|
{ |
64
|
|
|
$model = $this->findModel($id); |
65
|
|
|
|
66
|
|
|
return $this->render('view', [ |
67
|
|
|
'model' => $model, |
68
|
|
|
'content' => HtmlPurifier::process($model->meta->content), |
69
|
|
|
]); |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
/** |
73
|
|
|
* @var Article $model |
74
|
|
|
*/ |
75
|
|
|
private $model; |
76
|
|
|
|
77
|
|
|
private function findModel($id) |
78
|
|
|
{ |
79
|
|
|
$model = Article::findOne($id); |
80
|
|
|
if (!$model) { |
|
|
|
|
81
|
|
|
throw new NotFoundHttpException('Article does not exists'); |
82
|
|
|
} |
83
|
|
|
|
84
|
|
|
$this->model = $model; |
85
|
|
|
return $this->model; |
86
|
|
|
} |
87
|
|
|
|
88
|
|
|
public function actionComments($id) |
89
|
|
|
{ |
90
|
|
|
$comments = ArticleComment::findAll([ |
|
|
|
|
91
|
|
|
'article_id' => $id, |
92
|
|
|
]); |
93
|
|
|
return $this->render('comments', [ |
94
|
|
|
'comments' => $comments, |
95
|
|
|
]); |
96
|
|
|
} |
97
|
|
|
} |
98
|
|
|
|