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