Passed
Push — develop ( b546ed...ec145b )
by Felipe
08:20
created

ConstraintsController::addPrimaryOrUniqueKey()   C

Complexity

Conditions 11
Paths 7

Size

Total Lines 39
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 39
rs 5.2653
c 0
b 0
f 0
cc 11
eloc 25
nc 7
nop 1

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * PHPPgAdmin v6.0.0-beta.48
5
 */
6
7
namespace PHPPgAdmin\Controller;
8
9
use PHPPgAdmin\Decorators\Decorator;
10
11
/**
12
 * Base controller class.
13
 *
14
 * @package PHPPgAdmin
15
 */
16
class ConstraintsController extends BaseController
17
{
18
    use \PHPPgAdmin\Traits\FormTrait;
19
20
    /**
21
     * Default method to render the controller according to the action parameter.
22
     */
23
    public function render()
24
    {
25
        if ('tree' == $this->action) {
26
            return $this->/* @scrutinizer ignore-call */doTree();
27
        }
28
29
        $this->printHeader(
30
            $this->lang['strtables'].' - '.$_REQUEST['table'].' - '.$this->lang['strconstraints'],
31
            '<script src="'.\SUBFOLDER.'/assets/js/indexes.js" type="text/javascript"></script>',
32
            true,
33
            'header_select2.twig'
34
        );
35
36
        $onloadInitActions = [
37
            'add_unique_key',
38
            'save_add_unique_key',
39
            'add_primary_key',
40
            'save_add_primary_key',
41
            'add_foreign_key',
42
            'select_referencing_columns',
43
            'save_add_foreign_key',
44
        ];
45
46
        $onloadInit = false;
47
        if (in_array($this->action, $onloadInitActions, true)) {
48
            $onloadInit = true;
49
        }
50
        $this->printBody(true, 'detailbody', $onloadInit);
51
52
        if (isset($_POST['cancel']) || ($this->action === 'drop' && !isset($_POST['drop']))) {
53
            $this->action = 'default';
54
        }
55
56
        switch ($this->action) {
57
            case 'add_foreign_key':
58
                $this->printFKForm();
59
60
                break;
61
            case 'select_referencing_columns':
62
                $this->_selectFKColumns();
63
64
                break;
65
            case 'save_add_foreign_key':
66
                $this->addForeignKey();
67
68
                break;
69
            case 'add_unique_key':
70
                $this->formPrimaryOrUniqueKey('unique');
71
72
                break;
73
            case 'add_primary_key':
74
                $this->formPrimaryOrUniqueKey('primary');
75
76
                break;
77
            case 'save_add_unique_key':
78
                $this->addPrimaryOrUniqueKey('unique');
79
80
                break;
81
            case 'save_add_primary_key':
82
                $this->addPrimaryOrUniqueKey('primary');
83
84
                break;
85
            case 'add_check':
86
                $this->addCheck(true);
87
88
                break;
89
            case 'save_add_check':
90
                $this->addCheck(false);
91
92
                break;
93
            case 'drop':
94
                $this->doDrop();
95
96
                break;
97
            case 'confirm_drop':
98
                $this->printDropForm();
99
100
                break;
101
            default:
102
                $this->doDefault();
103
104
                break;
105
        }
106
107
        $this->printFooter();
108
    }
109
110
    /**
111
     * List all the constraints on the table.
112
     *
113
     * @param mixed $msg
114
     */
115
    public function doDefault($msg = '')
116
    {
117
        $data = $this->misc->getDatabaseAccessor();
118
119
        $cnPre = function (&$rowdata) use ($data) {
120
            if (is_null($rowdata->fields['consrc'])) {
121
                $atts                           = $data->getAttributeNames($_REQUEST['table'], explode(' ', $rowdata->fields['indkey']));
122
                $rowdata->fields['+definition'] = ('u' == $rowdata->fields['contype'] ? 'UNIQUE (' : 'PRIMARY KEY (').join(',', $atts).')';
123
            } else {
124
                $rowdata->fields['+definition'] = $rowdata->fields['consrc'];
125
            }
126
        };
127
128
        $this->printTrail('table');
129
        $this->printTabs('table', 'constraints');
130
        $this->printMsg($msg);
131
132
        $constraints = $data->getConstraints($_REQUEST['table']);
133
134
        $columns = [
135
            'constraint' => [
136
                'title' => $this->lang['strname'],
137
                'field' => Decorator::field('conname'),
138
            ],
139
            'definition' => [
140
                'title' => $this->lang['strdefinition'],
141
                'field' => Decorator::field('+definition'),
142
                'type'  => 'pre',
143
            ],
144
            'actions'    => [
145
                'title' => $this->lang['stractions'],
146
            ],
147
            'comment'    => [
148
                'title' => $this->lang['strcomment'],
149
                'field' => Decorator::field('constcomment'),
150
            ],
151
        ];
152
153
        $actions = [
154
            'drop' => [
155
                'content' => $this->lang['strdrop'],
156
                'attr'    => [
157
                    'href' => [
158
                        'url'     => 'constraints',
159
                        'urlvars' => [
160
                            'action'     => 'confirm_drop',
161
                            'table'      => $_REQUEST['table'],
162
                            'constraint' => Decorator::field('conname'),
163
                            'type'       => Decorator::field('contype'),
164
                        ],
165
                    ],
166
                ],
167
            ],
168
        ];
169
170
        echo $this->printTable($constraints, $columns, $actions, 'constraints-constraints', $this->lang['strnoconstraints'], $cnPre);
171
172
        $navlinks = [
173
            'addcheck' => [
174
                'attr'    => [
175
                    'href' => [
176
                        'url'     => 'constraints',
177
                        'urlvars' => [
178
                            'action'   => 'add_check',
179
                            'server'   => $_REQUEST['server'],
180
                            'database' => $_REQUEST['database'],
181
                            'schema'   => $_REQUEST['schema'],
182
                            'table'    => $_REQUEST['table'],
183
                        ],
184
                    ],
185
                ],
186
                'content' => $this->lang['straddcheck'],
187
            ],
188
            'adduniq'  => [
189
                'attr'    => [
190
                    'href' => [
191
                        'url'     => 'constraints',
192
                        'urlvars' => [
193
                            'action'   => 'add_unique_key',
194
                            'server'   => $_REQUEST['server'],
195
                            'database' => $_REQUEST['database'],
196
                            'schema'   => $_REQUEST['schema'],
197
                            'table'    => $_REQUEST['table'],
198
                        ],
199
                    ],
200
                ],
201
                'content' => $this->lang['stradduniq'],
202
            ],
203
            'addpk'    => [
204
                'attr'    => [
205
                    'href' => [
206
                        'url'     => 'constraints',
207
                        'urlvars' => [
208
                            'action'   => 'add_primary_key',
209
                            'server'   => $_REQUEST['server'],
210
                            'database' => $_REQUEST['database'],
211
                            'schema'   => $_REQUEST['schema'],
212
                            'table'    => $_REQUEST['table'],
213
                        ],
214
                    ],
215
                ],
216
                'content' => $this->lang['straddpk'],
217
            ],
218
            'addfk'    => [
219
                'attr'    => [
220
                    'href' => [
221
                        'url'     => 'constraints',
222
                        'urlvars' => [
223
                            'action'   => 'add_foreign_key',
224
                            'server'   => $_REQUEST['server'],
225
                            'database' => $_REQUEST['database'],
226
                            'schema'   => $_REQUEST['schema'],
227
                            'table'    => $_REQUEST['table'],
228
                        ],
229
                    ],
230
                ],
231
                'content' => $this->lang['straddfk'],
232
            ],
233
        ];
234
        $this->printNavLinks($navlinks, 'constraints-constraints', get_defined_vars());
235
    }
236
237
    /**
238
     * Prints the first step to create an FK.
239
     *
240
     * @param string $msg The message
241
     */
242
    public function printFKForm($msg = '')
243
    {
244
        $data = $this->misc->getDatabaseAccessor();
245
246
        $this->printTrail('table');
247
        $this->printTitle($this->lang['straddfk'], 'pg.constraint.foreign_key');
248
        $this->printMsg($msg);
249
250
        $attrs  = $data->getTableAttributes($_REQUEST['table']);
251
        $tables = $data->getTables(true);
252
253
        $selColumns = new \PHPPgAdmin\XHtml\XHtmlSelect('TableColumnList', true, 10);
254
        $selColumns->set_style('width: 15em;');
255
256
        if ($attrs->recordCount() > 0) {
257
            while (!$attrs->EOF) {
258
                $xmloption = new \PHPPgAdmin\XHtml\XHtmlOption($attrs->fields['attname']);
259
                $selColumns->add($xmloption);
260
                $attrs->moveNext();
261
            }
262
        }
263
264
        $selIndex = new \PHPPgAdmin\XHtml\XHtmlSelect('IndexColumnList[]', true, 10);
265
        $selIndex->set_style('width: 15em;');
266
        $selIndex->set_attribute('id', 'IndexColumnList');
267
        $buttonAdd = new \PHPPgAdmin\XHtml\XHtmlButton('add', '>>');
268
        $buttonAdd->set_attribute('onclick', 'buttonPressed(this);');
269
        $buttonAdd->set_attribute('type', 'button');
270
271
        $buttonRemove = new \PHPPgAdmin\XHtml\XHtmlButton('remove', '<<');
272
        $buttonRemove->set_attribute('onclick', 'buttonPressed(this);');
273
        $buttonRemove->set_attribute('type', 'button');
274
275
        echo "<form onsubmit=\"doSelectAll();\" name=\"formIndex\" action=\"constraints\" method=\"post\">\n";
276
277
        echo "<table>\n";
278
        echo "<tr><th class=\"data\" colspan=\"3\">{$this->lang['strname']}</th></tr>\n";
279
        echo "<tr><td class=\"data1\" colspan=\"3\"><input type=\"text\" name=\"name\" size=\"32\" maxlength=\"{$data->_maxNameLen}\" /></td></tr>\n";
280
        echo "<tr><th class=\"data\">{$this->lang['strtablecolumnlist']}</th><th class=\"data\">&nbsp;</th><th class=\"data required\">{$this->lang['strfkcolumnlist']}</th></tr>\n";
281
        echo '<tr><td class="data1">'.$selColumns->fetch()."</td>\n";
282
        echo '<td class="data1" style="text-align: center">'.$buttonRemove->fetch().$buttonAdd->fetch()."</td>\n";
283
        echo '<td class=data1>'.$selIndex->fetch()."</td></tr>\n";
284
        echo "<tr><th class=\"data\" colspan=\"3\">{$this->lang['strfktarget']}</th></tr>";
285
        echo '<tr>';
286
        echo '<td class="data1" colspan="3"><select class="select2" name="target">';
287
        while (!$tables->EOF) {
288
            $key = ['schemaname' => $tables->fields['nspname'], 'tablename' => $tables->fields['relname']];
289
            $key = serialize($key);
290
            echo '<option value="', htmlspecialchars($key), '">';
291
            if ($tables->fields['nspname'] != $_REQUEST['schema']) {
292
                echo htmlspecialchars($tables->fields['nspname']), '.';
293
            }
294
            echo htmlspecialchars($tables->fields['relname']), "</option>\n";
295
            $tables->moveNext();
296
        }
297
        echo "</select>\n";
298
        echo '</td></tr>';
299
        echo "</table>\n";
300
301
        echo "<p>\n";
302
303
        echo $this->getActionTableAndButtons(
304
            'select_referencing_columns',
305
            htmlspecialchars($_REQUEST['table']),
306
            $this->lang['stradd'],
307
            $this->lang['strcancel']
308
        );
309
310
        echo sprintf('</p>%s</form>%s', "\n", "\n");
311
    }
312
313
    /**
314
     * Prints second screen of FK creation, where you select which columns
315
     * to use in the referencing table.
316
     *
317
     * @param string $msg optional message to display
318
     */
319
    private function _selectFKColumns($msg = '')
320
    {
321
        $data = $this->misc->getDatabaseAccessor();
322
323
        $this->coalesceArr($_POST, 'name', '');
324
325
        $this->coalesceArr($_POST, 'target', '');
326
327
        // Check that they've given at least one source column
328
        if (!isset($_REQUEST['SourceColumnList']) && (!isset($_POST['IndexColumnList']) ||
329
            !is_array($_POST['IndexColumnList']) ||
330
            0 == sizeof($_POST['IndexColumnList']))) {
331
            return $this->printFKForm($this->lang['strfkneedscols']);
332
        }
333
        // Copy the IndexColumnList variable from stage 1
334
        if (isset($_REQUEST['IndexColumnList']) && !isset($_REQUEST['SourceColumnList'])) {
335
            $_REQUEST['SourceColumnList'] = serialize($_REQUEST['IndexColumnList']);
336
        }
337
338
        // Initialise variables
339
        $this->coalesceArr($_POST, 'upd_action', null);
340
341
        $this->coalesceArr($_POST, 'del_action', null);
342
343
        $this->coalesceArr($_POST, 'match', null);
344
345
        $this->coalesceArr($_POST, 'deferrable', null);
346
347
        $this->coalesceArr($_POST, 'initially', null);
348
349
        $_REQUEST['target'] = unserialize($_REQUEST['target']);
350
351
        $this->printTrail('table');
352
        $this->printTitle($this->lang['straddfk'], 'pg.constraint.foreign_key');
353
        $this->printMsg($msg);
354
355
        // Unserialize target and fetch appropriate table. This is a bit messy
356
        // because the table could be in another schema.
357
        $data->setSchema($_REQUEST['target']['schemaname']);
358
        $attrs = $data->getTableAttributes($_REQUEST['target']['tablename']);
359
        $data->setSchema($_REQUEST['schema']);
360
361
        $selColumns = new \PHPPgAdmin\XHtml\XHtmlSelect('TableColumnList', true, 10);
362
        $selColumns->set_style('width: 15em;');
363
364
        if ($attrs->recordCount() > 0) {
365
            while (!$attrs->EOF) {
366
                $xmloption = new \PHPPgAdmin\XHtml\XHtmlOption($attrs->fields['attname']);
367
                $selColumns->add($xmloption);
368
                $attrs->moveNext();
369
            }
370
        }
371
372
        $selIndex = new \PHPPgAdmin\XHtml\XHtmlSelect('IndexColumnList[]', true, 10);
373
        $selIndex->set_style('width: 15em;');
374
        $selIndex->set_attribute('id', 'IndexColumnList');
375
        $buttonAdd = new \PHPPgAdmin\XHtml\XHtmlButton('add', '>>');
376
        $buttonAdd->set_attribute('onclick', 'buttonPressed(this);');
377
        $buttonAdd->set_attribute('type', 'button');
378
379
        $buttonRemove = new \PHPPgAdmin\XHtml\XHtmlButton('remove', '<<');
380
        $buttonRemove->set_attribute('onclick', 'buttonPressed(this);');
381
        $buttonRemove->set_attribute('type', 'button');
382
383
        echo "<form onsubmit=\"doSelectAll();\" name=\"formIndex\" action=\"constraints\" method=\"post\">\n";
384
385
        echo "<table>\n";
386
        echo "<tr><th class=\"data\" colspan=\"3\">{$this->lang['strfktarget']}</th></tr>";
387
        echo "<tr><th class=\"data\">{$this->lang['strtablecolumnlist']}</th><th class=\"data\">&nbsp;</th><th class=data>{$this->lang['strfkcolumnlist']}</th></tr>\n";
388
        echo '<tr><td class="data1">'.$selColumns->fetch()."</td>\n";
389
        echo '<td class="data1" style="text-align: center">'.$buttonRemove->fetch().$buttonAdd->fetch().'</td>';
390
        echo '<td class="data1">'.$selIndex->fetch()."</td></tr>\n";
391
        echo "<tr><th class=\"data\" colspan=\"3\">{$this->lang['stractions']}</th></tr>";
392
        echo '<tr>';
393
        echo "<td class=\"data1\" colspan=\"3\">\n";
394
        // ON SELECT actions
395
        echo "{$this->lang['stronupdate']} <select name=\"upd_action\">";
396
        foreach ($data->fkactions as $v) {
397
            echo "<option value=\"{$v}\"", ($_POST['upd_action'] == $v) ? ' selected="selected"' : '', ">{$v}</option>\n";
398
        }
399
400
        echo "</select><br />\n";
401
402
        // ON DELETE actions
403
        echo "{$this->lang['strondelete']} <select name=\"del_action\">";
404
        foreach ($data->fkactions as $v) {
405
            echo "<option value=\"{$v}\"", ($_POST['del_action'] == $v) ? ' selected="selected"' : '', ">{$v}</option>\n";
406
        }
407
408
        echo "</select><br />\n";
409
410
        // MATCH options
411
        echo '<select name="match">';
412
        foreach ($data->fkmatches as $v) {
413
            echo "<option value=\"{$v}\"", ($_POST['match'] == $v) ? ' selected="selected"' : '', ">{$v}</option>\n";
414
        }
415
416
        echo "</select><br />\n";
417
418
        // DEFERRABLE options
419
        echo '<select name="deferrable">';
420
        foreach ($data->fkdeferrable as $v) {
421
            echo "<option value=\"{$v}\"", ($_POST['deferrable'] == $v) ? ' selected="selected"' : '', ">{$v}</option>\n";
422
        }
423
424
        echo "</select><br />\n";
425
426
        // INITIALLY options
427
        echo '<select name="initially">';
428
        foreach ($data->fkinitial as $v) {
429
            echo "<option value=\"{$v}\"", ($_POST['initially'] == $v) ? ' selected="selected"' : '', ">{$v}</option>\n";
430
        }
431
432
        echo "</select>\n";
433
        echo "</td></tr>\n";
434
        echo "</table>\n";
435
436
        echo '<p>';
437
438
        echo '<input type="hidden" name="name" value="', htmlspecialchars($_REQUEST['name']), "\" />\n";
439
        echo '<input type="hidden" name="target" value="', htmlspecialchars(serialize($_REQUEST['target'])), "\" />\n";
440
        echo '<input type="hidden" name="SourceColumnList" value="', htmlspecialchars($_REQUEST['SourceColumnList']), "\" />\n";
441
442
        echo $this->getActionTableAndButtons(
443
            'save_add_foreign_key',
444
            htmlspecialchars($_REQUEST['table']),
445
            $this->lang['stradd'],
446
            $this->lang['strcancel']
447
        );
448
449
        echo sprintf('</p>%s</form>%s', "\n", "\n");
450
    }
451
452
    /**
453
     * Perform actual creation of the FOREIGN KEY constraint.
454
     *
455
     * @param string $msg optional message to display
456
     */
457
    public function addForeignKey($msg = '')
458
    {
459
        $data = $this->misc->getDatabaseAccessor();
460
461
        $this->coalesceArr($_POST, 'name', '');
462
463
        $this->coalesceArr($_POST, 'target', '');
464
465
        $this->coalesceArr($_POST, 'SourceColumnList', 'a:0:{}');
466
467
        $this->coalesceArr($_POST, 'IndexColumnList', []);
468
469
        // Unserialize target
470
        $_POST['target'] = unserialize($_POST['target']);
471
472
        // Check that they've given at least one column
473
        $temp = unserialize($_POST['SourceColumnList']);
474
475
        // If IndexColumnList or SourceColumnList are empty, return to screen to select referencing table columns
476
        if (!is_array($_POST['IndexColumnList'])
477
            || 0 == sizeof($_POST['IndexColumnList'])
478
            || 0 == sizeof($temp)) {
479
            return $this->_selectFKColumns($this->lang['strfkneedscols']);
480
        }
481
482
        $status = $data->addForeignKey(
483
            $_POST['table'],
484
            $_POST['target']['schemaname'],
485
            $_POST['target']['tablename'],
486
            unserialize($_POST['SourceColumnList']),
487
            $_POST['IndexColumnList'],
488
            $_POST['upd_action'],
489
            $_POST['del_action'],
490
            $_POST['match'],
491
            $_POST['deferrable'],
492
            $_POST['initially'],
493
            $_POST['name']
494
        );
495
        if (0 == $status) {
496
            return $this->doDefault($this->lang['strfkadded']);
497
        }
498
499
        return $this->_selectFKColumns($this->lang['strfkaddedbad']);
500
    }
501
502
    /**
503
     * Print form to add a PRIMARY KEY or UNIQUE constraint.
504
     *
505
     * @param string $type either primary or unique
506
     * @param string $msg  optional message
507
     */
508
    public function formPrimaryOrUniqueKey($type, $msg = '')
509
    {
510
        $data = $this->misc->getDatabaseAccessor();
511
        $this->coalesceArr($_POST, 'name', '');
512
513
        $this->coalesceArr($_POST, 'tablespace', '');
514
515
        $this->printTrail('table');
516
517
        switch ($type) {
518
            case 'primary':
519
                $this->printTitle($this->lang['straddpk'], 'pg.constraint.primary_key');
520
521
                break;
522
            case 'unique':
523
                $this->printTitle($this->lang['stradduniq'], 'pg.constraint.unique_key');
524
525
                break;
526
            default:
527
                $this->doDefault($this->lang['strinvalidparam']);
528
529
                return;
530
        }
531
532
        $this->printMsg($msg);
533
534
        $attrs       = $data->getTableAttributes($_REQUEST['table']);
535
        $tablespaces = null;
536
        // Fetch all tablespaces from the database
537
        if ($data->hasTablespaces()) {
538
            $tablespaces = $data->getTablespaces();
539
        }
540
541
        $selColumns = new \PHPPgAdmin\XHtml\XHtmlSelect('TableColumnList', true, 10);
542
        $selColumns->set_style('width: 15em;');
543
544
        if ($attrs->recordCount() > 0) {
545
            while (!$attrs->EOF) {
546
                $new_option = new \PHPPgAdmin\XHtml\XHtmlOption($attrs->fields['attname']);
547
                $selColumns->add($new_option);
548
                $attrs->moveNext();
549
            }
550
        }
551
552
        $selIndex = new \PHPPgAdmin\XHtml\XHtmlSelect('IndexColumnList[]', true, 10);
553
        $selIndex->set_style('width: 15em;');
554
        $selIndex->set_attribute('id', 'IndexColumnList');
555
        $buttonAdd = new \PHPPgAdmin\XHtml\XHtmlButton('add', '>>');
556
        $buttonAdd->set_attribute('onclick', 'buttonPressed(this);');
557
        $buttonAdd->set_attribute('type', 'button');
558
559
        $buttonRemove = new \PHPPgAdmin\XHtml\XHtmlButton('remove', '<<');
560
        $buttonRemove->set_attribute('onclick', 'buttonPressed(this);');
561
        $buttonRemove->set_attribute('type', 'button');
562
563
        echo "<form onsubmit=\"doSelectAll();\" name=\"formIndex\" action=\"constraints\" method=\"post\">\n";
564
565
        echo "<table>\n";
566
        echo "<tr><th class=\"data\" colspan=\"3\">{$this->lang['strname']}</th></tr>";
567
        echo '<tr>';
568
        echo '<td class="data1" colspan="3"><input type="text" name="name" value="', htmlspecialchars($_POST['name']),
569
            "\" size=\"32\" maxlength=\"{$data->_maxNameLen}\" /></td></tr>";
570
        echo "<tr><th class=\"data\">{$this->lang['strtablecolumnlist']}</th><th class=\"data\">&nbsp;</th><th class=\"data required\">{$this->lang['strindexcolumnlist']}</th></tr>\n";
571
        echo '<tr><td class="data1">'.$selColumns->fetch()."</td>\n";
572
        echo '<td class="data1" style="text-align: center">'.$buttonRemove->fetch().$buttonAdd->fetch().'</td>';
573
        echo '<td class=data1>'.$selIndex->fetch()."</td></tr>\n";
574
575
        // Tablespace (if there are any)
576
        if ($data->hasTablespaces() && $tablespaces->recordCount() > 0) {
577
            echo "<tr><th class=\"data\" colspan=\"3\">{$this->lang['strtablespace']}</th></tr>";
578
            echo "<tr><td class=\"data1\" colspan=\"3\"><select name=\"tablespace\">\n";
579
            // Always offer the default (empty) option
580
            echo "\t\t\t\t<option value=\"\"",
581
            ('' == $_POST['tablespace']) ? ' selected="selected"' : '', "></option>\n";
582
            // Display all other tablespaces
583
            while (!$tablespaces->EOF) {
584
                $spcname = htmlspecialchars($tablespaces->fields['spcname']);
585
                echo "\t\t\t\t<option value=\"{$spcname}\"",
586
                ($spcname == $_POST['tablespace']) ? ' selected="selected"' : '', ">{$spcname}</option>\n";
587
                $tablespaces->moveNext();
588
            }
589
            echo "</select></td></tr>\n";
590
        }
591
592
        echo "</table>\n";
593
594
        echo '<p>';
595
596
        echo $this->getActionTableAndButtons(
597
            ($type === 'primary' ? 'save_add_primary_key' : 'save_add_unique_key'),
598
            htmlspecialchars($_REQUEST['table']),
599
            $this->lang['stradd'],
600
            $this->lang['strcancel']
601
        );
602
603
        echo sprintf('</p>%s</form>%s', "\n", "\n");
604
    }
605
606
    /**
607
     * Try to add a PRIMARY KEY or UNIQUE constraint.
608
     *
609
     * @param string $type either primary or unique
610
     */
611
    public function addPrimaryOrUniqueKey($type)
612
    {
613
        $data = $this->misc->getDatabaseAccessor();
614
615
        $this->coalesceArr($_POST, 'name', '');
616
617
        // Default tablespace to empty if it isn't set
618
        $this->coalesceArr($_POST, 'tablespace', '');
619
620
        if ('primary' == $type) {
621
            // Check that they've given at least one column
622
            if (!isset($_POST['IndexColumnList']) || !is_array($_POST['IndexColumnList'])
623
                || 0 == sizeof($_POST['IndexColumnList'])
624
            ) {
625
                $this->formPrimaryOrUniqueKey($type, $this->lang['strpkneedscols']);
626
            } else {
627
                $status = $data->addPrimaryKey($_POST['table'], $_POST['IndexColumnList'], $_POST['name'], $_POST['tablespace']);
628
                if (0 == $status) {
629
                    $this->doDefault($this->lang['strpkadded']);
630
                } else {
631
                    $this->formPrimaryOrUniqueKey($type, $this->lang['strpkaddedbad']);
632
                }
633
            }
634
        } elseif ('unique' == $type) {
635
            // Check that they've given at least one column
636
            if (!isset($_POST['IndexColumnList']) || !is_array($_POST['IndexColumnList'])
637
                || 0 == sizeof($_POST['IndexColumnList'])
638
            ) {
639
                $this->formPrimaryOrUniqueKey($type, $this->lang['struniqneedscols']);
640
            } else {
641
                $status = $data->addUniqueKey($_POST['table'], $_POST['IndexColumnList'], $_POST['name'], $_POST['tablespace']);
642
                if (0 == $status) {
643
                    $this->doDefault($this->lang['struniqadded']);
644
                } else {
645
                    $this->formPrimaryOrUniqueKey($type, $this->lang['struniqaddedbad']);
646
                }
647
            }
648
        } else {
649
            $this->doDefault($this->lang['strinvalidparam']);
650
        }
651
    }
652
653
    /**
654
     * Confirm and then actually add a CHECK constraint.
655
     *
656
     * @param mixed $confirm
657
     * @param mixed $msg
658
     */
659
    public function addCheck($confirm, $msg = '')
660
    {
661
        $data = $this->misc->getDatabaseAccessor();
662
663
        $this->coalesceArr($_POST, 'name', '');
664
665
        $this->coalesceArr($_POST, 'definition', '');
666
667
        if ($confirm) {
668
            $this->printTrail('table');
669
            $this->printTitle($this->lang['straddcheck'], 'pg.constraint.check');
670
            $this->printMsg($msg);
671
672
            echo '<form action="'.\SUBFOLDER."/src/views/constraints\" method=\"post\">\n";
673
            echo "<table>\n";
674
            echo "<tr><th class=\"data\">{$this->lang['strname']}</th>\n";
675
            echo "<th class=\"data required\">{$this->lang['strdefinition']}</th></tr>\n";
676
677
            echo "<tr><td class=\"data1\"><input name=\"name\" size=\"24\" maxlength=\"{$data->_maxNameLen}\" value=\"",
678
            htmlspecialchars($_POST['name']), "\" /></td>\n";
679
680
            echo '<td class="data1">(<input name="definition" size="64" value="',
681
            htmlspecialchars($_POST['definition']), "\" />)</td></tr>\n";
682
            echo "</table>\n";
683
684
            echo "<input type=\"hidden\" name=\"action\" value=\"save_add_check\" />\n";
685
            echo '<input type="hidden" name="table" value="', htmlspecialchars($_REQUEST['table']), "\" />\n";
686
            echo $this->misc->form;
687
            echo "<p><input type=\"submit\" name=\"ok\" value=\"{$this->lang['stradd']}\" />\n";
688
            echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>\n";
689
            echo "</form>\n";
690
        } else {
691
            if ('' == trim($_POST['definition'])) {
692
                $this->addCheck(true, $this->lang['strcheckneedsdefinition']);
693
            } else {
694
                $status = $data->addCheckConstraint(
695
                    $_POST['table'],
696
                    $_POST['definition'],
697
                    $_POST['name']
698
                );
699
                if (0 == $status) {
700
                    $this->doDefault($this->lang['strcheckadded']);
701
                } else {
702
                    $this->addCheck(true, $this->lang['strcheckaddedbad']);
703
                }
704
            }
705
        }
706
    }
707
708
    /**
709
     * Prints the drop form.
710
     */
711
    public function printDropForm()
712
    {
713
        $data = $this->misc->getDatabaseAccessor();
0 ignored issues
show
Unused Code introduced by
The assignment to $data is dead and can be removed.
Loading history...
714
        $this->printTrail('constraint');
715
        $this->printTitle($this->lang['strdrop'], 'pg.constraint.drop');
716
717
        echo '<p>', sprintf(
718
            $this->lang['strconfdropconstraint'],
719
            $this->misc->printVal($_REQUEST['constraint']),
720
            $this->misc->printVal($_REQUEST['table'])
721
        ), "</p>\n";
722
723
        echo '<form action="'.\SUBFOLDER."/src/views/constraints\" method=\"post\">\n";
724
        echo "<input type=\"hidden\" name=\"action\" value=\"drop\" />\n";
725
        echo '<input type="hidden" name="table" value="', htmlspecialchars($_REQUEST['table']), "\" />\n";
726
        echo '<input type="hidden" name="constraint" value="', htmlspecialchars($_REQUEST['constraint']), "\" />\n";
727
        echo '<input type="hidden" name="type" value="', htmlspecialchars($_REQUEST['type']), "\" />\n";
728
        echo $this->misc->form;
729
        echo "<p><input type=\"checkbox\" id=\"cascade\" name=\"cascade\" /> <label for=\"cascade\">{$this->lang['strcascade']}</label></p>\n";
730
        echo "<input type=\"submit\" name=\"drop\" value=\"{$this->lang['strdrop']}\" />\n";
731
        echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />\n";
732
        echo "</form>\n";
733
    }
734
735
    /**
736
     * Try to perform actual drop.
737
     */
738
    public function doDrop()
739
    {
740
        $data = $this->misc->getDatabaseAccessor();
741
742
        $status = $data->dropConstraint($_POST['constraint'], $_POST['table'], $_POST['type'], isset($_POST['cascade']));
743
        if (0 == $status) {
744
            $this->doDefault($this->lang['strconstraintdropped']);
745
        }
746
        $this->doDefault($this->lang['strconstraintdroppedbad']);
747
    }
748
}
749