Passed
Push — master ( f7299d...2397c6 )
by Stephen
01:10 queued 11s
created

RandomModelAttributeQuery::execute()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 5
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 7
rs 10
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
     * RandomModelAttributeQuery constructor.
22
     *
23
     * @param string $modelClass
24
     * @param string $attribute
25
     */
26
    public function __construct(string $modelClass, string $attribute)
27
    {
28
        $this->modelClass = $modelClass;
29
        $this->attribute = $attribute;
30
    }
31
32
    /**
33
     * Retrieve a Query builder.
34
     *
35
     * @return Builder
36
     */
37
    protected function builder(): Builder
38
    {
39
        return $this->modelClass::query();
40
    }
41
42
    /**
43
     * Retrieve a random model attribute from all of the model records.
44
     *
45
     * @return mixed
46
     */
47
    public function execute()
48
    {
49
        return $this->builder()
50
            ->get($this->attribute)
51
            ->shuffle()
52
            ->first()
53
            ->{$this->attribute};
54
    }
55
}
56