Completed
Pull Request — master (#8)
by Timo
05:30
created

Relation::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 1
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 5
    public function __construct(string $columnName)
26
    {
27 5
        $this->name = $this->_extractAggregate($columnName);
28 5
    }
29
30
    /**
31
     * @param string $name
32
     * @return string
33
     */
34 5
    private function _extractAggregate(string $name): string
35
    {
36 5
        $replaced = 0;
37 5
        $extractedName = preg_replace('/\((.*?)\)/', '#$1', $name, 1, $replaced);
38 5
        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 5
        return \mb_substr($extractedName, 0, \mb_strpos($extractedName, '.'));
47
    }
48
49
    /**
50
     * @param string $columnName
51
     * @param Collection $relation
52
     * @return string
53
     */
54
    public function getValue(string $columnName, Collection $relation): string
55
    {
56
        $aggregateFunctionSet = $this->aggregate !== 'first';
57
        if ($aggregateFunctionSet)
58
        {
59
            return $relation->{$this->aggregate}($columnName);
60
        }
61
62
        return (string) $relation->first()->{$columnName};
63
    }
64
}