1
|
|
|
<?php namespace AdamWathan\Faktory\Relationship; |
2
|
|
|
|
3
|
|
|
abstract class Relationship |
4
|
|
|
{ |
5
|
|
|
protected $factory; |
6
|
|
|
protected $foreign_key; |
7
|
|
|
protected $attributes; |
8
|
|
|
protected $related_model; |
9
|
|
|
|
10
|
|
|
public function __construct($related_model, $factory, $foreign_key = null, $attributes = []) |
11
|
|
|
{ |
12
|
|
|
$this->related_model = $related_model; |
13
|
|
|
$this->factory = $factory; |
14
|
|
|
$this->foreign_key = $foreign_key; |
15
|
|
|
$this->attributes = $attributes; |
16
|
|
|
} |
17
|
|
|
|
18
|
|
|
public function foreignKey($key) |
19
|
|
|
{ |
20
|
|
|
$this->foreign_key = $key; |
21
|
|
|
return $this; |
22
|
|
|
} |
23
|
|
|
|
24
|
|
|
public function getForeignKey() |
25
|
|
|
{ |
26
|
|
|
if (! is_null($this->foreign_key)) { |
27
|
|
|
return $this->foreign_key; |
28
|
|
|
} |
29
|
|
|
return $this->guessForeignKey(); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
protected function guessForeignKey() |
33
|
|
|
{ |
34
|
|
|
return $this->snakeCase($this->relatedModelBase()).'_id'; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
protected function snakeCase($value) |
38
|
|
|
{ |
39
|
|
|
return ctype_lower($value) ? $value : strtolower(preg_replace('/(.)([A-Z])/', '$1_$2', $value)); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
protected function relatedModelBase() |
43
|
|
|
{ |
44
|
|
|
return $this->extractClassBase($this->getRelatedModel()); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
protected function getRelatedModel() |
48
|
|
|
{ |
49
|
|
|
return $this->related_model; |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
protected function extractClassBase($class) |
53
|
|
|
{ |
54
|
|
|
$class_pieces = explode('\\', $class); |
55
|
|
|
return array_pop($class_pieces); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
public function attributes($attributes) |
59
|
|
|
{ |
60
|
|
|
$this->attributes = array_merge($this->attributes, $attributes); |
61
|
|
|
return $this; |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
public function __set($key, $value) |
65
|
|
|
{ |
66
|
|
|
$this->attributes[$key] = $value; |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
abstract public function build(); |
70
|
|
|
} |
71
|
|
|
|