Passed
Pull Request — master (#49)
by
unknown
17:14 queued 02:12
created

PostRepository::prepareDataReader()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
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, ?string $userId = null): ?Post
39
    {
40
        $query = $this
41
            ->select()
42
            ->where(['slug' => $slug])
43
            ->load('user', [
44
                'method' => Select::SINGLE_QUERY,
45
            ])
46
            ->load('tags', [
47
                'method' => Select::OUTER_QUERY,
48
            ])
49
            // force loading in single query with comments
50
            ->load('comments.user', ['method' => Select::SINGLE_QUERY])
51
            ->load('comments', [
52
                'method' => Select::OUTER_QUERY,
53
                // not works (default Constraint would not be replaced):
54
                'load' => new PublicScope($userId === null ? null : ['user_id' => $userId]),
55
            ]);
56
        /** @var null|Post $post */
57
        $post = $query->fetchOne();
58
        // /** @var Select\Repository $commentRepo */
59
        // $commentRepo = $this->orm->getRepository(Comment::class);
60
        // $commentRepo->select()->load('user')->where('post_id', $post->getId())->fetchAll();
61
        return $post;
62
    }
63
64
    private function prepareDataReader($query): SelectDataReader
65
    {
66
        return (new SelectDataReader($query))->withSort((new Sort([]))->withOrder(['published_at' => 'desc']));
67
    }
68
}
69