Completed
Push — master ( 2fc3bb...dacf7a )
by David
06:29
created

Model::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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