Create::createPrecedent()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 1
1
<?php namespace AdamWathan\Faktory\Strategy;
2
3
use AdamWathan\Faktory\Relationship\BelongsTo;
4
use AdamWathan\Faktory\Relationship\Relationship;
5
use AdamWathan\Faktory\Relationship\DependentRelationship;
6
7
class Create extends Strategy
8
{
9
    public function newInstance()
10
    {
11
        $this->createPrecedents();
12
        $instance = $this->newModel();
13
        foreach ($this->independentAttributes() as $attribute => $value) {
14
            $instance->{$attribute} = $this->getAttributeValue($value);
15
        }
16
        $instance->save();
17
        $this->createDependents($instance);
18
        return $instance;
19
    }
20
21
    protected function createPrecedents()
22
    {
23
        foreach ($this->attributes as $attribute => $value) {
24
            if ($value instanceof BelongsTo) {
25
                $this->createPrecedent($value);
26
                $this->unsetAttribute($attribute);
27
            }
28
        }
29
    }
30
31
    protected function createPrecedent($relationship)
32
    {
33
        $precedent = $relationship->create();
34
        $this->setAttribute($relationship->getForeignKey(), $precedent->getKey());
35
    }
36
37 View Code Duplication
    protected function independentAttributes()
38
    {
39
        $result = [];
40
        foreach ($this->attributes as $attribute => $value) {
41
            if (! $value instanceof Relationship) {
42
                $result[$attribute] = $value;
43
            }
44
        }
45
        return $result;
46
    }
47
48
    protected function createDependents($instance)
49
    {
50
        foreach ($this->dependentRelationships() as $relationship) {
51
            $relationship->create($instance);
52
        }
53
    }
54
55 View Code Duplication
    protected function dependentRelationships()
56
    {
57
        $result = [];
58
        foreach ($this->attributes as $attribute => $value) {
59
            if ($this->isDependentRelationship($value)) {
60
                $result[] = $value;
61
            }
62
        }
63
        return $result;
64
    }
65
66
    protected function isDependentRelationship($value)
67
    {
68
        return $value instanceof DependentRelationship;
69
    }
70
}
71