Skip to content

Commit

Permalink
Merge pull request #23 from pashaapsky/dev
Browse files Browse the repository at this point in the history
Dev
  • Loading branch information
pashaapsky authored Oct 20, 2020
2 parents 533a06b + c3fcfb2 commit 88c699a
Show file tree
Hide file tree
Showing 56 changed files with 1,748 additions and 330 deletions.
20 changes: 20 additions & 0 deletions app/Comment.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

namespace App;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
use HasFactory;

protected $table = 'comments';

protected $guarded = [''];

public function commentable()
{
return $this->morphTo();
}
}
20 changes: 20 additions & 0 deletions app/Events/PostUpdated.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

namespace App\Events;

use App\Post;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class PostUpdated
{
use Dispatchable, InteractsWithSockets, SerializesModels;

public Post $post;

public function __construct(Post $post)
{
$this->post = $post;
}
}
15 changes: 15 additions & 0 deletions app/History.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

namespace App;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class History extends Model
{
use HasFactory;

protected $table = 'histories';

protected $guarded = [''];
}
7 changes: 6 additions & 1 deletion app/Http/Controllers/AdministrationController.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@

namespace App\Http\Controllers;

use App\News;
use App\Post;
use Illuminate\Http\Request;

class AdministrationController extends Controller
{
Expand All @@ -20,4 +20,9 @@ public function posts() {
$posts = Post::with('tags')->latest()->get();
return view('/admin.posts', compact('posts'));
}

public function news() {
$news = News::latest()->get();
return view('/admin.news', compact('news'));
}
}
46 changes: 46 additions & 0 deletions app/Http/Controllers/CommentsController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?php

namespace App\Http\Controllers;

use App\Comment;
use App\News;
use App\Post;
use Illuminate\Http\Request;

class CommentsController extends Controller
{
public function newsCommentStore(Request $request, News $new)
{
$values = $request->validate([
'text' => 'required'
]);

$new->comments()->create($values);

flash('Comment create successfully');

return back();
}

public function postsCommentStore(Request $request, Post $post)
{
$values = $request->validate([
'text' => 'required'
]);

$post->comments()->create($values);

flash('Comment create successfully');

return back();
}

public function destroy(Comment $comment)
{
$comment->delete();

flash('Comment delete successfully');

return back();
}
}
93 changes: 93 additions & 0 deletions app/Http/Controllers/NewsController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
<?php

namespace App\Http\Controllers;

use App\News;
use App\NewTag;
use App\Services\TagsCreatorService;
use App\Tag;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class NewsController extends Controller
{
public function __construct()
{
$this->middleware('auth');
$this->middleware('role:admin')->except(['index', 'show']);
}

public function validateRequest($request, $new)
{
return $request->validate([
'name' => ['required', 'max:100', Rule::unique('news')->ignore($new->id)],
'text' => 'required'
]);
}

public function index()
{
$news = News::with(['tags', 'comments'])->latest()->get();

return view('news.index', compact('news'));
}

public function create()
{
return view('news.create');
}

public function store(Request $request)
{
$values = $this->validateRequest($request, new News());

$new = News::create($values);

if (!is_null($request['tags'])) {
$requestTags = explode(', ', $request['tags']);
foreach ($requestTags as $tag) {
$tag = Tag::firstOrCreate(['name' => $tag]);
$new->tags()->attach($tag);
}
}

flash('New created successfully');

return back();
}

public function show(News $new)
{
return view('news.show', compact('new'));
}

public function edit(News $new)
{
return view('news.edit', compact('new'));
}

public function update(Request $request, News $new)
{
$values = $this->validateRequest($request, $new);

$new->update($values);

$updater = new TagsCreatorService($new, $request);
$updater->updateTags();

// updateTags($new, $request);

flash( 'New updated successfully');

return back();
}

public function destroy(News $new)
{
$new->delete();

flash( 'New deleted successfully');

return redirect('/admin/news');
}
}
42 changes: 10 additions & 32 deletions app/Http/Controllers/PostsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use App\Notifications\PostEdited;
use App\Post;
use App\PostTag;
use App\Services\TagsCreatorService;
use App\Tag;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
Expand All @@ -30,13 +31,7 @@ public function validateRequest($request, $post)

public function index()
{
$posts = Post::with('tags')->where('published', 1)->latest()->get();
return view('/index', compact('posts'));
}

public function userPosts()
{
$posts = auth()->user()->posts()->with('tags')->latest()->get();
$posts = auth()->user()->posts()->with(['tags', 'comments'])->latest()->get();
return view('/posts.index', compact('posts'));
}

Expand Down Expand Up @@ -96,31 +91,10 @@ public function update(Request $request, Post $post)

