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

RelationshipTrait::getRelationshipProperties()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 22
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 22
ccs 13
cts 13
cp 1
rs 8.9197
c 0
b 0
f 0
cc 4
eloc 11
nc 4
nop 1
crap 4
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