public function __invoke($post_id) { // 检查登录 $session = $this->getSession(); if (empty($session['user'])) { $session->addFlash('error', '请先登录'); return new RedirectResponse($this->generateUrl('user_login')); } $user = UserModel::getUser($session['user']['id']); // 检查帖子是否存在 $post = PostModel::getPost($post_id); if (!$post) { $session->addFlash('error', '帖子不存在'); return new RedirectResponse($this->getRequest()->server->get('HTTP_REFERER')); } // 检查主题 $thread = ThreadModel::getThread($post->threadId); if (!$thread) { $session->addFlash('error', '主题不存在'); return new RedirectResponse($this->generateUrl('forum_board', array('forum_id' => $post->forumId))); } $request = $this->getRequest(); if ($request->getMethod() == 'POST') { $posts = $request->request; $db = ForumDatabase::getInstance(); $db->transaction(); try { $content = $posts->get('content'); $pictures = $posts->get('thumbnails'); if (!$pictures) { $pictures = array(); } else { $pictures = explode('<>', $pictures); } if (empty($content) && empty($pictures)) { throw new \Exception("内容和图片不能都为空"); } $reply = new PostModel(); $reply->threadId = $post->threadId; $reply->forumId = $post->forumId; $reply->replyPostId = $post->postId; $reply->content = $content; $reply->thumbnails = implode('<>', $pictures); $reply->createTimestamp = time(); $reply->authorId = $user->id; $reply->authorName = $user->username; // 保存 PostModel::createPost($reply); // 增加主题回复数 $thread->replies += 1; ThreadModel::saveThread($thread); $db->commit(); } catch (\Exception $e) { $db->rollback(); $session->addFlash('error', $e->getMessage()); } return new RedirectResponse($this->generateUrl('forum_thread_view', array('thread_id' => $post->threadId))); } return $this->render('post/reply.html.twig', array('post' => $post)); }