105 lines
2.6 KiB
PHP
105 lines
2.6 KiB
PHP
<?php
|
|
|
|
namespace app\controllers;
|
|
|
|
use app\models\Comment;
|
|
use app\models\CommentEditForm;
|
|
use app\models\CommentNewForm;
|
|
use Yii;
|
|
use yii\web\Controller;
|
|
use yii\filters\AccessControl;
|
|
use yii\filters\VerbFilter;
|
|
use yii\web\Request;
|
|
|
|
class CommentsController extends Controller
|
|
{
|
|
public function behaviors()
|
|
{
|
|
return [
|
|
'access' => [
|
|
'class' => AccessControl::class,
|
|
],
|
|
'verbs' => [
|
|
'class' => VerbFilter::class,
|
|
'actions' => [
|
|
'post' => ['POST'],
|
|
'edit' => ['POST'],
|
|
'delete' => ['DELETE']
|
|
]
|
|
]
|
|
];
|
|
}
|
|
|
|
public function actionPost(Request $request)
|
|
{
|
|
if (!$request->isPost) {
|
|
return false;
|
|
}
|
|
if (Yii::$app->user->id === null) {
|
|
return false;
|
|
}
|
|
|
|
$data = $request->post();
|
|
$form = new CommentNewForm();
|
|
$form->load([ ...$data, 'user_id' => Yii::$app->user->id ]);
|
|
if ($form->validate()) {
|
|
if ($form->create()) {
|
|
return true;
|
|
}
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
public function actionEdit(Request $request)
|
|
{
|
|
if (!$request->isPost) {
|
|
return false;
|
|
}
|
|
if (Yii::$app->user->id === null) {
|
|
return false;
|
|
}
|
|
|
|
$data = $request->post();
|
|
$form = new CommentEditForm();
|
|
$form->load([ ...$data, 'user_id' => Yii::$app->user->id ]);
|
|
if ($form->validate()) {
|
|
if ($form->edit()) {
|
|
return true;
|
|
}
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
public function actionDelete(Request $request)
|
|
{
|
|
/*
|
|
Можно конечно поспорить что в этом месте лучше
|
|
в модель это запихнуть, но мне кажется что это
|
|
какой-то абсурд для такого маленького кол-ва
|
|
данных
|
|
*/
|
|
|
|
if (!$request->isDelete) {
|
|
return false;
|
|
}
|
|
if (Yii::$app->user->id === null) {
|
|
return false;
|
|
}
|
|
if ($request->getQueryParam('id') === null) {
|
|
return false;
|
|
}
|
|
|
|
$comment = Comment::findOne([ 'id' => $request->getQueryParam('id') ]);
|
|
if ($comment === null) {
|
|
return false;
|
|
}
|
|
if ($comment->user_id !== Yii::$app->user->id) {
|
|
return false;
|
|
}
|
|
|
|
return $comment->delete();
|
|
}
|
|
}
|