Passed
Pull Request — master (#210)
by Aleksei
05:21
created

PostRepository   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Test Coverage

Coverage 38.46%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 22
dl 0
loc 53
ccs 10
cts 26
cp 0.3846
rs 10
c 1
b 0
f 0
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 fullPostPage() 0 11 1
A prepareDataReader() 0 3 1
A save() 0 3 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\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