|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace App\Blog\Post; |
|
4
|
|
|
|
|
5
|
|
|
use App\Blog\Entity\Post; |
|
6
|
|
|
use Cycle\ORM\ORMInterface; |
|
7
|
|
|
use Cycle\ORM\Select; |
|
8
|
|
|
use Cycle\ORM\Transaction; |
|
9
|
|
|
use Yiisoft\Data\Reader\DataReaderInterface; |
|
10
|
|
|
use Yiisoft\Data\Reader\Sort; |
|
11
|
|
|
use Yiisoft\Yii\Cycle\DataReader\SelectDataReader; |
|
12
|
|
|
use Throwable; |
|
13
|
|
|
|
|
14
|
|
|
final class PostRepository extends Select\Repository |
|
15
|
|
|
{ |
|
16
|
|
|
private ORMInterface $orm; |
|
17
|
|
|
|
|
18
|
|
|
public function __construct(Select $select, ORMInterface $orm) |
|
19
|
|
|
{ |
|
20
|
|
|
$this->orm = $orm; |
|
21
|
|
|
parent::__construct($select); |
|
22
|
|
|
} |
|
23
|
|
|
|
|
24
|
|
|
/** |
|
25
|
|
|
* Get posts without filter with preloaded Users and Tags |
|
26
|
|
|
*/ |
|
27
|
|
|
public function findAllPreloaded(): DataReaderInterface |
|
28
|
|
|
{ |
|
29
|
|
|
$query = $this->select() |
|
30
|
|
|
->load(['user', 'tags']); |
|
31
|
|
|
return $this->prepareDataReader($query); |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
public function findByTag($tagId): DataReaderInterface |
|
35
|
|
|
{ |
|
36
|
|
|
$query = $this |
|
37
|
|
|
->select() |
|
38
|
|
|
->where(['tags.id' => $tagId]) |
|
39
|
|
|
->load('user', ['method' => Select::SINGLE_QUERY]); |
|
40
|
|
|
return $this->prepareDataReader($query); |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
public function fullPostPage(string $slug): ?Post |
|
44
|
|
|
{ |
|
45
|
|
|
$query = $this |
|
46
|
|
|
->select() |
|
47
|
|
|
->where(['slug' => $slug]) |
|
48
|
|
|
->load('user', ['method' => Select::SINGLE_QUERY]) |
|
49
|
|
|
->load(['tags']) |
|
50
|
|
|
// force loading in single query with comments |
|
51
|
|
|
->load('comments.user', ['method' => Select::SINGLE_QUERY]) |
|
52
|
|
|
->load('comments', ['method' => Select::OUTER_QUERY]); |
|
53
|
|
|
/** @var null|Post $post */ |
|
54
|
|
|
$post = $query->fetchOne(); |
|
55
|
|
|
return $post; |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
/** |
|
59
|
|
|
* @param Post $post |
|
60
|
|
|
* @throws Throwable |
|
61
|
|
|
*/ |
|
62
|
|
|
public function save(Post $post): void |
|
63
|
|
|
{ |
|
64
|
|
|
$transaction = new Transaction($this->orm); |
|
65
|
|
|
$transaction->persist($post); |
|
66
|
|
|
$transaction->run(); |
|
67
|
|
|
} |
|
68
|
|
|
|
|
69
|
|
|
private function prepareDataReader($query): SelectDataReader |
|
70
|
|
|
{ |
|
71
|
|
|
return (new SelectDataReader($query))->withSort((new Sort([]))->withOrder(['published_at' => 'desc'])); |
|
72
|
|
|
} |
|
73
|
|
|
} |
|
74
|
|
|
|