Completed
Push — master ( ed61e9...497a60 )
by Rougin
04:46
created

RelationshipTrait   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 70
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 89.47%

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 1
dl 0
loc 70
ccs 17
cts 19
cp 0.8947
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getRelationshipProperties() 0 4 1
A relationships() 0 20 4
A with() 0 10 2
1
<?php
2
3
namespace Rougin\Wildfire\Traits;
4
5
use Rougin\SparkPlug\Instance;
6
7
use Rougin\Wildfire\Helpers\TableHelper;
8
9
/**
10
 * Relationship Trait
11
 *
12
 * @package Wildfire
13
 * @author  Rougin Royce Gutib <[email protected]>
14
 *
15
 * @property \CI_Loader $load
16
 */
17
trait RelationshipTrait
18
{
19
    /**
20
     * Defines an inverse one-to-one or many relationship.
21
     *
22
     * @var array
23
     */
24
    protected $belongs_to = [];
25
26
    /**
27
     * @var array
28
     */
29
    private $_with = [];
30
31
    /**
32
     * Returns the values from the model's properties.
33
     * NOTE: To be removed in v1.0.0. Use $this->properties instead.
34
     *
35
     * @param  array $properties
36
     * @return array
37
     */
38
    public function getRelationshipProperties(array $properties)
39
    {
40
        return $this->relationships($properties);
41
    }
42
43
    /**
44
     * Returns the values from the model's properties.
45
     *
46
     * @param  array $properties
47
     * @return array
48
     */
49 36
    public function relationships(array $properties)
50
    {
51 36
        $belongs = array();
52
53 36
        foreach ((array) $this->belongs_to as $item) {
54 21
            if (! in_array($item, $this->_with)) {
55 15
                continue;
56
            }
57
58 6
            isset($this->$item) || $this->load->model($item);
59
60 6
            $table = TableHelper::name(new $item);
61
62 6
            array_push($belongs, (string) $table);
63 36
        }
64
65 36
        $properties['belongs_to'] = $belongs;
66
67 36
        return $properties;
68
    }
69
70
    /**
71
     * Adds relationship/s to the model.
72
     *
73
     * @param  string|array $relationships
74
     * @return self
75
     */
76 3
    public function with($relationships)
77
    {
78 3
        $relationships = (array) $relationships;
79
80 3
        foreach ($relationships as $relationship) {
81 3
            array_push($this->_with, $relationship);
82 3
        }
83
84 3
        return $this;
85
    }
86
}
87