Completed
Push — develop ( 35ebd6...f6916d )
by Mohamed
13:11 queued 06:49
created

CountAttributeTrait::getCountAttribute()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 12
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 3.3332

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 12
ccs 4
cts 6
cp 0.6667
rs 9.4285
cc 3
eloc 5
nc 4
nop 1
crap 3.3332
1
<?php
2
3
/*
4
 * This file is part of the Tinyissue package.
5
 *
6
 * (c) Mohamed Alsharaf <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Tinyissue\Model\Traits;
13
14
/**
15
 * CountAttributeTrait is trait class for adding method to return count attribute.
16
 *
17
 * @author Mohamed Alsharaf <[email protected]>
18
 *
19
 * @property array $relations
20
 *
21
 * @method \Illuminate\Database\Eloquent\Model load($relations)
22
 * @method \Illuminate\Database\Eloquent\Model getRelation($relation)
23
 */
24
trait CountAttributeTrait
25
{
26
    /**
27
     * Returns the aggregate value of a field.
28
     *
29
     * @param string $field
30
     *
31
     * @return int
32
     */
33 8
    protected function getCountAttribute($field)
34
    {
35
        // if relation is not loaded already, let's do it first
36 8
        if (!array_key_exists($field, $this->relations)) {
37
            $this->load($field);
38
        }
39
40 8
        $related = $this->getRelation($field);
41
42
        // then return the count directly
43 8
        return ($related) ? (int) $related->aggregate : 0;
44
    }
45
}
46