CountAttributeTrait::getCountAttribute()   A
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 12
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 3.072

Importance

Changes 0
Metric Value
dl 0
loc 12
c 0
b 0
f 0
ccs 4
cts 5
cp 0.8
rs 9.4285
cc 3
eloc 5
nc 4
nop 1
crap 3.072
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 static $this
20
 */
21
trait CountAttributeTrait
22
{
23
    /**
24
     * Returns the aggregate value of a field.
25
     *
26
     * @param string $field
27
     *
28
     * @return int
29
     */
30 8
    protected function getCountAttribute($field)
31
    {
32
        // if relation is not loaded already, let's do it first
33 8
        if (!array_key_exists($field, $this->relations)) {
0 ignored issues
show
Bug introduced by
The property relations does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
34
            $this->load($field);
35
        }
36
37 8
        $related = $this->getRelation($field);
38
39
        // then return the count directly
40 8
        return ($related) ? (int) $related->aggregate : 0;
41
    }
42
43
    /**
44
     * Eager load relations on the model.
45
     *
46
     * @param array|string $relations
47
     *
48
     * @return $this
49
     */
50
    abstract public function load($relations);
51
52
    /**
53
     * Get a specified relationship.
54
     *
55
     * @param string $relation
56
     *
57
     * @return mixed
58
     */
59
    abstract public function getRelation($relation);
60
}
61