1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Taskforcedev\CrudApi\Helpers; |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* Class Model |
7
|
|
|
* @package Taskforcedev\CrudApi\Helpers |
8
|
|
|
*/ |
9
|
|
|
class Model |
10
|
|
|
{ |
11
|
|
|
public $crudApi; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* Model constructor. |
15
|
|
|
* |
16
|
|
|
* @param CrudApi $crudApi |
17
|
|
|
*/ |
18
|
|
|
public function __construct(CrudApi $crudApi) |
19
|
|
|
{ |
20
|
|
|
$this->crudApi = $crudApi; |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* Get a model from the currently set namespace and model. |
25
|
|
|
* |
26
|
|
|
* If the model does not exist from the base namespace it will also |
27
|
|
|
* look in the namespace\Models as a secondary convention. |
28
|
|
|
* |
29
|
|
|
* @return false|string |
30
|
|
|
*/ |
31
|
|
|
public function getModel($model = null) |
32
|
|
|
{ |
33
|
|
|
if ($model === null) { |
34
|
|
|
$model = $this->crudApi->model; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
if ($model === null) { |
38
|
|
|
return false; |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
// Make Sure model name is uppercased. |
42
|
|
|
$model = ucfirst($model); |
43
|
|
|
|
44
|
|
|
// If namespace is not detected or set then set to the laravel default of App. |
45
|
|
|
if ($this->crudApi->namespace === null) { |
46
|
|
|
$this->crudApi->setNamespace('App\\'); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
|
50
|
|
|
// Test conventional namespace model combinations |
51
|
|
|
$conventions = [ |
52
|
|
|
$this->crudApi->namespace . $model, |
53
|
|
|
$this->crudApi->namespace . 'Models\\' . $model |
54
|
|
|
]; |
55
|
|
|
|
56
|
|
|
foreach ($conventions as $fqModel) { |
57
|
|
|
if (class_exists($fqModel)) { |
58
|
|
|
return $fqModel; |
59
|
|
|
} |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
try { |
63
|
|
|
// If not conventional, try configurable |
64
|
|
|
$additionalNamespaces = $this->getAdditionalNamespaces(); |
65
|
|
|
if (!empty($additionalNamespaces)) { |
66
|
|
|
foreach ($additionalNamespaces as $ns) { |
67
|
|
|
$fqModel = $ns . $model; |
68
|
|
|
if (class_exists($fqModel)) { |
69
|
|
|
return $fqModel; |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
} catch (\Exception $e) { |
74
|
|
|
return false; |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
return false; |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
/** |
81
|
|
|
* Return the crudapi model instance. |
82
|
|
|
* @return mixed |
83
|
|
|
*/ |
84
|
|
|
public function instance() |
85
|
|
|
{ |
86
|
|
|
if ($this->crudApi->instance === null) { |
87
|
|
|
$fq = $this->getModel(); |
88
|
|
|
$instance = new $fq(); |
89
|
|
|
$this->crudApi->setInstance($instance); |
90
|
|
|
} |
91
|
|
|
|
92
|
|
|
return $this->crudApi->instance; |
93
|
|
|
} |
94
|
|
|
|
95
|
|
|
/** |
96
|
|
|
* Retrieve any additional configured namespaces. |
97
|
|
|
* @return mixed |
98
|
|
|
*/ |
99
|
|
|
public function getAdditionalNamespaces() |
100
|
|
|
{ |
101
|
|
|
return config('crudapi.models.namespaces'); |
102
|
|
|
} |
103
|
|
|
} |
104
|
|
|
|