PostRepository::fullPostPage()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 8
nc 1
nop 1
dl 0
loc 11
ccs 0
cts 8
cp 0
crap 2
rs 10
c 0
b 0
f 0
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
     * @psalm-return DataReaderInterface<int, Post>
29
     */
30 1
    public function findAllPreloaded(): DataReaderInterface
31
    {
32 1
        $query = $this->select()
33 1
            ->load(['user', 'tags']);
34 1
        return $this->prepareDataReader($query);
35
    }
36
37
    /**
38
     * @psalm-return DataReaderInterface<int, Post>
39
     */
40
    public function findByTag($tagId): DataReaderInterface
41
    {
42
        $query = $this
43
            ->select()
44
            ->where(['tags.id' => $tagId])
45
            ->load('user', ['method' => Select::SINGLE_QUERY]);
46
        return $this->prepareDataReader($query);
47
    }
48
49
    public function fullPostPage(string $slug): ?Post
50
    {
51
        $query = $this
52
            ->select()
53
            ->where(['slug' => $slug])
54
            ->load('user', ['method' => Select::SINGLE_QUERY])
55
            ->load(['tags'])
56
            // force loading in single query with comments
57
            ->load('comments.user', ['method' => Select::SINGLE_QUERY])
58
            ->load('comments', ['method' => Select::OUTER_QUERY]);
59
        return  $query->fetchOne();
60
    }
61
62
    /**
63
     * @throws Throwable
64
     */
65
    public function save(Post $post): void
66
    {
67
        $this->entityWriter->write([$post]);
68
    }
69
70 1
    private function prepareDataReader($query): EntityReader
71
    {
72 1
        return (new EntityReader($query))->withSort(
73 1
            Sort::only(['id', 'title', 'public', 'updated_at', 'published_at', 'user_id'])
74 1
                ->withOrder(['published_at' => 'desc'])
75
        );
76
    }
77
}
78