CRUDTrait   A
last analyzed

Complexity

Total Complexity 35

Size/Duplication

Total Lines 196
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 76
dl 0
loc 196
rs 9.6
c 2
b 0
f 0
wmc 35

14 Methods

Rating   Name   Duplication   Size   Complexity  
A getById() 0 20 4
A processDataBeforeSave() 0 14 4
A filterAllowedFields() 0 4 1
A getByFieldWithCondtioned() 0 18 3
A afterProcessDataBeforeGet() 0 3 1
A processDataForForm() 0 3 1
A getByField() 0 14 3
A processDataBeforeGet() 0 11 4
A delete() 0 8 2
A create() 0 11 3
A getDataForForm() 0 7 3
A afterProcessDataBeforeSave() 0 3 1
A update() 0 12 2
A setPosttypeBeforeSave() 0 10 3
1
<?php
2
3
namespace Jidaikobo\Kontiki\Models\Traits;
4
5
use Carbon\Carbon;
6
use  Jidaikobo\Kontiki\Managers\FlashManager;
7
8
trait CRUDTrait
9
{
10
    public function getById(int $id): ?array
11
    {
12
        $result = $this->db->table($this->table)
13
            ->where('id', $id)
14
            ->first();
15
16
        if ($result === null) {
17
            return null;
18
        }
19
20
        $result = (array)$result;
21
22
        if (method_exists($this, 'getAllMetaData')) {
23
            $metaData = $this->getAllMetaData($id);
24
            $result = array_merge($result, $metaData);
25
        }
26
27
        $result = $this->processDataBeforeGet($result);
28
29
        return $result ? (array)$result : null;
30
    }
31
32
    public function getByField(string $field, mixed $value): ?array
33
    {
34
        $result = $this->db->table($this->table)
35
            ->where($field, $value)
36
            ->first();
37
38
        if ($result === null) {
39
            return null;
40
        }
41
42
        $result = (array)$result;
43
        $result = $this->processDataBeforeGet($result);
44
45
        return $result ? (array)$result : null;
46
    }
47
48
    public function getByFieldWithCondtioned(
49
        string $field,
50
        mixed $value,
51
        string $context = 'published'
52
    ): ?array {
53
        $query = $this->getQuery();
0 ignored issues
show
Bug introduced by
It seems like getQuery() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

53
        /** @scrutinizer ignore-call */ 
54
        $query = $this->getQuery();
Loading history...
54
        $query = $this->getAdditionalConditions($query, $context);
0 ignored issues
show
Bug introduced by
It seems like getAdditionalConditions() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

54
        /** @scrutinizer ignore-call */ 
55
        $query = $this->getAdditionalConditions($query, $context);
Loading history...
55
        $result = $query
56
            ->where($field, $value)
57
            ->where('post_type', $this->postType)
58
            ->first();
59
60
        if (is_object($result)) {
61
            $result = (array)$result;
62
            $result = $this->processDataBeforeGet($result);
63
        }
64
65
        return $result ? (array)$result : null;
66
    }
67
68
    public function getDataForForm(
69
        string $actionType,
70
        FlashManager $flashManager,
71
        ?int $id = null
72
    ): array {
73
        $data = $flashManager->getData('data') ?: ($id ? $this->getById($id) : []);
74
        return $this->processDataForForm($actionType, $data);
0 ignored issues
show
Bug introduced by
It seems like $data can also be of type null; however, parameter $data of Jidaikobo\Kontiki\Models...t::processDataForForm() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

74
        return $this->processDataForForm($actionType, /** @scrutinizer ignore-type */ $data);
Loading history...
75
    }
76
77
    protected function processDataForForm(string $actionType, array $data): array
0 ignored issues
show
Unused Code introduced by
The parameter $actionType is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

77
    protected function processDataForForm(/** @scrutinizer ignore-unused */ string $actionType, array $data): array

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
78
    {
79
        return $data;
80
    }
81
82
    protected function setPosttypeBeforeSave(array $data): array
83
    {
84
        $post_type = $data['post_type'] ?? '';
85
        if (!empty($post_type)) {
86
            return $data;
87
        }
88
        if (!empty($this->postType)) {
89
            $data['post_type'] = $this->postType;
90
        }
91
        return $data;
92
    }
93
94
    protected function processDataBeforeSave(string $context, array $data): array
95
    {
96
        foreach ($data as $field => $value) {
97
            $saveAsUtc = $this->getFieldDefinitions()[$field]['save_as_utc'] ?? false;
0 ignored issues
show
Bug introduced by
It seems like getFieldDefinitions() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

97
            $saveAsUtc = $this->/** @scrutinizer ignore-call */ getFieldDefinitions()[$field]['save_as_utc'] ?? false;
Loading history...
98
            if ($saveAsUtc) {
99
                if (empty($value)) {
100
                    $data[$field] = null;
101
                } else {
102
                    $date = Carbon::parse($value, env('TIMEZONE', 'UTC'))->setTimezone('UTC');
103
                    $data[$field] = $date->format('Y-m-d H:i:s');
104
                }
105
            }
106
        }
107
        return $this->afterProcessDataBeforeSave($context, $data);
108
    }
109
110
    protected function processDataBeforeGet(array $data): array
111
    {
112
        foreach ($data as $field => $value) {
113
            $saveAsUtc = $this->getFieldDefinitions()[$field]['save_as_utc'] ?? false;
114
            if ($saveAsUtc && !empty($value)) {
115
                $date = Carbon::parse($value, 'UTC')->setTimezone(env('TIMEZONE', 'UTC'));
116
                $data[$field] = $date->format('Y-m-d H:i:s');
117
            }
118
        }
119
120
        return $this->afterProcessDataBeforeGet($data);
121
        ;
122
    }
123
124
    protected function afterProcessDataBeforeSave(string $context, array $data): array
0 ignored issues
show
Unused Code introduced by
The parameter $context is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

124
    protected function afterProcessDataBeforeSave(/** @scrutinizer ignore-unused */ string $context, array $data): array

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
125
    {
126
        return $data;
127
    }
128
129
    protected function afterProcessDataBeforeGet(array $data): array
130
    {
131
        return $data;
132
    }
133
134
    /**
135
     * Filter the given data array to include only allowed fields.
136
     *
137
     * @param array $data The data to filter.
138
     *
139
     * @return array The filtered data.
140
     */
141
    public function filterAllowedFields(array $data): array
142
    {
143
        $allowedFields = array_keys($this->getFieldDefinitions());
144
        return array_intersect_key($data, array_flip($allowedFields));
145
    }
146
147
    /**
148
     * Create a new record in the table.
149
     *
150
     * @param array $data Key-value pairs of column names and values.
151
     *
152
     * @return int|null The ID of the newly created record, or null if the operation failed.
153
     */
154
    public function create(array $data, bool $skipFieldFilter = false): ?int
155
    {
156
        if (!$skipFieldFilter) {
157
            $data = $this->filterAllowedFields($data);
158
        }
159
160
        $data = $this->processDataBeforeSave('create', $data);
161
        $data = $this->setPosttypeBeforeSave($data);
162
163
        $success = $this->db->table($this->table)->insert($data);
164
        return $success ? (int) $this->db->getPdo()->lastInsertId() : null;
165
    }
166
167
    /**
168
     * Update a record in the table by its ID.
169
     *
170
     * @param  int   $id   The ID of the record to update.
171
     * @param  array $data Key-value pairs of column names and values to update.
172
     *
173
     * @return bool True if the record was updated, false otherwise.
174
     */
175
    public function update(int $id, array $data, bool $skipFieldFilter = false): bool
176
    {
177
        if (!$skipFieldFilter) {
178
            $data = $this->filterAllowedFields($data);
179
        }
180
181
        $data = $this->processDataBeforeSave('update', $data);
182
        $data = $this->setPosttypeBeforeSave($data);
183
184
        return (bool) $this->db->table($this->table)
185
            ->where('id', $id)
186
            ->update($data);
187
    }
188
189
    /**
190
     * Delte a record in the table by its ID.
191
     *
192
     * @param  int   $id   The ID of the record to update.
193
     *
194
     * @return bool True if the record was updated, false otherwise.
195
     */
196
    public function delete(int $id): bool
197
    {
198
        if (!$this->getById($id)) {
199
            return false;
200
        }
201
        return (bool)$this->db->table($this->table)
202
            ->where('id', $id)
203
            ->delete();
204
    }
205
}
206