|
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
|
|
|
|