Passed
Push — master ( 0e3a8a...c79287 )
by Alexander
07:06 queued 02:16
created

PostRepository::fullPostPage()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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