Test Failed
Push — master ( 7fee35...e1add9 )
by Julien
24:19 queued 18:36
created

DatabaseTrait::addModelsPermissions()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 9
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 12
ccs 0
cts 10
cp 0
crap 6
rs 9.9666
1
<?php
2
3
/**
4
 * This file is part of the Zemit Framework.
5
 *
6
 * (c) Zemit Team <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE.txt
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Zemit\Modules\Cli\Tasks\Traits;
13
14
use Phalcon\Mvc\ModelInterface;
15
use Zemit\Exception\CliException;
16
use Zemit\Utils;
17
18
trait DatabaseTrait
19
{
20
    /**
21
     * Default action
22
     * @throws CliException
23
     */
24
    public function mainAction(): ?array
25
    {
26
        $response = [];
27
        
28
        $response ['truncate'] = $this->truncateAction();
29
        $response ['drop'] = $this->dropAction();
30
        $response ['engine'] = $this->fixEngineAction();
31
        $response ['insert'] = $this->insertAction();
32
        $response ['optimize'] = $this->optimizeAction();
33
        $response ['analyze'] = $this->analyzeAction();
34
        
35
        return $response;
36
    }
37
    
38
    /**
39
     * The truncateAction method is responsible for truncating (emptying) database tables specified in the
40
     * $this->truncate array. Truncating a table removes all of its data, effectively resetting it to an
41
     * empty state. This method iterates through a list of table names and executes an SQL TRUNCATE TABLE
42
     * command for each of them.
43
     *
44
     * Use Case:
45
     * This method is often used when you need to reset the data in database tables without deleting
46
     * the table itself. Truncating tables is a quicker alternative to deleting all rows one by one.
47
     */
48
    public function truncateAction(): array
49
    {
50
        $response = [];
51
        
52
        foreach ($this->truncate as $table) {
53
            $response [] = $this->db->execute('TRUNCATE TABLE ' . $this->db->escapeIdentifier($table));
54
        }
55
        
56
        return $response;
57
    }
58
    
59
    /**
60
     * The dropAction method is responsible for dropping database tables specified in the $this->drop array.
61
     * Dropping a table means permanently removing it from the database schema. This method iterates through
62
     * a list of table names and executes an SQL DROP TABLE command for each of them, with a safety check to
63
     * ensure that the table is only dropped if it exists.
64
     *
65
     * Use Case:
66
     * This method is commonly used when performing database schema changes or cleanup tasks, where you need
67
     * to remove tables that are no longer needed. The IF EXISTS clause is a safety measure to prevent
68
     * accidental deletion of tables.
69
     */
70
    public function dropAction(): array
71
    {
72
        $response = [];
73
        
74
        foreach ($this->drop as $table) {
75
            $response [] = $this->db->execute('DROP TABLE IF EXISTS ' . $this->db->escapeIdentifier($table));
76
        }
77
        
78
        return $response;
79
    }
80
    
81
    /**
82
     * The fixEngineAction method is responsible for fixing or changing the storage engine for database tables
83
     * specified in the $this->engine array. A storage engine determines how data is stored and managed within
84
     * a database table. This method iterates through a list of table names and their corresponding desired
85
     * storage engines and executes SQL ALTER TABLE commands to make the necessary changes.
86
     *
87
     * Use Case:
88
     * This method is useful when you need to adjust the storage engine of database tables to optimize performance,
89
     * compatibility, or for other specific requirements. Different storage engines have different characteristics,
90
     * and choosing the right one can impact table performance and functionality.
91
     */
92
    public function fixEngineAction(): array
93
    {
94
        $response = [];
95
        
96
        foreach ($this->engine as $table => $engine) {
97
            $response [] = $this->db->execute('ALTER TABLE ' . $this->db->escapeIdentifier($table) . ' ENGINE = ' . $engine);
98
        }
99
        
100
        return $response;
101
    }
102
    
103
    /**
104
     * Insert records
105
     * @throws CliException
106
     */
107
    public function insertAction(?string $models = null): array
