Test Failed
Push — master ( 244aa0...8b6dec )
by Julien
10:46 queued 06:25
created

DeploymentTask::dropAction()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 0
dl 0
loc 9
ccs 0
cts 5
cp 0
crap 6
rs 10
c 0
b 0
f 0
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;
13
14
use Phalcon\Mvc\ModelInterface;
15
use Zemit\Exception\CliException;
16
use Zemit\Models\Lang;
17
use Zemit\Models\Site;
18
use Zemit\Modules\Cli\Task;
19
use Zemit\Models\Role;
20
use Zemit\Models\Setting;
21
use Zemit\Models\Template;
22
use Zemit\Utils;
23
24
class DeploymentTask extends Task
25
{
26
    /**
27
     * @var string
28
     */
29
    public string $cliDoc = <<<DOC
30
Usage:
31
  php zemit cli deployment <action> [<params> ...]
32
33
Options:
34
  task: cache
35
  action: clear
36
37
38
DOC;
39
    
40
    public array $drops = [];
41
    
42
    /**
43
     * Tables to truncate
44
     * @var array Raw DB table sources
45
     */
46
    private array $truncates = [
47
        'audit',
48
        'audit_detail',
49
        'category',
50
        'channel',
51
        'data',
52
        'email',
53
        'email_file',
54
        'field',
55
        'file',
56
        'file_relation',
57
        'flag',
58
        'group',
59
        'group_role',
60
        'group_type',
61
        'lang',
62
        'log',
63
        'menu',
64
        'meta',
65
        'page',
66
        'phalcon_migrations',
67
        'post',
68
        'post_category',
69
        'role',
70
        'session',
71
        'setting',
72
        'site',
73
        'site_lang',
74
        'template',
75
        'translate',
76
        'translate_field',
77
        'translate_table',
78
        'type',
79
        'user',
80
        'user_group',
81
        'user_role',
82
        'user_type',
83
        'validator',
84
    ];
85
    
86
    private array $engines = [];
87
    
88
    public array $insert = [
89
        Role::class => [
90
            ['index' => 'dev', 'label' => 'Developer', 'userlist' => [
91
                ['username' => 'dev', 'email' => '[email protected]', 'firstName' => 'Developer', 'lastName' => 'Zemit'],
92
            ]],
93
            ['index' => 'admin', 'label' => 'Administrator'],
94
            ['index' => 'user', 'label' => 'User'],
95
            ['index' => 'guest', 'label' => 'Guest'],
96
            ['index' => 'everyone', 'label' => 'Everyone'],
97
        ],
98
//        User::class => [
99
//            ['username' => 'dev', 'email' => '[email protected]', 'firstName' => 'Developer', 'lastName' => 'Zemit'],
100
//        ],
101
        Lang::class => [
102
            ['label' => 'Francais', 'code' => 'fr'],
103
            ['label' => 'English', 'code' => 'en'],
104
            ['label' => 'Spanish', 'code' => 'sp'],
105
        ],
106
        Site::class => [
107
            ['name' => 'Zemit CMS', 'title' => 'Zemit CMS', 'description' => ''],
108
        ],
109
        Template::class => [
110
        ],
111
        Setting::class => [
112
        ],
113
    ];
114
    
115
    public function initialize(): void
116
    {
117
        Utils::setUnlimitedRuntime();
118
        $this->addModelsPermissions();
119
    }
120
    
121
    /**
122
     * Default action
123
     * @throws CliException
124
     */
125
    public function mainAction(): ?array
126
    {
127
        $response = [];
128
        
129
        $response ['truncate'] = $this->truncateAction();
130
        $response ['drop'] = $this->dropAction();
131
        $response ['engine'] = $this->fixEngineAction();
132
        $response ['insert'] = $this->insertAction();
133
        
134
        return $response;
135
    }
136
    
137
    /**
138
     * Truncate tables
139
     */
140
    public function truncateAction(): array
141
    {
142
        $response = [];
143
        
144
        foreach ($this->truncates as $table) {
145
            $response [] = $this->db->execute('TRUNCATE TABLE ' . $this->db->escapeIdentifier($table));
146
        }
147
        
148
        return $response;
149
    }
150
    
151
    /**
152
     * Drops tables
153
     */
154
    public function dropAction(): array
155
    {
156
        $response = [];
157
        
158
        foreach ($this->drops as $table) {
159
            $response [] = $this->db->execute('DROP TABLE IF EXISTS ' . $this->db->escapeIdentifier($table));
160
        }
161
        
162
        return $response;
163
    }
164
    
165
    /**
166
     * Fix tables engine
167
     */
168
    public function fixEngineAction(): array
169
    {
170
        $response = [];
171
        
172
        foreach ($this->engines as $table => $engine) {
173
            $response [] = $this->db->execute('ALTER TABLE ' . $this->db->escapeIdentifier($table) . ' ENGINE = ' . $engine);
174
        }
175
        
176
        return $response;
177
    }
178
    
179
    /**
180
     * Insert records
181
     * @throws CliException
182
     */
183
    public function insertAction(): array
184
    {
185
        $response = [
186
            'saved' => 0,
187
            'error' => [],
188
            'message' => [],
189
        ];
190
        
191
        foreach ($this->insert as $modelName => $insert) {
192
            
193
            foreach ($insert as $key => $row) {
194
                $entity = new $modelName();
195
                assert($entity instanceof ModelInterface);
196
                
197
                $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 said class. However, the method does not exist in Zemit\Models\SessionInterface or Zemit\Models\RoleInterface. Are you sure you never get one of those? ( Ignorable by Annotation )

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

197
                $assign = isset($row[0]) ? array_combine($entity->/** @scrutinizer ignore-call */ columnMap(), $row) : $row;
Loading history...
198
                if (!$assign) {
199
                    throw new CliException('Can\'t assign row #' . $key . ' for model `' . $modelName . '`.');
200
                } else {
201
                    $entity->assign($assign);
202
                }
203
                
204
                // Automagically fill passwords
205
                if (property_exists($entity, 'password')) {
206
                    if (empty($row['password'])) {
207
                        $entity->assign(['password' => $row['username'], 'passwordConfirm' => $row['username']]);
208
                    }
209
                    elseif (empty($row['passwordConfirm'])) {
210
                        $entity->assign(['passwordConfirm' => $row['password']]);
211
                    }
212
                }
213
                
214
                if (!$entity->save()) {
215
                    $response['error'][$modelName][] = $entity->toArray();
216
                    
217
                    foreach ($entity->getMessages() as $message) {
218
                        $response['message'][$modelName][] = $message;
219
                    }
220
                }
221
                else {
222
                    $response['saved']++;
223
                }
224
            }
225
        }
226
        
227
        return $response;
228
    }
229
    
230
    public function addModelsPermissions(?array $tables = null): void
231
    {
232
        $permissions = [];
233
        $tables ??= $this->insert;
234
        foreach ($tables as $model => $entity) {
235
            $permissions[$model] = ['*'];
236
        }
237
        $this->config->merge([
238
            'permissions' => [
239
                'roles' => [
240
                    'cli' => [
241
                        'models' => $permissions
242
                    ],
243
                ]
244
            ]
245
        ]);
246
    }
247
}
248