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