aboutsummaryrefslogtreecommitdiffhomepage
path: root/api/Posts/Repositories/PostRepository.php
blob: 1f035b766a7a45df5fdf89e1c2eddd24cb9f83d5 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<?php

namespace Api\Posts\Repositories;

use Api\Posts\Models\Post;
use Infrastructure\Database\Eloquent\Repository;

class PostRepository extends Repository
{
    public function getModel()
    {
        return new Post();
    }

    public function getJoined($options)
    {
        $query = Post::query()->with('user')->with('post_type');
        $this->applyResourceOptions($query, $options);
        $posts = $query->get();
        $joinedPosts = [];

        foreach ($posts as $post) {
            $postType = 'Api\Posts\Models\\' . $post["post_type"]["type"] . 'Post';
            $postTypeClass = new $postType();
            $post["post"] = $postTypeClass::query()->where('id', $post->id)->first();
            array_push($joinedPosts, $post);
        }
        return $joinedPosts;
    }

    public function getJoinedById($postId)
    {
        $query = Post::query()->with('user')->with('post_type')->where('id', $postId);
        $post = $query->first();

        $postType = 'Api\Posts\Models\\' . $post["post_type"]["type"] . 'Post';
        $postTypeClass = new $postType();
        $post["post"] = $postTypeClass::query()->where('id', $post["id"])->first();
        return $post;
    }

    public function create(array $data)
    {
        $post = $this->getModel();

        $post->fill($data);
        $post->save();

        return $post;
    }

    public function update(Post $post, array $data)
    {
        $post->fill($data);

        $post->save();

        return $post;
    }
}