108
    {
109
        $response = [
110
            'saved' => 0,
111
            'error' => [],
112
            'message' => [],
113
        ];
114
        
115
        $models = (!empty($models)) ? explode(',', $models) : null;
116
        
117
        foreach ($this->insert as $modelName => $insert) {
118
            if (is_array($models) && !in_array($modelName, $models, true)) {
119
                continue;
120
            }
121
            
122
            foreach ($insert as $key => $row) {
123
                $entity = new $modelName();
124
                assert($entity instanceof ModelInterface);
125
                
126
                $assign = isset($row[0]) ? array_combine($entity->columnMap(), $row) : $row;
0 ignored issues
show
Bug introduced by
The method columnMap() does not exist on Phalcon\Mvc\ModelInterface. It seems like you code against a sub-type of Phalcon\Mvc\ModelInterface such as Phalcon\Mvc\Model or Zemit\Models\Setting or Zemit\Models\Category or Zemit\Models\Audit or Zemit\Models\UserGroup or Zemit\Models\User or Zemit\Models\Field or Zemit\Models\Page or Zemit\Models\Log or Zemit\Models\File or Zemit\Models\Role or Zemit\Models\GroupRole or Zemit\Models\Template or Zemit\Models\AuditDetail or Zemit\Models\UserType or Zemit\Models\Post or Zemit\Models\PostCategory or Zemit\Models\Session or Zemit\Models\TranslateField or Zemit\Models\GroupType or Zemit\Models\Translate or Zemit\Models\Email or Zemit\Models\Data or Zemit\Models\Group or Zemit\Models\Lang or Zemit\Models\EmailFile or Zemit\Models\TranslateTable or Zemit\Models\SiteLang or Zemit\Models\UserRole or Zemit\Models\Flag or Zemit\Models\Menu or Zemit\Models\Site or Zemit\Models\Type or Zemit\Models\Channel or Zemit\Models\Meta. ( Ignorable by Annotation )

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

126
                $assign = isset($row[0]) ? array_combine($entity->/** @scrutinizer ignore-call */ columnMap(), $row) : $row;
Loading history...
127
                if (!$assign) {
128
                    throw new CliException('Can\'t assign row #' . $key . ' for model `' . $modelName . '`.');
129
                }
130
                else {
131
                    $entity->assign($assign);
132
                }
133
                
134
                // Automagically fill passwords
135
                if (property_exists($entity, 'password')) {
136
                    if (empty($row['password']) && property_exists($entity, 'username')) {
137
                        $entity->assign(['password' => $row['username'], 'passwordConfirm' => $row['username']]);
138
                    }
139
                    elseif (empty($row['passwordConfirm'])) {
140
                        $entity->assign(['passwordConfirm' => $row['password']]);
141
                    }
142
                }
143
                
144
                if (!$entity->save()) {
145
                    $response['error'][$modelName][] = $entity->toArray();
146
                    
147
                    foreach ($entity->getMessages() as $message) {
148
                        $response['message'][$modelName][] = $message;
149
                    }
150
                }
151
                else {
152
                    $response['saved']++;
153
                }
154
            }
155
        }
156
        
157
        return $response;
158
    }
159
    
160
    /**
161
     * The optimizeAction method is responsible for optimizing database tables specified in the
162
     * $this->optimize array. Database table optimization is a maintenance task aimed at improving
163
     * the performance and storage efficiency of database tables. This method iterates through a
164
     * list of table names and executes an SQL OPTIMIZE TABLE command for each of them.
165
     *
166
     * Use Case:
167
     * This method is typically used in the context of database maintenance and optimization routines.
168
     * It allows you to automate the process of optimizing database tables, which can help reclaim storage
169
     * space and improve query performance by reorganizing table data and indexes.
170
     */
171
    public function optimizeAction(): array
172
    {
173
        $response = [];
174
        
175
        foreach ($this->optimize as $table) {
176
            $response [] = $this->db->query('OPTIMIZE TABLE ' . $this->db->escapeIdentifier($table))->fetchAll();
177
        }
178
        
179
        return $response;
180
    }
181
    
182
    /**
183
     * This method is responsible for analyzing database tables specified in the $this->analyse array.
184
     * Table analysis is an essential database maintenance task that helps optimize the performance
185
     * of database queries. Analyzing a table refreshes statistics and metadata about the table's
186
     * structure, which can lead to improved query execution plans.
187
     *
188
     * Use Case:
189
     * This method can be used in the context of database optimization and maintenance scripts.
190
     * It allows you to automate the process of analyzing database tables, ensuring that the database's
191
     * query optimizer has up-to-date statistics to make informed decisions about query execution plans.
192
     */
193
    public function analyzeAction(): array
194
    {
195
        $response = [];
196
        
197
        foreach ($this->analyze as $table) {
198
            $response [] = $this->db->query('ANALYZE TABLE ' . $this->db->escapeIdentifier($table))->fetchAll();
199
        }
200
        
201
        return $response;
202
    }
203
    
204
    public function addModelsPermissions(?array $tables = null): void
205
    {
206
        $permissions = [];
207
        $tables ??= $this->insert;
208
        foreach ($tables as $model => $entity) {
209
            $permissions[$model] = ['*'];
210
        }
211
        $this->config->merge([
212
            'permissions' => [
213
                'roles' => [
214
                    'cli' => [
215
                        'models' => $permissions,
216
                    ],
217
                ],
218
            ],
219
        ]);
220
    }
221
}
222