Test Failed
Pull Request — master (#20)
by
unknown
03:57
created

AbstractCustomFieldsModel   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 127
Duplicated Lines 0 %

Test Coverage

Coverage 62.22%

Importance

Changes 0
Metric Value
eloc 41
dl 0
loc 127
ccs 28
cts 45
cp 0.6222
rs 10
c 0
b 0
f 0
wmc 13

4 Methods

Rating   Name   Duplication   Size   Complexity  
A saveCustomFields() 0 39 5
A getCustomFieldsByModel() 0 11 4
A getAllCustomFields() 0 39 3
A beforeCreate() 0 5 1
1
<?php
2
declare(strict_types=1);
3
4
namespace Gewaer\CustomFields;
5
6
use Gewaer\Models\CustomFieldsModules;
7
use Exception;
8
9
/**
10
 * Custom Fields Abstract Class
11
 * @property \Phalcon\Di $di
12
 */
13
abstract class AbstractCustomFieldsModel extends \Baka\Database\ModelCustomFields
14
{
15
    /**
16
     * Get all custom fields of the given object
17
     *
18
     * @param  array  $fields
19
     * @return array
20
     */
21 7
    public function getAllCustomFields(array $fields = [])
22
    {
23
        //We does it only find names in plural? We need to fix this or make a workaroun
24 7
        if (!$models = CustomFieldsModules::findFirstByName($this->getSource())) {
25
            return;
26
        }
27
28 7
        $bind = [$this->getId(), $this->di->getApp()->getId(), $models->getId(), $this->di->getUserData()->default_company];
29
30
        // $customFieldsValueTable = $this->getSource() . '_custom_fields';
31 7
        $customFieldsValueTable = $this->getSource() . '_custom_fields';
32
33
        //We are to make a new query to replace old gewaer implementation.
34 7
        $result = $this->getReadConnection()->prepare("SELECT l.{$this->getSource()}_id,
35
                                               c.id as field_id,
36
                                               c.name,
37
                                               l.value ,
38
                                               c.users_id,
39
                                               l.created_at,
40
                                               l.updated_at
41 7
                                        FROM {$customFieldsValueTable} l,
42
                                             custom_fields c
43
                                        WHERE c.id = l.custom_fields_id
44 7
                                          AND l.{$this->getSource()}_id = ?
45
                                          AND c.apps_id = ?
46
                                          AND c.custom_fields_modules_id = ?
47
                                          AND c.companies_id = ? 
48
                                          ");
49
50 7
        $result->execute($bind);
51
52
        // $listOfCustomFields = $result->fetchAll();
53 7
        $listOfCustomFields = [];
54
55 7
        while ($row = $result->fetch(\PDO::FETCH_OBJ)) {
56
            $listOfCustomFields[$row->name] = $row->value;
57
        }
58
59 7
        return $listOfCustomFields;
60
    }
61
62
    /**
63
     * Get all custom fields of the given model
64
     *
65
     * @param  array  $fields
66
     * @return \Phalcon\Mvc\Model
67
     */
68
    public function getCustomFieldsByModel($modelName)
69
    {
70
        if (!$module = CustomFieldsModules::findFirstByName($modelName)) {
71
            return;
72
        }
73
        $allFields = [];
74
        if ($fields = CustomFields::findByModulesId($module->id)->toArray()) {
75
            foreach ($fields as $field) {
76
                array_push($allFields, $field['name']);
77
            }
78
            return $allFields;
79
        }
80
    }
81
82
    /**
83
    * Create new custom fields
84
    *
85
    * We never update any custom fields, we delete them and create them again, thats why we call cleanCustomFields before updates
86
    *
87
    * @return void
88
    */
89 3
    protected function saveCustomFields(): bool
90
    {
91
        //find the custom field module
92 3
        if (!$module = CustomFieldsModules::findFirstByName($this->getSource())) {
93
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type void.
Loading history...
94
        }
95
        //we need a new instane to avoid overwrite
96 3
        $reflector = new \ReflectionClass($this);
97 3
        $classNameWithNameSpace = $reflector->getNamespaceName() . '\\' . $reflector->getShortName() . 'CustomFields';
98
99
        //if all is good now lets get the custom fields and save them
100 3
        foreach ($this->customFields as $key => $value) {
101
            //create a new obj per itration to se can save new info
102 2
            $customModel = new $classNameWithNameSpace();
103
104
            //validate the custome field by it model
105 2
            $customField = CustomFields::findFirst([
106 2
                'conditions' => 'name = ?0 AND custom_fields_modules_id = ?1 AND companies_id = ?2 AND apps_id = ?3',
107 2
                'bind' => [$key, $module->id, $this->di->getUserData()->default_company, $this->di->getApp()->getId()]
108
            ]);
109
110 2
            if ($customField) {
111
                //throw new Exception("this custom field doesnt exist");
112
113
                $customModel->setCustomId($this->getId());
114
                $customModel->custom_fields_id = $customField->id;
115
                $customModel->value = $value;
116
                $customModel->created_at = date('Y-m-d H:i:s');
117
118
                if (!$customModel->save()) {
119 2
                    throw new Exception('Custome ' . $key . ' - ' . current($customModel->getMessages()));
120
                }
121
            }
122
        }
123
124
        //clean
125 3
        unset($this->customFields);
126
127 3
        return true;
0 ignored issues
show
Bug Best Practice introduced by
The expression return true returns the type true which is incompatible with the documented return type void.
Loading history...
128
    }
129
130
    /**
131
    * Before create
132
    *
133
    * @return void
134
    */
135 2
    public function beforeCreate()
136
    {
137 2
        $this->created_at = date('Y-m-d H:i:s');
138 2
        $this->updated_at = null;
139 2
        $this->is_deleted = 0;
140 2
    }
141
}
142