$post->update($values);

$postTags = $post->tags->keyBy('name');

if (!is_null($request['tags'])) {
$requestTags = collect(explode(', ', $request['tags']))->keyBy(function ($item) { return $item; });
} else {
$requestTags = collect([]);
}

$deleteTags = $postTags->diffKeys($requestTags);
$addTags = $requestTags->diffKeys($postTags);
$updater = new TagsCreatorService($post, $request);
$updater->updateTags();

if ($addTags->isNotEmpty()) {
foreach ($addTags as $tag) {
$tag = Tag::firstOrCreate(['name' => $tag]);
$post->tags()->attach($tag);
};
}

if ($deleteTags->isNotEmpty()) {
foreach ($deleteTags as $tag) {
$post->tags()->detach($tag);
$isLastTag = PostTag::where('tag_id', $tag->id)->first();
if (!$isLastTag) $tag->delete();
};
}
// updateTags($post, $request);

sendMailNotifyToAdmin(new PostEdited($post));
flash( 'Post edited successfully');
Expand All @@ -139,6 +113,10 @@ public function destroy(Post $post)
flash( 'Post deleted successfully');
pushNotification('Post deleted successfully', 'New Notification');

return back();
if (auth()->user()->hasRole('admin')) {
return redirect('/admin/posts');
} else {
return back();
}
}
}
48 changes: 47 additions & 1 deletion app/Http/Controllers/StaticPagesController.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,61 @@

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Services\StatisticService;

class StaticPagesController extends Controller
{
protected $statisticService;

public function __construct(StatisticService $statisticService)
{
$this->statisticService = $statisticService;
}

public function contactsIndex() {
return view('static.contacts');
}

public function aboutIndex() {
return view('static.about');
}

public function statisticsIndex() {
//Общее количество статей
$postsCount = $this->statisticService->getPostsCount();

//Общее количество новостей
$newsCount = $this->statisticService->getNewsCount();

//ФИО автора, у которого больше всего статей на сайте
$userWithMostPosts = $this->statisticService->getUserWithMaxPosts();

//Самая длинная статья - название, ссылка на статью и длина статьи в символах
$theLongestPost = $this->statisticService->getTheLongestPost();

//Самая короткая статья - название, ссылка на статью и длина статьи в символах
$theShortestPost = $this->statisticService->getTheShortestPost();

//Средние количество статей у “активных” пользователей, при этом активным пользователь считается, если у него есть более 1-й статьи
$avgPostsHaveActiveUsers = $this->statisticService->getAveragePosts();

//Самая непостоянная - название, ссылка на статью, которую меняли больше всего раз
$mostChangingPost = $this->statisticService->getMostChangingPost();

//Самая обсуждаемая статья - название, ссылка на статью, у которой больше всего комментариев.
$mostCommentPost = $this->statisticService->getMostCommentPost();

$statistics = [
'posts_count' => $postsCount,
'news_count' => $newsCount,
'user_with_most_posts' => $userWithMostPosts,
'the_longest_post' => $theLongestPost,
'the_shortest_post' => $theShortestPost,
'avg_posts_have_active_users' => $avgPostsHaveActiveUsers,
'most_changing_post' => $mostChangingPost,
'most_comment_post' => $mostCommentPost
];

return view('static.statistics', ['statistics' => $statistics]);
}
}
3 changes: 2 additions & 1 deletion app/Http/Controllers/TagsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ class TagsController extends Controller
public function index(Tag $tag)
{
$posts = $tag->posts()->with('tags')->get();
return view('index', compact('posts'));
$news = $tag->news()->with('tags')->get();
return view('layouts.tags.index', compact('posts', 'news'));
}
}
37 changes: 37 additions & 0 deletions app/Listeners/AddHistoryOnUpdatePost.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<?php

namespace App\Listeners;

use App\Events\PostUpdated;

class AddHistoryOnUpdatePost
{
public function __construct()
{

}

public function handle(PostUpdated $event)
{
$result = '';

$dirtyValues = $event->post->getChanges();
$freshValues = $event->post->getOriginal();
unset($dirtyValues['updated_at']);

if ($dirtyValues['published'] === true && $freshValues['published'] === 1) {
unset($dirtyValues['published']);
}

foreach ($dirtyValues as $key => $field) {
$result .= 'Изменено поле: "' . $key . '". Было: "' . $freshValues[$key] . '". Стало: "' . $field . '"' . PHP_EOL;
}

$values = [
'user_email' => auth()->user()->email,
'text' => $result
];

$event->post->history()->create($values);
}
}
Loading

0 comments on commit 88c699a

Please sign in to comment.