Completed
Push — master ( a449a7...7f0061 )
by Gino
12:11
created

PostsRelationScopeTrait::scopeListFrontend()   B

Complexity

Conditions 6
Paths 16

Size

Total Lines 32
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 32
rs 8.439
c 0
b 0
f 0
cc 6
eloc 17
nc 16
nop 2
1
<?php
2
3
namespace GinoPane\BlogTaxonomy\Models;
4
5
trait PostsRelationScopeTrait
6
{
7
    /**
8
     * @var array
9
     *
10
     * public static $sortingOptions
11
     */
12
13
    /**
14
     * Gets a list of items related to Posts for frontend use
15
     *
16
     * @param       $query
17
     * @param array $options Available options are "sort", "displayEmpty", "limit"
18
     *
19
     * @return mixed
20
     */
21
    public function scopeListFrontend($query, array $options = [])
22
    {
23
        if (in_array($options['sort'], array_keys(self::$sortingOptions))) {
24
            if ($options['sort'] == 'random') {
25
                $query->inRandomOrder();
26
            } else {
27
                list($sortField, $sortDirection) = explode(' ', $options['sort']);
28
29
                if ($sortField == 'posts_count') {
30
                    $query->withCount('posts');
31
                }
32
33
                $query->orderBy($sortField, $sortDirection);
34
            }
35
        }
36
37
        if (empty($options['displayEmpty'])) {
38
            $query->has('posts');
39
        }
40
41
        // Limit the number of results
42
        if (!empty($options['limit'])) {
43
            $query->take($options['limit']);
44
        }
45
46
        return $query->with([
47
                'posts' => function($query){
48
                    $query->isPublished();
49
                }
50
            ]
51
        )->get();
52
    }
53
}