Completed
Push — master ( 98f154...86f929 )
by Timo
04:06
created

Relation::getValue()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 5
cts 5
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 2
crap 2
1
<?php
2
3
namespace hamburgscleanest\DataTables\Models;
4
5
use Illuminate\Support\Collection;
6
7
8
/**
9
 * Class Relation
10
 * @package hamburgscleanest\hamburgscleanest\DataTables\Models
11
 */
12
class Relation {
13
14
    /** @var string */
15
    public $name;
16
17
    /** @var string */
18
    public $aggregate = 'first';
19
20
    /**
21
     * Relation constructor.
22
     * @param string $columnName
23
     * @internal param string $name
24
     */
25 4
    public function __construct(string $columnName)
26
    {
27 4
        $this->name = $this->_extractAggregate($columnName);
28 4
    }
29
30
    /**
31
     * @param string $name
32
     * @return string
33
     */
34 4
    private function _extractAggregate(string $name): string
35
    {
36 4
        $replaced = 0;
37 4
        $extractedName = preg_replace('/\((.*?)\)/', '#$1', $name, 1, $replaced);
38 4
        if ($replaced !== 0)
39
        {
40 2
            $parts = \explode('#', $extractedName);
41 2
            $this->aggregate = \mb_strtolower($parts[0]);
42
43 2
            $extractedName = $parts[1];
44
        }
45
46 4
        return \mb_substr($extractedName, 0, \mb_strpos($extractedName, '.'));
47
    }
48
49
    /**
50
     * @param string $columnName
51
     * @param Collection $relation
52
     * @return string
53
     */
54 2
    public function getValue(string $columnName, Collection $relation): string
55
    {
56 2
        $aggregateFunctionSet = $this->aggregate !== 'first';
57 2
        if ($aggregateFunctionSet)
58
        {
59 1
            return $relation->{$this->aggregate}($columnName);
60
        }
61
62 1
        return (string) $relation->first()->{$columnName};
63
    }
64
}