Completed
Pull Request — master (#3)
by Rougin
02:51
created

RelationshipTrait   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 7
lcom 1
cbo 2
dl 0
loc 62
ccs 21
cts 21
cp 1
rs 10
c 1
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
B getRelationshipProperties() 0 22 4
A with() 0 12 3
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
trait RelationshipTrait
16
{
17
    /**
18
     * Defines an inverse one-to-one or many relationship.
19
     *
20
     * @var array
21
     */
22
    protected $belongs_to = [];
23
24
    /**
25
     * @var array
26
     */
27
    private $_with = [];
28
29
    /**
30
     * Returns the values from the model's properties.
31
     *
32
     * @param  array $properties
33
     * @return array
34
     */
35 30
    public function getRelationshipProperties(array $properties)
36
    {
37 30
        $belongsTo = [];
38
39 30
        $ci = Instance::create();
40
41 30
        foreach ($this->belongs_to as $item) {
42 18
            if (! in_array($item, $this->_with)) {
43 15
                continue;
44
            }
45
46 3
            if (! isset($ci->$item)) {
47 3
                $ci->load->model($item);
0 ignored issues
show
Bug introduced by
The property load does not seem to exist in CI_Controller.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
48 3
            }
49
50 3
            array_push($belongsTo, TableHelper::getNameFromModel(new $item));
51 30
        }
52
53 30
        $properties['belongs_to'] = $belongsTo;
54
55 30
        return $properties;
56
    }
57
58
    /**
59
     * Adds relationship/s to the model.
60
     *
61
     * @param  string|array $relationships
62
     * @return self
63
     */
64 3
    public function with($relationships)
65
    {
66 3
        if (is_string($relationships)) {
67 3
            $relationships = [ $relationships ];
68 3
        }
69
70 3
        foreach ($relationships as $relationship) {
71 3
            array_push($this->_with, $relationship);
72 3
        }
73
74 3
        return $this;
75
    }
76
}
77