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

RandomModelAttributeQuery   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 11
c 1
b 0
f 0
dl 0
loc 46
rs 10
wmc 3

3 Methods

Rating   Name   Duplication   Size   Complexity  
A execute() 0 7 1
A __construct() 0 4 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
     * 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