-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathArticleService.php
More file actions
78 lines (68 loc) · 2.03 KB
/
ArticleService.php
File metadata and controls
78 lines (68 loc) · 2.03 KB
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
<?php
namespace App\Service;
use App\Entity\Article;
use App\Entity\PostCount;
use App\Repository\ArticleRepository;
use App\Repository\PostCountRepository;
use DateTime;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\ORMException;
use Throwable;
class ArticleService
{
/** @var EntityManagerInterface */
private $entityManager;
/** @var ArticleRepository */
private $articleRepository;
/** @var PostCountRepository */
private $postCountRepository;
/**
* ArticleService constructor.
* @param EntityManagerInterface $entityManager
* @param ArticleRepository $articleRepository
* @param PostCountRepository $postCountRepository
*/
public function __construct(EntityManagerInterface $entityManager, ArticleRepository $articleRepository, PostCountRepository $postCountRepository)
{
$this->entityManager = $entityManager;
$this->articleRepository = $articleRepository;
$this->postCountRepository = $postCountRepository;
}
/**
* @return Article[]
*/
public function getList()
{
return $this->articleRepository->findAll();
}
/**
* @param Article $article
* @throws Throwable
*/
public function add(Article $article)
{
$this->entityManager->transactional(function () use ($article) {
$this->articleRepository->add($article);
$today = new DateTime();
$postCount = $this->getPostCountOrCreate($today);
$postCount->incrementPostCount();
});
}
/**
* @param DateTime $dateTime
* @return PostCount|null
* @throws ORMException
*/
private function getPostCountOrCreate(DateTime $dateTime)
{
$postCount = $this->postCountRepository->findOneBy([
'postDate' => $dateTime,
]);
if (empty($postCount)) {
$postCount = new PostCount();
$postCount->setPostDate($dateTime);
$this->postCountRepository->add($postCount);
}
return $postCount;
}
}