RandomModelAttributeQuery   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 18
c 2
b 0
f 0
dl 0
loc 62
rs 10
wmc 4

3 Methods

Rating   Name   Duplication   Size   Complexity  
A execute() 0 16 2
A __construct() 0 5 1
A builder() 0 3 1
1
<?php
2
3
namespace Sfneal\Queries;
4
5
use Illuminate\Database\Eloquent\Builder;
6
use Illuminate\Database\Eloquent\Model;
7
8
class RandomModelAttributeQuery extends Query
9
{
10
    /**
11
     * @var Model|string
12
     */
13
    private $modelClass;
14
15
    /**
16
     * @var string
17
     */
18
    private $attribute;
19
20
    /**
21
     * @var int
22
     */
23
    private $take;
24
25
    /**
26
     * RandomModelAttributeQuery constructor.
27
     *
28
     * @param  string  $modelClass
29
     * @param  string  $attribute
30
     * @param  int  $take
31
     */
32
    public function __construct(string $modelClass, string $attribute, int $take = 1)
33
    {
34
        $this->modelClass = $modelClass;
35
        $this->attribute = $attribute;
36
        $this->take = $take;
37
    }
38
39
    /**
40
     * Retrieve a Query builder.
41
     *
42
     * @return Builder
43
     */
44
    protected function builder(): Builder
45
    {
46
        return $this->modelClass::query();
47
    }
48
49
    /**
50
     * Retrieve a random model attribute from all of the model records.
51
     *
52
     * @return mixed
53
     */
54
    public function execute()
55
    {
56
        $attributes = $this->builder()
57
            ->distinct()
58
            ->get($this->attribute)
59
            ->shuffle()
60
            ->take($this->take)
61
            ->pluck($this->attribute);
62
63
        // Return a single attribute
64
        if ($attributes->count() == 1) {
65
            return $attributes->first();
66
        }
67
        // Return an array of attributes if more than '1' is being taken
68
        else {
69
            return $attributes->toArray();
70
        }
71
    }
72
}
73