Passed
Pull Request — master (#178)
by Alexander
04:31
created

PostRepository   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Test Coverage

Coverage 35.7%

Importance

Changes 0
Metric Value
eloc 24
c 0
b 0
f 0
dl 0
loc 58
ccs 10
cts 28
cp 0.357
rs 10
wmc 6

6 Methods

Rating   Name   Duplication   Size   Complexity  
A findAllPreloaded() 0 5 1
A __construct() 0 4 1
A findByTag() 0 7 1
A prepareDataReader() 0 3 1
A save() 0 5 1
A fullPostPage() 0 12 1
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